blob: 3f6abd388391891402ddffdf98bf84f5099ac04f [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>
5
6#include "absl/container/btree_map.h"
7#include "absl/container/btree_set.h"
8#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 {
18 char data alignas(32);
19 };
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
31class SimulatedFetcher;
32
33class SimulatedChannel {
34 public:
35 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler)
36 : channel_(CopyFlatBuffer(channel)),
37 scheduler_(scheduler),
38 next_queue_index_(ipc_lib::QueueIndex::Zero(channel->max_size())) {}
39
40 ~SimulatedChannel() { CHECK_EQ(0u, fetchers_.size()); }
41
42 // Makes a connected raw sender which calls Send below.
43 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
44
45 // Makes a connected raw fetcher.
46 ::std::unique_ptr<RawFetcher> MakeRawFetcher();
47
48 // Registers a watcher for the queue.
49 void MakeRawWatcher(
50 ::std::function<void(const Context &context, const void *message)>
51 watcher);
52
53 // Sends the message to all the connected receivers and fetchers.
54 void Send(std::shared_ptr<SimulatedMessage> message);
55
56 // Unregisters a fetcher.
57 void UnregisterFetcher(SimulatedFetcher *fetcher);
58
59 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
60
61 size_t max_size() const { return channel_.message().max_size(); }
62
63 const absl::string_view name() const {
64 return channel_.message().name()->string_view();
65 }
66
67 const Channel *channel() const { return &channel_.message(); }
68
69 private:
70 const FlatbufferDetachedBuffer<Channel> channel_;
71
72 // List of all watchers.
73 ::std::vector<
74 std::function<void(const Context &context, const void *message)>>
75 watchers_;
76
77 // List of all fetchers.
78 ::std::vector<SimulatedFetcher *> fetchers_;
79 std::shared_ptr<SimulatedMessage> latest_message_;
80 EventScheduler *scheduler_;
81
82 ipc_lib::QueueIndex next_queue_index_;
83};
84
85namespace {
86
87// Creates a SimulatedMessage with size bytes of storage.
88// This is a shared_ptr so we don't have to implement refcounting or copying.
89std::shared_ptr<SimulatedMessage> MakeSimulatedMessage(size_t size) {
90 SimulatedMessage *message = reinterpret_cast<SimulatedMessage *>(
91 malloc(sizeof(SimulatedMessage) + size));
92 message->context.size = size;
93 message->context.data = message->data();
94
95 return std::shared_ptr<SimulatedMessage>(message, free);
96}
97
98class SimulatedSender : public RawSender {
99 public:
100 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh54cf95f2019-11-29 13:14:18 -0800101 : RawSender(simulated_channel->channel()),
102 simulated_channel_(simulated_channel),
103 event_loop_(event_loop) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700104 ~SimulatedSender() {}
105
106 void *data() override {
107 if (!message_) {
108 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
109 }
110 return message_->data();
111 }
112
113 size_t size() override { return simulated_channel_->max_size(); }
114
115 bool Send(size_t length) override {
116 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
117 message_->context.monotonic_sent_time = event_loop_->monotonic_now();
118 message_->context.realtime_sent_time = event_loop_->realtime_now();
119 CHECK_LE(length, message_->context.size);
120 message_->context.size = length;
121
122 // TODO(austin): Track sending too fast.
123 simulated_channel_->Send(message_);
124
125 // Drop the reference to the message so that we allocate a new message for
126 // next time. Otherwise we will continue to reuse the same memory for all
127 // messages and corrupt it.
128 message_.reset();
129 return true;
130 }
131
Austin Schuh4726ce92019-11-29 13:23:18 -0800132 bool Send(const void *msg, size_t size) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
134
135 // This is wasteful, but since flatbuffers fill from the back end of the
136 // queue, we need it to be full sized.
137 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
138
139 // Now fill in the message. size is already populated above, and
140 // queue_index will be populated in queue_. Put this at the back of the
141 // data segment.
142 memcpy(message_->data() + simulated_channel_->max_size() - size, msg, size);
143
144 return Send(size);
145 }
146
James Kuszmaul3ae42262019-11-08 12:33:41 -0800147 const std::string_view name() const override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700148 return simulated_channel_->name();
149 }
150
151 private:
152 SimulatedChannel *simulated_channel_;
153 EventLoop *event_loop_;
154
155 std::shared_ptr<SimulatedMessage> message_;
156};
157} // namespace
158
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800159class SimulatedEventLoop;
160
Alex Perrycb7da4b2019-08-28 19:35:56 -0700161class SimulatedFetcher : public RawFetcher {
162 public:
Austin Schuh54cf95f2019-11-29 13:14:18 -0800163 explicit SimulatedFetcher(SimulatedChannel *queue)
164 : RawFetcher(queue->channel()), queue_(queue) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700165 ~SimulatedFetcher() { queue_->UnregisterFetcher(this); }
166
167 bool FetchNext() override {
168 if (msgs_.size() == 0) return false;
169
170 SetMsg(msgs_.front());
171 msgs_.pop_front();
172 return true;
173 }
174
175 bool Fetch() override {
176 if (msgs_.size() == 0) {
177 if (!msg_ && queue_->latest_message()) {
178 SetMsg(queue_->latest_message());
179 return true;
180 } else {
181 return false;
182 }
183 }
184
185 // We've had a message enqueued, so we don't need to go looking for the
186 // latest message from before we started.
187 SetMsg(msgs_.back());
188 msgs_.clear();
189 return true;
190 }
191
192 private:
193 friend class SimulatedChannel;
194
195 // Updates the state inside RawFetcher to point to the data in msg_.
196 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
197 msg_ = msg;
198 data_ = msg_->context.data;
199 context_ = msg_->context;
200 }
201
202 // Internal method for Simulation to add a message to the buffer.
203 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
204 msgs_.emplace_back(buffer);
205 }
206
207 SimulatedChannel *queue_;
208 std::shared_ptr<SimulatedMessage> msg_;
209
210 // Messages queued up but not in use.
211 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
212};
213
214class SimulatedTimerHandler : public TimerHandler {
215 public:
216 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800217 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700218 ::std::function<void()> fn)
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800219 : scheduler_(scheduler),
220 token_(scheduler_->InvalidToken()),
221 simulated_event_loop_(simulated_event_loop),
222 fn_(fn) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700223 ~SimulatedTimerHandler() {}
224
225 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800226 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700227
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800228 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700229
230 void Disable() override {
231 if (token_ != scheduler_->InvalidToken()) {
232 scheduler_->Deschedule(token_);
233 token_ = scheduler_->InvalidToken();
234 }
235 }
236
237 ::aos::monotonic_clock::time_point monotonic_now() const {
238 return scheduler_->monotonic_now();
239 }
240
241 private:
242 EventScheduler *scheduler_;
243 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800244
245 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700246 // Function to be run on the thread
247 ::std::function<void()> fn_;
248 monotonic_clock::time_point base_;
249 monotonic_clock::duration repeat_offset_;
250};
251
252class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
253 public:
254 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800255 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256 ::std::function<void(int)> fn,
257 const monotonic_clock::duration interval,
258 const monotonic_clock::duration offset)
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800259 : simulated_timer_handler_(scheduler, simulated_event_loop,
260 [this]() { HandleTimerWakeup(); }),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700261 phased_loop_(interval, simulated_timer_handler_.monotonic_now(),
262 offset),
263 fn_(fn) {
264 // TODO(austin): This assumes time doesn't change between when the
265 // constructor is called and when we start running. It's probably a safe
266 // assumption.
267 Reschedule();
268 }
269
270 void HandleTimerWakeup() {
271 fn_(cycles_elapsed_);
272 Reschedule();
273 }
274
275 void set_interval_and_offset(
276 const monotonic_clock::duration interval,
277 const monotonic_clock::duration offset) override {
278 phased_loop_.set_interval_and_offset(interval, offset);
279 }
280
281 void Reschedule() {
282 cycles_elapsed_ =
283 phased_loop_.Iterate(simulated_timer_handler_.monotonic_now());
284 simulated_timer_handler_.Setup(phased_loop_.sleep_time(),
285 ::aos::monotonic_clock::zero());
286 }
287
288 private:
289 SimulatedTimerHandler simulated_timer_handler_;
290
291 time::PhasedLoop phased_loop_;
292
293 int cycles_elapsed_ = 1;
294
295 ::std::function<void(int)> fn_;
296};
297
298class SimulatedEventLoop : public EventLoop {
299 public:
300 explicit SimulatedEventLoop(
301 EventScheduler *scheduler,
302 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
303 *channels,
304 const Configuration *configuration,
305 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
306 *raw_event_loops)
307 : EventLoop(configuration),
308 scheduler_(scheduler),
309 channels_(channels),
310 raw_event_loops_(raw_event_loops) {
311 raw_event_loops_->push_back(
312 std::make_pair(this, [this](bool value) { set_is_running(value); }));
313 }
314 ~SimulatedEventLoop() override {
315 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
316 ++it) {
317 if (it->first == this) {
318 raw_event_loops_->erase(it);
319 break;
320 }
321 }
322 }
323
324 ::aos::monotonic_clock::time_point monotonic_now() override {
325 return scheduler_->monotonic_now();
326 }
327
328 ::aos::realtime_clock::time_point realtime_now() override {
329 return scheduler_->realtime_now();
330 }
331
332 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
333
334 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
335
336 void MakeRawWatcher(
337 const Channel *channel,
338 ::std::function<void(const Context &context, const void *message)>
339 watcher) override;
340
341 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800342 timers_.emplace_back(new SimulatedTimerHandler(scheduler_, this, callback));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343 return timers_.back().get();
344 }
345
346 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
347 const monotonic_clock::duration interval,
348 const monotonic_clock::duration offset =
349 ::std::chrono::seconds(0)) override {
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800350 phased_loops_.emplace_back(new SimulatedPhasedLoopHandler(
351 scheduler_, this, callback, interval, offset));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700352 return phased_loops_.back().get();
353 }
354
355 void OnRun(::std::function<void()> on_run) override {
356 scheduler_->Schedule(scheduler_->monotonic_now(), on_run);
357 }
358
James Kuszmaul3ae42262019-11-08 12:33:41 -0800359 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360 name_ = std::string(name);
361 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800362 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700363
364 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
365
366 void Take(const Channel *channel);
367
368 void SetRuntimeRealtimePriority(int /*priority*/) override {
369 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
370 }
371
372 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800373 friend class SimulatedTimerHandler;
374
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375 EventScheduler *scheduler_;
376 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
377 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
378 *raw_event_loops_;
379 absl::btree_set<SimpleChannel> taken_;
380 ::std::vector<std::unique_ptr<TimerHandler>> timers_;
381 ::std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
382
383 ::std::string name_;
384};
385
386void SimulatedEventLoop::MakeRawWatcher(
387 const Channel *channel,
388 std::function<void(const Context &channel, const void *message)> watcher) {
Austin Schuh54cf95f2019-11-29 13:14:18 -0800389 ValidateChannel(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700390 Take(channel);
391 GetSimulatedChannel(channel)->MakeRawWatcher(watcher);
392}
393
394std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
395 const Channel *channel) {
Austin Schuh54cf95f2019-11-29 13:14:18 -0800396 ValidateChannel(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700397 Take(channel);
398 return GetSimulatedChannel(channel)->MakeRawSender(this);
399}
400
401std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
402 const Channel *channel) {
Austin Schuh54cf95f2019-11-29 13:14:18 -0800403 ValidateChannel(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700404 return GetSimulatedChannel(channel)->MakeRawFetcher();
405}
406
407SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
408 const Channel *channel) {
409 auto it = channels_->find(SimpleChannel(channel));
410 if (it == channels_->end()) {
411 it = channels_
412 ->emplace(SimpleChannel(channel),
413 std::unique_ptr<SimulatedChannel>(
414 new SimulatedChannel(channel, scheduler_)))
415 .first;
416 }
417 return it->second.get();
418}
419
420void SimulatedChannel::MakeRawWatcher(
421 ::std::function<void(const Context &context, const void *message)>
422 watcher) {
423 watchers_.push_back(watcher);
424}
425
426::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
427 EventLoop *event_loop) {
428 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
429}
430
431::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher() {
432 ::std::unique_ptr<SimulatedFetcher> fetcher(new SimulatedFetcher(this));
433 fetchers_.push_back(fetcher.get());
434 return ::std::move(fetcher);
435}
436
437void SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
438 message->context.queue_index = next_queue_index_.index();
439 message->context.data =
440 message->data() + channel()->max_size() - message->context.size;
441 next_queue_index_ = next_queue_index_.Increment();
442
443 latest_message_ = message;
444 if (scheduler_->is_running()) {
445 for (auto &watcher : watchers_) {
446 scheduler_->Schedule(scheduler_->monotonic_now(), [watcher, message]() {
447 watcher(message->context, message->context.data);
448 });
449 }
450 }
451 for (auto &fetcher : fetchers_) {
452 fetcher->Enqueue(message);
453 }
454}
455
456void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
457 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
458}
459
460SimpleChannel::SimpleChannel(const Channel *channel)
461 : name(CHECK_NOTNULL(CHECK_NOTNULL(channel)->name())->str()),
462 type(CHECK_NOTNULL(CHECK_NOTNULL(channel)->type())->str()) {}
463
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800464void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
465 monotonic_clock::duration repeat_offset) {
466 Disable();
467 const ::aos::monotonic_clock::time_point monotonic_now =
468 scheduler_->monotonic_now();
469 base_ = base;
470 repeat_offset_ = repeat_offset;
471 if (base < monotonic_now) {
472 token_ = scheduler_->Schedule(monotonic_now, [this]() { HandleEvent(); });
473 } else {
474 token_ = scheduler_->Schedule(base, [this]() { HandleEvent(); });
475 }
476}
477
478void SimulatedTimerHandler::HandleEvent() {
479 const ::aos::monotonic_clock::time_point monotonic_now =
480 scheduler_->monotonic_now();
481 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
482 // Reschedule.
483 while (base_ <= monotonic_now) base_ += repeat_offset_;
484 token_ = scheduler_->Schedule(base_, [this]() { HandleEvent(); });
485 } else {
486 token_ = scheduler_->InvalidToken();
487 }
488 // The scheduler is perfect, so we will always wake up on time.
489 simulated_event_loop_->context_.monotonic_sent_time =
490 scheduler_->monotonic_now();
491 simulated_event_loop_->context_.realtime_sent_time = realtime_clock::min_time;
492 simulated_event_loop_->context_.queue_index = 0;
493 simulated_event_loop_->context_.size = 0;
494 simulated_event_loop_->context_.data = nullptr;
495
496 fn_();
497}
498
499
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500void SimulatedEventLoop::Take(const Channel *channel) {
501 CHECK(!is_running()) << ": Cannot add new objects while running.";
502
503 auto result = taken_.insert(SimpleChannel(channel));
504 CHECK(result.second) << ": " << FlatbufferToJson(channel)
505 << " is already being used.";
506}
507
508SimulatedEventLoopFactory::SimulatedEventLoopFactory(
509 const Configuration *configuration)
510 : configuration_(configuration) {}
511SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
512
513::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop() {
514 return ::std::unique_ptr<EventLoop>(new SimulatedEventLoop(
515 &scheduler_, &channels_, configuration_, &raw_event_loops_));
516}
517
518void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
519 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
520 raw_event_loops_) {
521 event_loop.second(true);
522 }
523 scheduler_.RunFor(duration);
524 if (!scheduler_.is_running()) {
525 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
526 raw_event_loops_) {
527 event_loop.second(false);
528 }
529 }
530}
531
532void SimulatedEventLoopFactory::Run() {
533 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
534 raw_event_loops_) {
535 event_loop.second(true);
536 }
537 scheduler_.Run();
538 if (!scheduler_.is_running()) {
539 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
540 raw_event_loops_) {
541 event_loop.second(false);
542 }
543 }
544}
545
546} // namespace aos