blob: 0d8a4889a62950d03b11b7d512b3846dd1dacddd [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,
Austin Schuhac0771c2020-01-07 18:36:30 -080039 NodeEventLoopFactory *node_event_loop_factory,
Austin Schuh7d87b672019-12-01 20:23:49 -080040 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_;
Austin Schuhac0771c2020-01-07 18:36:30 -080063 NodeEventLoopFactory *node_event_loop_factory_;
Austin Schuh7d87b672019-12-01 20:23:49 -080064 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -080065 SimulatedChannel *simulated_channel_ = nullptr;
66};
Alex Perrycb7da4b2019-08-28 19:35:56 -070067
68class SimulatedChannel {
69 public:
70 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -080071 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -070072 scheduler_(scheduler),
73 next_queue_index_(ipc_lib::QueueIndex::Zero(channel->max_size())) {}
74
75 ~SimulatedChannel() { CHECK_EQ(0u, fetchers_.size()); }
76
77 // Makes a connected raw sender which calls Send below.
78 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
79
80 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -080081 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -070082
83 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -080084 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -080085
Austin Schuh7d87b672019-12-01 20:23:49 -080086 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -080087 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
88 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070089
Austin Schuhad154822019-12-27 15:45:13 -080090 // Sends the message to all the connected receivers and fetchers. Returns the
91 // sent queue index.
92 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -070093
94 // Unregisters a fetcher.
95 void UnregisterFetcher(SimulatedFetcher *fetcher);
96
97 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
98
Austin Schuh39788ff2019-12-01 18:22:57 -080099 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700100
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800101 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700103 }
104
Austin Schuh39788ff2019-12-01 18:22:57 -0800105 const Channel *channel() const { return channel_; }
106
Alex Perrycb7da4b2019-08-28 19:35:56 -0700107 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800108 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700109
110 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800111 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700112
113 // List of all fetchers.
114 ::std::vector<SimulatedFetcher *> fetchers_;
115 std::shared_ptr<SimulatedMessage> latest_message_;
116 EventScheduler *scheduler_;
117
118 ipc_lib::QueueIndex next_queue_index_;
119};
120
121namespace {
122
123// Creates a SimulatedMessage with size bytes of storage.
124// This is a shared_ptr so we don't have to implement refcounting or copying.
125std::shared_ptr<SimulatedMessage> MakeSimulatedMessage(size_t size) {
126 SimulatedMessage *message = reinterpret_cast<SimulatedMessage *>(
127 malloc(sizeof(SimulatedMessage) + size));
128 message->context.size = size;
129 message->context.data = message->data();
130
131 return std::shared_ptr<SimulatedMessage>(message, free);
132}
133
134class SimulatedSender : public RawSender {
135 public:
136 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800137 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800138 simulated_channel_(simulated_channel),
139 event_loop_(event_loop) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700140 ~SimulatedSender() {}
141
142 void *data() override {
143 if (!message_) {
144 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
145 }
146 return message_->data();
147 }
148
149 size_t size() override { return simulated_channel_->max_size(); }
150
Austin Schuhad154822019-12-27 15:45:13 -0800151 bool DoSend(size_t length,
152 aos::monotonic_clock::time_point monotonic_remote_time,
153 aos::realtime_clock::time_point realtime_remote_time,
154 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700155 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuhad154822019-12-27 15:45:13 -0800156 message_->context.monotonic_event_time = event_loop_->monotonic_now();
157 message_->context.monotonic_remote_time = monotonic_remote_time;
158 message_->context.remote_queue_index = remote_queue_index;
159 message_->context.realtime_event_time = event_loop_->realtime_now();
160 message_->context.realtime_remote_time = realtime_remote_time;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700161 CHECK_LE(length, message_->context.size);
162 message_->context.size = length;
163
164 // TODO(austin): Track sending too fast.
Austin Schuhad154822019-12-27 15:45:13 -0800165 sent_queue_index_ = simulated_channel_->Send(message_);
166 monotonic_sent_time_ = event_loop_->monotonic_now();
167 realtime_sent_time_ = event_loop_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700168
169 // Drop the reference to the message so that we allocate a new message for
170 // next time. Otherwise we will continue to reuse the same memory for all
171 // messages and corrupt it.
172 message_.reset();
173 return true;
174 }
175
Austin Schuhad154822019-12-27 15:45:13 -0800176 bool DoSend(const void *msg, size_t size,
177 aos::monotonic_clock::time_point monotonic_remote_time,
178 aos::realtime_clock::time_point realtime_remote_time,
179 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700180 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
181
182 // This is wasteful, but since flatbuffers fill from the back end of the
183 // queue, we need it to be full sized.
184 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
185
186 // Now fill in the message. size is already populated above, and
Austin Schuhac0771c2020-01-07 18:36:30 -0800187 // queue_index will be populated in simulated_channel_. Put this at the
188 // back of the data segment.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700189 memcpy(message_->data() + simulated_channel_->max_size() - size, msg, size);
190
Austin Schuhac0771c2020-01-07 18:36:30 -0800191 return DoSend(size, monotonic_remote_time, realtime_remote_time,
192 remote_queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700193 }
194
Alex Perrycb7da4b2019-08-28 19:35:56 -0700195 private:
196 SimulatedChannel *simulated_channel_;
197 EventLoop *event_loop_;
198
199 std::shared_ptr<SimulatedMessage> message_;
200};
201} // namespace
202
203class SimulatedFetcher : public RawFetcher {
204 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800205 explicit SimulatedFetcher(EventLoop *event_loop,
206 SimulatedChannel *simulated_channel)
207 : RawFetcher(event_loop, simulated_channel->channel()),
208 simulated_channel_(simulated_channel) {}
209 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210
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.
Austin Schuhac0771c2020-01-07 18:36:30 -0800225 if (!msg_ && simulated_channel_->latest_message()) {
226 SetMsg(simulated_channel_->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
Austin Schuhac0771c2020-01-07 18:36:30 -0800263 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700264 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 Schuhac0771c2020-01-07 18:36:30 -0800273 NodeEventLoopFactory *node_event_loop_factory,
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
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800286 SimulatedEventLoop *simulated_event_loop_;
287 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700288 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800289 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700290 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800291
Alex Perrycb7da4b2019-08-28 19:35:56 -0700292 monotonic_clock::time_point base_;
293 monotonic_clock::duration repeat_offset_;
294};
295
296class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
297 public:
298 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhac0771c2020-01-07 18:36:30 -0800299 NodeEventLoopFactory *node_event_loop_factory,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800300 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700301 ::std::function<void(int)> fn,
302 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800303 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800304 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700305
Austin Schuh7d87b672019-12-01 20:23:49 -0800306 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307
Austin Schuh7d87b672019-12-01 20:23:49 -0800308 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309
310 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800311 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800312 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700313
Austin Schuh39788ff2019-12-01 18:22:57 -0800314 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800315 NodeEventLoopFactory *node_event_loop_factory_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800316 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700317};
318
319class SimulatedEventLoop : public EventLoop {
320 public:
321 explicit SimulatedEventLoop(
322 EventScheduler *scheduler,
Austin Schuhac0771c2020-01-07 18:36:30 -0800323 NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700324 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),
Austin Schuhac0771c2020-01-07 18:36:30 -0800332 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700333 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800334 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800335 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800336 tid_(tid) {
337 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
338 if (!has_setup_) {
339 Setup();
340 has_setup_ = true;
341 }
342 set_is_running(value);
343 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700344 }
345 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800346 // Trigger any remaining senders or fetchers to be cleared before destroying
347 // the event loop so the book keeping matches.
348 timing_report_sender_.reset();
349
350 // Force everything with a registered fd with epoll to be destroyed now.
351 timers_.clear();
352 phased_loops_.clear();
353 watchers_.clear();
354
Alex Perrycb7da4b2019-08-28 19:35:56 -0700355 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
356 ++it) {
357 if (it->first == this) {
358 raw_event_loops_->erase(it);
359 break;
360 }
361 }
362 }
363
Austin Schuh7d87b672019-12-01 20:23:49 -0800364 std::chrono::nanoseconds send_delay() const { return send_delay_; }
365 void set_send_delay(std::chrono::nanoseconds send_delay) {
366 send_delay_ = send_delay;
367 }
368
Alex Perrycb7da4b2019-08-28 19:35:56 -0700369 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800370 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700371 }
372
373 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800374 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375 }
376
377 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
378
379 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
380
381 void MakeRawWatcher(
382 const Channel *channel,
383 ::std::function<void(const Context &context, const void *message)>
384 watcher) override;
385
386 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800387 CHECK(!is_running());
Austin Schuhac0771c2020-01-07 18:36:30 -0800388 return NewTimer(::std::unique_ptr<TimerHandler>(new SimulatedTimerHandler(
389 scheduler_, node_event_loop_factory_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700390 }
391
392 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
393 const monotonic_clock::duration interval,
394 const monotonic_clock::duration offset =
395 ::std::chrono::seconds(0)) override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800396 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
397 new SimulatedPhasedLoopHandler(scheduler_, node_event_loop_factory_,
398 this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700399 }
400
401 void OnRun(::std::function<void()> on_run) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800402 scheduler_->ScheduleOnRun(on_run);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403 }
404
Austin Schuh217a9782019-12-21 23:02:50 -0800405 const Node *node() const override { return node_; }
406
James Kuszmaul3ae42262019-11-08 12:33:41 -0800407 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408 name_ = std::string(name);
409 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800410 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411
412 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
413
Austin Schuh39788ff2019-12-01 18:22:57 -0800414 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700415 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800416 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417 }
418
Austin Schuh39788ff2019-12-01 18:22:57 -0800419 int priority() const override { return priority_; }
420
421 void Setup() { MaybeScheduleTimingReports(); }
422
Alex Perrycb7da4b2019-08-28 19:35:56 -0700423 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800424 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800425 friend class SimulatedPhasedLoopHandler;
426 friend class SimulatedWatcher;
427
428 void HandleEvent() {
429 while (true) {
430 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
431 break;
432 }
433
434 EventLoopEvent *event = PopEvent();
435 event->HandleEvent();
436 }
437 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800438
Austin Schuh39788ff2019-12-01 18:22:57 -0800439 pid_t GetTid() override { return tid_; }
440
Alex Perrycb7da4b2019-08-28 19:35:56 -0700441 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800442 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
444 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
445 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446
447 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800448
449 int priority_ = 0;
450
451 bool has_setup_ = false;
452
Austin Schuh7d87b672019-12-01 20:23:49 -0800453 std::chrono::nanoseconds send_delay_;
454
Austin Schuh217a9782019-12-21 23:02:50 -0800455 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800456 const pid_t tid_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457};
458
Austin Schuh7d87b672019-12-01 20:23:49 -0800459void SimulatedEventLoopFactory::set_send_delay(
460 std::chrono::nanoseconds send_delay) {
461 send_delay_ = send_delay;
462 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
463 raw_event_loops_) {
464 reinterpret_cast<SimulatedEventLoop *>(loop.first)
465 ->set_send_delay(send_delay_);
466 }
467}
468
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469void SimulatedEventLoop::MakeRawWatcher(
470 const Channel *channel,
471 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800472 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800473
Austin Schuhac0771c2020-01-07 18:36:30 -0800474 std::unique_ptr<SimulatedWatcher> shm_watcher(new SimulatedWatcher(
475 this, scheduler_, node_event_loop_factory_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800476
477 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
478 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479}
480
481std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
482 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800483 TakeSender(channel);
484
Alex Perrycb7da4b2019-08-28 19:35:56 -0700485 return GetSimulatedChannel(channel)->MakeRawSender(this);
486}
487
488std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
489 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800490 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800491
Austin Schuhca4828c2019-12-28 14:21:35 -0800492 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
493 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
494 << "\", \"type\": \"" << channel->type()->string_view()
495 << "\" } is not able to be fetched on this node. Check your "
496 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800497 }
498
Austin Schuh39788ff2019-12-01 18:22:57 -0800499 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500}
501
502SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
503 const Channel *channel) {
504 auto it = channels_->find(SimpleChannel(channel));
505 if (it == channels_->end()) {
506 it = channels_
507 ->emplace(SimpleChannel(channel),
508 std::unique_ptr<SimulatedChannel>(
509 new SimulatedChannel(channel, scheduler_)))
510 .first;
511 }
512 return it->second.get();
513}
514
Austin Schuh7d87b672019-12-01 20:23:49 -0800515SimulatedWatcher::SimulatedWatcher(
516 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuhac0771c2020-01-07 18:36:30 -0800517 NodeEventLoopFactory *node_event_loop_factory, const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800518 std::function<void(const Context &context, const void *message)> fn)
519 : WatcherState(simulated_event_loop, channel, std::move(fn)),
520 simulated_event_loop_(simulated_event_loop),
521 event_(this),
522 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800523 node_event_loop_factory_(node_event_loop_factory),
Austin Schuh7d87b672019-12-01 20:23:49 -0800524 token_(scheduler_->InvalidToken()) {}
525
526SimulatedWatcher::~SimulatedWatcher() {
527 simulated_event_loop_->RemoveEvent(&event_);
528 if (token_ != scheduler_->InvalidToken()) {
529 scheduler_->Deschedule(token_);
530 }
531 simulated_channel_->RemoveWatcher(this);
532}
533
534void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800535 monotonic_clock::time_point event_time =
536 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800537
538 // Messages are queued in order. If we are the first, add ourselves.
539 // Otherwise, don't.
540 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800541 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800542 simulated_event_loop_->AddEvent(&event_);
543
544 DoSchedule(event_time);
545 }
546
547 msgs_.emplace_back(message);
548}
549
550void SimulatedWatcher::HandleEvent() {
551 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
552
553 const monotonic_clock::time_point monotonic_now =
554 simulated_event_loop_->monotonic_now();
Austin Schuhad154822019-12-27 15:45:13 -0800555 Context context = msgs_.front()->context;
556
557 if (context.remote_queue_index == 0xffffffffu) {
558 context.remote_queue_index = context.queue_index;
559 }
560 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
561 context.monotonic_remote_time = context.monotonic_event_time;
562 }
563 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
564 context.realtime_remote_time = context.realtime_event_time;
565 }
566
567 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh7d87b672019-12-01 20:23:49 -0800568
569 msgs_.pop_front();
570 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800571 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800572 simulated_event_loop_->AddEvent(&event_);
573
574 DoSchedule(event_.event_time());
575 } else {
576 token_ = scheduler_->InvalidToken();
577 }
578}
579
580void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuhac0771c2020-01-07 18:36:30 -0800581 token_ = scheduler_->Schedule(
582 node_event_loop_factory_->ToDistributedClock(
583 event_time + simulated_event_loop_->send_delay()),
584 [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuh7d87b672019-12-01 20:23:49 -0800585}
586
587void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800588 watcher->SetSimulatedChannel(this);
589 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590}
591
592::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
593 EventLoop *event_loop) {
594 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
595}
596
Austin Schuh39788ff2019-12-01 18:22:57 -0800597::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
598 EventLoop *event_loop) {
599 ::std::unique_ptr<SimulatedFetcher> fetcher(
600 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700601 fetchers_.push_back(fetcher.get());
602 return ::std::move(fetcher);
603}
604
Austin Schuhad154822019-12-27 15:45:13 -0800605uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
606 const uint32_t queue_index = next_queue_index_.index();
607 message->context.queue_index = queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700608 message->context.data =
609 message->data() + channel()->max_size() - message->context.size;
610 next_queue_index_ = next_queue_index_.Increment();
611
612 latest_message_ = message;
613 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800614 for (SimulatedWatcher *watcher : watchers_) {
615 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700616 }
617 }
618 for (auto &fetcher : fetchers_) {
619 fetcher->Enqueue(message);
620 }
Austin Schuhad154822019-12-27 15:45:13 -0800621
622 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700623}
624
625void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
626 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
627}
628
Austin Schuh39788ff2019-12-01 18:22:57 -0800629SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuhac0771c2020-01-07 18:36:30 -0800630 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
631 SimulatedEventLoop *simulated_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800632 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800633 simulated_event_loop_(simulated_event_loop),
634 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800635 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800636 node_event_loop_factory_(node_event_loop_factory),
Austin Schuh39788ff2019-12-01 18:22:57 -0800637 token_(scheduler_->InvalidToken()) {}
638
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800639void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
640 monotonic_clock::duration repeat_offset) {
641 Disable();
642 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800643 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800644 base_ = base;
645 repeat_offset_ = repeat_offset;
646 if (base < monotonic_now) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800647 token_ = scheduler_->Schedule(
Austin Schuhac0771c2020-01-07 18:36:30 -0800648 node_event_loop_factory_->ToDistributedClock(monotonic_now),
649 [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800650 } else {
Austin Schuh7d87b672019-12-01 20:23:49 -0800651 token_ = scheduler_->Schedule(
Austin Schuhac0771c2020-01-07 18:36:30 -0800652 node_event_loop_factory_->ToDistributedClock(base),
653 [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800654 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800655 event_.set_event_time(base_);
656 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800657}
658
659void SimulatedTimerHandler::HandleEvent() {
660 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800661 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800662 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
663 // Reschedule.
664 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800665 token_ = scheduler_->Schedule(
Austin Schuhac0771c2020-01-07 18:36:30 -0800666 node_event_loop_factory_->ToDistributedClock(base_),
667 [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuh7d87b672019-12-01 20:23:49 -0800668 event_.set_event_time(base_);
669 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800670 } else {
671 token_ = scheduler_->InvalidToken();
672 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800673
Austin Schuh39788ff2019-12-01 18:22:57 -0800674 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800675}
676
Austin Schuh7d87b672019-12-01 20:23:49 -0800677void SimulatedTimerHandler::Disable() {
678 simulated_event_loop_->RemoveEvent(&event_);
679 if (token_ != scheduler_->InvalidToken()) {
680 scheduler_->Deschedule(token_);
681 token_ = scheduler_->InvalidToken();
682 }
683}
684
Austin Schuh39788ff2019-12-01 18:22:57 -0800685SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuhac0771c2020-01-07 18:36:30 -0800686 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
687 SimulatedEventLoop *simulated_event_loop, ::std::function<void(int)> fn,
688 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800689 const monotonic_clock::duration offset)
690 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
691 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800692 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800693 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800694 node_event_loop_factory_(node_event_loop_factory),
Austin Schuh39788ff2019-12-01 18:22:57 -0800695 token_(scheduler_->InvalidToken()) {}
696
Austin Schuh7d87b672019-12-01 20:23:49 -0800697SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
698 if (token_ != scheduler_->InvalidToken()) {
699 scheduler_->Deschedule(token_);
700 token_ = scheduler_->InvalidToken();
701 }
702 simulated_event_loop_->RemoveEvent(&event_);
703}
704
705void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800706 monotonic_clock::time_point monotonic_now =
707 simulated_event_loop_->monotonic_now();
708 Call(
709 [monotonic_now]() { return monotonic_now; },
710 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
711}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800712
Austin Schuh7d87b672019-12-01 20:23:49 -0800713void SimulatedPhasedLoopHandler::Schedule(
714 monotonic_clock::time_point sleep_time) {
715 token_ = scheduler_->Schedule(
Austin Schuhac0771c2020-01-07 18:36:30 -0800716 node_event_loop_factory_->ToDistributedClock(sleep_time),
717 [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuh7d87b672019-12-01 20:23:49 -0800718 event_.set_event_time(sleep_time);
719 simulated_event_loop_->AddEvent(&event_);
720}
721
Austin Schuhac0771c2020-01-07 18:36:30 -0800722NodeEventLoopFactory::NodeEventLoopFactory(
723 EventScheduler *scheduler, SimulatedEventLoopFactory *factory,
724 const Node *node,
725 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
726 *raw_event_loops)
727 : scheduler_(scheduler),
728 factory_(factory),
729 node_(node),
730 raw_event_loops_(raw_event_loops) {}
731
Alex Perrycb7da4b2019-08-28 19:35:56 -0700732SimulatedEventLoopFactory::SimulatedEventLoopFactory(
733 const Configuration *configuration)
Austin Schuhac0771c2020-01-07 18:36:30 -0800734 : configuration_(CHECK_NOTNULL(configuration)) {
735 if (configuration::MultiNode(configuration_)) {
736 for (const Node *node : *configuration->nodes()) {
737 nodes_.emplace_back(node);
Austin Schuh15649d62019-12-28 16:36:38 -0800738 }
Austin Schuhac0771c2020-01-07 18:36:30 -0800739 } else {
740 nodes_.emplace_back(nullptr);
741 }
742
743 for (const Node *node : nodes_) {
744 node_factories_.emplace_back(
745 new NodeEventLoopFactory(&scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -0800746 }
Austin Schuh15649d62019-12-28 16:36:38 -0800747}
748
Alex Perrycb7da4b2019-08-28 19:35:56 -0700749SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
750
Austin Schuhac0771c2020-01-07 18:36:30 -0800751NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
752 const Node *node) {
753 auto result = std::find_if(
754 node_factories_.begin(), node_factories_.end(),
755 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
756 return node_factory->node() == node;
757 });
758
759 CHECK(result != node_factories_.end())
760 << ": Failed to find node " << FlatbufferToJson(node);
761
762 return result->get();
763}
764
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800765::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -0800766 std::string_view name, const Node *node) {
767 if (node == nullptr) {
768 CHECK(!configuration::MultiNode(configuration()))
769 << ": Can't make a single node event loop in a multi-node world.";
770 } else {
771 CHECK(configuration::MultiNode(configuration()))
772 << ": Can't make a multi-node event loop in a single-node world.";
773 }
774 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
775}
776
777::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800778 std::string_view name) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800779 pid_t tid = tid_;
780 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800781 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -0800782 scheduler_, this, &channels_, factory_->configuration(), raw_event_loops_,
783 node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800784 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -0800785 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -0800786 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700787}
788
789void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
790 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
791 raw_event_loops_) {
792 event_loop.second(true);
793 }
794 scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800795 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
796 raw_event_loops_) {
797 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700798 }
799}
800
801void SimulatedEventLoopFactory::Run() {
802 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
803 raw_event_loops_) {
804 event_loop.second(true);
805 }
806 scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -0800807 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
808 raw_event_loops_) {
809 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700810 }
811}
812
813} // namespace aos