blob: f65e75d8a841c6062ed220df6997e109d1996dc5 [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
159class SimulatedFetcher : public RawFetcher {
160 public:
Austin Schuh54cf95f2019-11-29 13:14:18 -0800161 explicit SimulatedFetcher(SimulatedChannel *queue)
162 : RawFetcher(queue->channel()), queue_(queue) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163 ~SimulatedFetcher() { queue_->UnregisterFetcher(this); }
164
165 bool FetchNext() override {
166 if (msgs_.size() == 0) return false;
167
168 SetMsg(msgs_.front());
169 msgs_.pop_front();
170 return true;
171 }
172
173 bool Fetch() override {
174 if (msgs_.size() == 0) {
175 if (!msg_ && queue_->latest_message()) {
176 SetMsg(queue_->latest_message());
177 return true;
178 } else {
179 return false;
180 }
181 }
182
183 // We've had a message enqueued, so we don't need to go looking for the
184 // latest message from before we started.
185 SetMsg(msgs_.back());
186 msgs_.clear();
187 return true;
188 }
189
190 private:
191 friend class SimulatedChannel;
192
193 // Updates the state inside RawFetcher to point to the data in msg_.
194 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
195 msg_ = msg;
196 data_ = msg_->context.data;
197 context_ = msg_->context;
198 }
199
200 // Internal method for Simulation to add a message to the buffer.
201 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
202 msgs_.emplace_back(buffer);
203 }
204
205 SimulatedChannel *queue_;
206 std::shared_ptr<SimulatedMessage> msg_;
207
208 // Messages queued up but not in use.
209 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
210};
211
212class SimulatedTimerHandler : public TimerHandler {
213 public:
214 explicit SimulatedTimerHandler(EventScheduler *scheduler,
215 ::std::function<void()> fn)
216 : scheduler_(scheduler), token_(scheduler_->InvalidToken()), fn_(fn) {}
217 ~SimulatedTimerHandler() {}
218
219 void Setup(monotonic_clock::time_point base,
220 monotonic_clock::duration repeat_offset) override {
221 Disable();
222 const ::aos::monotonic_clock::time_point monotonic_now =
223 scheduler_->monotonic_now();
224 base_ = base;
225 repeat_offset_ = repeat_offset;
226 if (base < monotonic_now) {
227 token_ = scheduler_->Schedule(monotonic_now, [this]() { HandleEvent(); });
228 } else {
229 token_ = scheduler_->Schedule(base, [this]() { HandleEvent(); });
230 }
231 }
232
233 void HandleEvent() {
234 const ::aos::monotonic_clock::time_point monotonic_now =
235 scheduler_->monotonic_now();
236 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
237 // Reschedule.
238 while (base_ <= monotonic_now) base_ += repeat_offset_;
239 token_ = scheduler_->Schedule(base_, [this]() { HandleEvent(); });
240 } else {
241 token_ = scheduler_->InvalidToken();
242 }
243 fn_();
244 }
245
246 void Disable() override {
247 if (token_ != scheduler_->InvalidToken()) {
248 scheduler_->Deschedule(token_);
249 token_ = scheduler_->InvalidToken();
250 }
251 }
252
253 ::aos::monotonic_clock::time_point monotonic_now() const {
254 return scheduler_->monotonic_now();
255 }
256
257 private:
258 EventScheduler *scheduler_;
259 EventScheduler::Token token_;
260 // Function to be run on the thread
261 ::std::function<void()> fn_;
262 monotonic_clock::time_point base_;
263 monotonic_clock::duration repeat_offset_;
264};
265
266class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
267 public:
268 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
269 ::std::function<void(int)> fn,
270 const monotonic_clock::duration interval,
271 const monotonic_clock::duration offset)
272 : simulated_timer_handler_(scheduler, [this]() { HandleTimerWakeup(); }),
273 phased_loop_(interval, simulated_timer_handler_.monotonic_now(),
274 offset),
275 fn_(fn) {
276 // TODO(austin): This assumes time doesn't change between when the
277 // constructor is called and when we start running. It's probably a safe
278 // assumption.
279 Reschedule();
280 }
281
282 void HandleTimerWakeup() {
283 fn_(cycles_elapsed_);
284 Reschedule();
285 }
286
287 void set_interval_and_offset(
288 const monotonic_clock::duration interval,
289 const monotonic_clock::duration offset) override {
290 phased_loop_.set_interval_and_offset(interval, offset);
291 }
292
293 void Reschedule() {
294 cycles_elapsed_ =
295 phased_loop_.Iterate(simulated_timer_handler_.monotonic_now());
296 simulated_timer_handler_.Setup(phased_loop_.sleep_time(),
297 ::aos::monotonic_clock::zero());
298 }
299
300 private:
301 SimulatedTimerHandler simulated_timer_handler_;
302
303 time::PhasedLoop phased_loop_;
304
305 int cycles_elapsed_ = 1;
306
307 ::std::function<void(int)> fn_;
308};
309
310class SimulatedEventLoop : public EventLoop {
311 public:
312 explicit SimulatedEventLoop(
313 EventScheduler *scheduler,
314 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
315 *channels,
316 const Configuration *configuration,
317 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
318 *raw_event_loops)
319 : EventLoop(configuration),
320 scheduler_(scheduler),
321 channels_(channels),
322 raw_event_loops_(raw_event_loops) {
323 raw_event_loops_->push_back(
324 std::make_pair(this, [this](bool value) { set_is_running(value); }));
325 }
326 ~SimulatedEventLoop() override {
327 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
328 ++it) {
329 if (it->first == this) {
330 raw_event_loops_->erase(it);
331 break;
332 }
333 }
334 }
335
336 ::aos::monotonic_clock::time_point monotonic_now() override {
337 return scheduler_->monotonic_now();
338 }
339
340 ::aos::realtime_clock::time_point realtime_now() override {
341 return scheduler_->realtime_now();
342 }
343
344 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
345
346 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
347
348 void MakeRawWatcher(
349 const Channel *channel,
350 ::std::function<void(const Context &context, const void *message)>
351 watcher) override;
352
353 TimerHandler *AddTimer(::std::function<void()> callback) override {
354 timers_.emplace_back(new SimulatedTimerHandler(scheduler_, callback));
355 return timers_.back().get();
356 }
357
358 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
359 const monotonic_clock::duration interval,
360 const monotonic_clock::duration offset =
361 ::std::chrono::seconds(0)) override {
362 phased_loops_.emplace_back(
363 new SimulatedPhasedLoopHandler(scheduler_, callback, interval, offset));
364 return phased_loops_.back().get();
365 }
366
367 void OnRun(::std::function<void()> on_run) override {
368 scheduler_->Schedule(scheduler_->monotonic_now(), on_run);
369 }
370
James Kuszmaul3ae42262019-11-08 12:33:41 -0800371 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700372 name_ = std::string(name);
373 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800374 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375
376 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
377
378 void Take(const Channel *channel);
379
380 void SetRuntimeRealtimePriority(int /*priority*/) override {
381 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
382 }
383
384 private:
385 EventScheduler *scheduler_;
386 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
387 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
388 *raw_event_loops_;
389 absl::btree_set<SimpleChannel> taken_;
390 ::std::vector<std::unique_ptr<TimerHandler>> timers_;
391 ::std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
392
393 ::std::string name_;
394};
395
396void SimulatedEventLoop::MakeRawWatcher(
397 const Channel *channel,
398 std::function<void(const Context &channel, const void *message)> watcher) {
Austin Schuh54cf95f2019-11-29 13:14:18 -0800399 ValidateChannel(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400 Take(channel);
401 GetSimulatedChannel(channel)->MakeRawWatcher(watcher);
402}
403
404std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
405 const Channel *channel) {
Austin Schuh54cf95f2019-11-29 13:14:18 -0800406 ValidateChannel(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407 Take(channel);
408 return GetSimulatedChannel(channel)->MakeRawSender(this);
409}
410
411std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
412 const Channel *channel) {
Austin Schuh54cf95f2019-11-29 13:14:18 -0800413 ValidateChannel(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700414 return GetSimulatedChannel(channel)->MakeRawFetcher();
415}
416
417SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
418 const Channel *channel) {
419 auto it = channels_->find(SimpleChannel(channel));
420 if (it == channels_->end()) {
421 it = channels_
422 ->emplace(SimpleChannel(channel),
423 std::unique_ptr<SimulatedChannel>(
424 new SimulatedChannel(channel, scheduler_)))
425 .first;
426 }
427 return it->second.get();
428}
429
430void SimulatedChannel::MakeRawWatcher(
431 ::std::function<void(const Context &context, const void *message)>
432 watcher) {
433 watchers_.push_back(watcher);
434}
435
436::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
437 EventLoop *event_loop) {
438 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
439}
440
441::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher() {
442 ::std::unique_ptr<SimulatedFetcher> fetcher(new SimulatedFetcher(this));
443 fetchers_.push_back(fetcher.get());
444 return ::std::move(fetcher);
445}
446
447void SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
448 message->context.queue_index = next_queue_index_.index();
449 message->context.data =
450 message->data() + channel()->max_size() - message->context.size;
451 next_queue_index_ = next_queue_index_.Increment();
452
453 latest_message_ = message;
454 if (scheduler_->is_running()) {
455 for (auto &watcher : watchers_) {
456 scheduler_->Schedule(scheduler_->monotonic_now(), [watcher, message]() {
457 watcher(message->context, message->context.data);
458 });
459 }
460 }
461 for (auto &fetcher : fetchers_) {
462 fetcher->Enqueue(message);
463 }
464}
465
466void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
467 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
468}
469
470SimpleChannel::SimpleChannel(const Channel *channel)
471 : name(CHECK_NOTNULL(CHECK_NOTNULL(channel)->name())->str()),
472 type(CHECK_NOTNULL(CHECK_NOTNULL(channel)->type())->str()) {}
473
474void SimulatedEventLoop::Take(const Channel *channel) {
475 CHECK(!is_running()) << ": Cannot add new objects while running.";
476
477 auto result = taken_.insert(SimpleChannel(channel));
478 CHECK(result.second) << ": " << FlatbufferToJson(channel)
479 << " is already being used.";
480}
481
482SimulatedEventLoopFactory::SimulatedEventLoopFactory(
483 const Configuration *configuration)
484 : configuration_(configuration) {}
485SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
486
487::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop() {
488 return ::std::unique_ptr<EventLoop>(new SimulatedEventLoop(
489 &scheduler_, &channels_, configuration_, &raw_event_loops_));
490}
491
492void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
493 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
494 raw_event_loops_) {
495 event_loop.second(true);
496 }
497 scheduler_.RunFor(duration);
498 if (!scheduler_.is_running()) {
499 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
500 raw_event_loops_) {
501 event_loop.second(false);
502 }
503 }
504}
505
506void SimulatedEventLoopFactory::Run() {
507 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
508 raw_event_loops_) {
509 event_loop.second(true);
510 }
511 scheduler_.Run();
512 if (!scheduler_.is_running()) {
513 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
514 raw_event_loops_) {
515 event_loop.second(false);
516 }
517 }
518}
519
520} // namespace aos