blob: b49ceb6578e198a18996a6e95d4b2c874f4d101a [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 Schuha5e14192020-01-06 18:02:41 -0800219 return std::make_pair(true, event_loop()->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 Schuha5e14192020-01-06 18:02:41 -0800228 return std::make_pair(true, event_loop()->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 Schuha5e14192020-01-06 18:02:41 -0800238 return std::make_pair(true, event_loop()->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
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_;
289 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800290
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291 monotonic_clock::time_point base_;
292 monotonic_clock::duration repeat_offset_;
293};
294
295class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
296 public:
297 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800298 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700299 ::std::function<void(int)> fn,
300 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800301 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800302 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303
Austin Schuh7d87b672019-12-01 20:23:49 -0800304 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700305
Austin Schuh7d87b672019-12-01 20:23:49 -0800306 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307
308 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800309 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800310 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700311
Austin Schuh39788ff2019-12-01 18:22:57 -0800312 EventScheduler *scheduler_;
313 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700314};
315
316class SimulatedEventLoop : public EventLoop {
317 public:
318 explicit SimulatedEventLoop(
319 EventScheduler *scheduler,
320 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
321 *channels,
322 const Configuration *configuration,
323 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800324 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800325 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800326 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327 scheduler_(scheduler),
328 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800329 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800330 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800331 tid_(tid) {
332 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
333 if (!has_setup_) {
334 Setup();
335 has_setup_ = true;
336 }
337 set_is_running(value);
338 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700339 }
340 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800341 // Trigger any remaining senders or fetchers to be cleared before destroying
342 // the event loop so the book keeping matches.
343 timing_report_sender_.reset();
344
345 // Force everything with a registered fd with epoll to be destroyed now.
346 timers_.clear();
347 phased_loops_.clear();
348 watchers_.clear();
349
Alex Perrycb7da4b2019-08-28 19:35:56 -0700350 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
351 ++it) {
352 if (it->first == this) {
353 raw_event_loops_->erase(it);
354 break;
355 }
356 }
357 }
358
Austin Schuh7d87b672019-12-01 20:23:49 -0800359 std::chrono::nanoseconds send_delay() const { return send_delay_; }
360 void set_send_delay(std::chrono::nanoseconds send_delay) {
361 send_delay_ = send_delay;
362 }
363
Alex Perrycb7da4b2019-08-28 19:35:56 -0700364 ::aos::monotonic_clock::time_point monotonic_now() override {
365 return scheduler_->monotonic_now();
366 }
367
368 ::aos::realtime_clock::time_point realtime_now() override {
369 return scheduler_->realtime_now();
370 }
371
372 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
373
374 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
375
376 void MakeRawWatcher(
377 const Channel *channel,
378 ::std::function<void(const Context &context, const void *message)>
379 watcher) override;
380
381 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800382 CHECK(!is_running());
383 return NewTimer(::std::unique_ptr<TimerHandler>(
384 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385 }
386
387 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
388 const monotonic_clock::duration interval,
389 const monotonic_clock::duration offset =
390 ::std::chrono::seconds(0)) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800391 return NewPhasedLoop(
392 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
393 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394 }
395
396 void OnRun(::std::function<void()> on_run) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800397 scheduler_->ScheduleOnRun(on_run);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700398 }
399
Austin Schuh217a9782019-12-21 23:02:50 -0800400 const Node *node() const override { return node_; }
401
James Kuszmaul3ae42262019-11-08 12:33:41 -0800402 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403 name_ = std::string(name);
404 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800405 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700406
407 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
408
409 void Take(const Channel *channel);
410
Austin Schuh39788ff2019-12-01 18:22:57 -0800411 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700412 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800413 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700414 }
415
Austin Schuh39788ff2019-12-01 18:22:57 -0800416 int priority() const override { return priority_; }
417
418 void Setup() { MaybeScheduleTimingReports(); }
419
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800421 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800422 friend class SimulatedPhasedLoopHandler;
423 friend class SimulatedWatcher;
424
425 void HandleEvent() {
426 while (true) {
427 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
428 break;
429 }
430
431 EventLoopEvent *event = PopEvent();
432 event->HandleEvent();
433 }
434 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800435
Austin Schuh39788ff2019-12-01 18:22:57 -0800436 pid_t GetTid() override { return tid_; }
437
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438 EventScheduler *scheduler_;
439 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
440 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
441 *raw_event_loops_;
442 absl::btree_set<SimpleChannel> taken_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443
444 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800445
446 int priority_ = 0;
447
448 bool has_setup_ = false;
449
Austin Schuh7d87b672019-12-01 20:23:49 -0800450 std::chrono::nanoseconds send_delay_;
451
Austin Schuh217a9782019-12-21 23:02:50 -0800452 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800453 const pid_t tid_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454};
455
Austin Schuh7d87b672019-12-01 20:23:49 -0800456void SimulatedEventLoopFactory::set_send_delay(
457 std::chrono::nanoseconds send_delay) {
458 send_delay_ = send_delay;
459 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
460 raw_event_loops_) {
461 reinterpret_cast<SimulatedEventLoop *>(loop.first)
462 ->set_send_delay(send_delay_);
463 }
464}
465
James Kuszmaul314f1672020-01-03 20:02:08 -0800466std::chrono::nanoseconds SimulatedEventLoopFactory::send_delay() const {
467 return send_delay_;
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) {
Austin Schuha5e14192020-01-06 18:02:41 -0800543 monotonic_clock::time_point event_time =
544 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800545
546 // Messages are queued in order. If we are the first, add ourselves.
547 // Otherwise, don't.
548 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800549 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800550 simulated_event_loop_->AddEvent(&event_);
551
552 DoSchedule(event_time);
553 }
554
555 msgs_.emplace_back(message);
556}
557
558void SimulatedWatcher::HandleEvent() {
559 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
560
561 const monotonic_clock::time_point monotonic_now =
562 simulated_event_loop_->monotonic_now();
Austin Schuhad154822019-12-27 15:45:13 -0800563 Context context = msgs_.front()->context;
564
565 if (context.remote_queue_index == 0xffffffffu) {
566 context.remote_queue_index = context.queue_index;
567 }
568 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
569 context.monotonic_remote_time = context.monotonic_event_time;
570 }
571 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
572 context.realtime_remote_time = context.realtime_event_time;
573 }
574
575 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh7d87b672019-12-01 20:23:49 -0800576
577 msgs_.pop_front();
578 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800579 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800580 simulated_event_loop_->AddEvent(&event_);
581
582 DoSchedule(event_.event_time());
583 } else {
584 token_ = scheduler_->InvalidToken();
585 }
586}
587
588void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
589 token_ =
590 scheduler_->Schedule(event_time + simulated_event_loop_->send_delay(),
591 [this]() { simulated_event_loop_->HandleEvent(); });
592}
593
594void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800595 watcher->SetSimulatedChannel(this);
596 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700597}
598
599::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
600 EventLoop *event_loop) {
601 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
602}
603
Austin Schuh39788ff2019-12-01 18:22:57 -0800604::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
605 EventLoop *event_loop) {
606 ::std::unique_ptr<SimulatedFetcher> fetcher(
607 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700608 fetchers_.push_back(fetcher.get());
609 return ::std::move(fetcher);
610}
611
Austin Schuhad154822019-12-27 15:45:13 -0800612uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
613 const uint32_t queue_index = next_queue_index_.index();
614 message->context.queue_index = queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700615 message->context.data =
616 message->data() + channel()->max_size() - message->context.size;
617 next_queue_index_ = next_queue_index_.Increment();
618
619 latest_message_ = message;
620 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800621 for (SimulatedWatcher *watcher : watchers_) {
622 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700623 }
624 }
625 for (auto &fetcher : fetchers_) {
626 fetcher->Enqueue(message);
627 }
Austin Schuhad154822019-12-27 15:45:13 -0800628
629 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630}
631
632void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
633 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
634}
635
636SimpleChannel::SimpleChannel(const Channel *channel)
637 : name(CHECK_NOTNULL(CHECK_NOTNULL(channel)->name())->str()),
638 type(CHECK_NOTNULL(CHECK_NOTNULL(channel)->type())->str()) {}
639
Austin Schuh39788ff2019-12-01 18:22:57 -0800640SimulatedTimerHandler::SimulatedTimerHandler(
641 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
642 ::std::function<void()> fn)
643 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800644 simulated_event_loop_(simulated_event_loop),
645 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800646 scheduler_(scheduler),
647 token_(scheduler_->InvalidToken()) {}
648
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800649void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
650 monotonic_clock::duration repeat_offset) {
651 Disable();
652 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800653 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800654 base_ = base;
655 repeat_offset_ = repeat_offset;
656 if (base < monotonic_now) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800657 token_ = scheduler_->Schedule(
658 monotonic_now, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800659 } else {
Austin Schuh7d87b672019-12-01 20:23:49 -0800660 token_ = scheduler_->Schedule(
661 base, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800662 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800663 event_.set_event_time(base_);
664 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800665}
666
667void SimulatedTimerHandler::HandleEvent() {
668 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800669 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800670 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
671 // Reschedule.
672 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800673 token_ = scheduler_->Schedule(
674 base_, [this]() { simulated_event_loop_->HandleEvent(); });
675 event_.set_event_time(base_);
676 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800677 } else {
678 token_ = scheduler_->InvalidToken();
679 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800680
Austin Schuh39788ff2019-12-01 18:22:57 -0800681 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800682}
683
Austin Schuh7d87b672019-12-01 20:23:49 -0800684void SimulatedTimerHandler::Disable() {
685 simulated_event_loop_->RemoveEvent(&event_);
686 if (token_ != scheduler_->InvalidToken()) {
687 scheduler_->Deschedule(token_);
688 token_ = scheduler_->InvalidToken();
689 }
690}
691
Austin Schuh39788ff2019-12-01 18:22:57 -0800692SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
693 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
694 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
695 const monotonic_clock::duration offset)
696 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
697 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800698 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800699 scheduler_(scheduler),
700 token_(scheduler_->InvalidToken()) {}
701
Austin Schuh7d87b672019-12-01 20:23:49 -0800702SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
703 if (token_ != scheduler_->InvalidToken()) {
704 scheduler_->Deschedule(token_);
705 token_ = scheduler_->InvalidToken();
706 }
707 simulated_event_loop_->RemoveEvent(&event_);
708}
709
710void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800711 monotonic_clock::time_point monotonic_now =
712 simulated_event_loop_->monotonic_now();
713 Call(
714 [monotonic_now]() { return monotonic_now; },
715 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
716}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800717
Austin Schuh7d87b672019-12-01 20:23:49 -0800718void SimulatedPhasedLoopHandler::Schedule(
719 monotonic_clock::time_point sleep_time) {
720 token_ = scheduler_->Schedule(
721 sleep_time, [this]() { simulated_event_loop_->HandleEvent(); });
722 event_.set_event_time(sleep_time);
723 simulated_event_loop_->AddEvent(&event_);
724}
725
Alex Perrycb7da4b2019-08-28 19:35:56 -0700726void SimulatedEventLoop::Take(const Channel *channel) {
727 CHECK(!is_running()) << ": Cannot add new objects while running.";
728
729 auto result = taken_.insert(SimpleChannel(channel));
730 CHECK(result.second) << ": " << FlatbufferToJson(channel)
731 << " is already being used.";
732}
733
734SimulatedEventLoopFactory::SimulatedEventLoopFactory(
735 const Configuration *configuration)
Austin Schuh217a9782019-12-21 23:02:50 -0800736 : configuration_(CHECK_NOTNULL(configuration)), node_(nullptr) {
737 CHECK(!configuration_->has_nodes())
738 << ": Got a configuration with multiple nodes and no node was selected.";
739}
740
741SimulatedEventLoopFactory::SimulatedEventLoopFactory(
742 const Configuration *configuration, std::string_view node_name)
Austin Schuh0bf5b9e2019-12-30 18:16:09 -0800743 : SimulatedEventLoopFactory(
744 configuration, configuration::GetNode(configuration, node_name)) {}
Austin Schuh217a9782019-12-21 23:02:50 -0800745
Austin Schuh15649d62019-12-28 16:36:38 -0800746SimulatedEventLoopFactory::SimulatedEventLoopFactory(
747 const Configuration *configuration, const Node *node)
748 : configuration_(CHECK_NOTNULL(configuration)), node_(node) {
Austin Schuh0bf5b9e2019-12-30 18:16:09 -0800749 if (node != nullptr) {
750 CHECK(configuration_->has_nodes())
751 << ": Got a configuration with no nodes and node \""
752 << node->name()->string_view() << "\" was selected.";
753 bool found = false;
754 for (const Node *node : *configuration_->nodes()) {
755 if (node == node_) {
756 found = true;
757 break;
758 }
Austin Schuh15649d62019-12-28 16:36:38 -0800759 }
Austin Schuh0bf5b9e2019-12-30 18:16:09 -0800760 CHECK(found) << ": node must be a pointer in the configuration.";
Austin Schuh15649d62019-12-28 16:36:38 -0800761 }
Austin Schuh15649d62019-12-28 16:36:38 -0800762}
763
Alex Perrycb7da4b2019-08-28 19:35:56 -0700764SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
765
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800766::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
767 std::string_view name) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800768 pid_t tid = tid_;
769 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800770 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh217a9782019-12-21 23:02:50 -0800771 &scheduler_, &channels_, configuration_, &raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800772 result->set_name(name);
Austin Schuh7d87b672019-12-01 20:23:49 -0800773 result->set_send_delay(send_delay_);
774 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700775}
776
777void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
778 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
779 raw_event_loops_) {
780 event_loop.second(true);
781 }
782 scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800783 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
784 raw_event_loops_) {
785 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700786 }
787}
788
789void SimulatedEventLoopFactory::Run() {
790 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
791 raw_event_loops_) {
792 event_loop.second(true);
793 }
794 scheduler_.Run();
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
801} // namespace aos