blob: 0b919e488cc5d50746b186eb47fc60a47cbb1510 [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>
Brian Silverman661eb8d2020-08-12 19:41:01 -07006#include <vector>
Alex Perrycb7da4b2019-08-28 19:35:56 -07007
8#include "absl/container/btree_map.h"
Brian Silverman661eb8d2020-08-12 19:41:01 -07009#include "aos/events/aos_logging.h"
Austin Schuh898f4972020-01-11 17:21:25 -080010#include "aos/events/simulated_network_bridge.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080011#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070012#include "aos/json_to_flatbuffer.h"
Austin Schuhcc6070c2020-10-10 20:25:56 -070013#include "aos/realtime.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/util/phased_loop.h"
15
16namespace aos {
17
Brian Silverman661eb8d2020-08-12 19:41:01 -070018class SimulatedEventLoop;
19class SimulatedFetcher;
20class SimulatedChannel;
21
22namespace {
23
Austin Schuhcc6070c2020-10-10 20:25:56 -070024class ScopedMarkRealtimeRestorer {
25 public:
26 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
27 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
28
29 private:
30 const bool rt_;
31 const bool prior_;
32};
33
Alex Perrycb7da4b2019-08-28 19:35:56 -070034// Container for both a message, and the context for it for simulation. This
35// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070036struct SimulatedMessage final {
37 SimulatedMessage(const SimulatedMessage &) = delete;
38 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
39
40 // Creates a SimulatedMessage with size bytes of storage.
41 // This is a shared_ptr so we don't have to implement refcounting or copying.
42 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel);
43
Alex Perrycb7da4b2019-08-28 19:35:56 -070044 // Context for the data.
45 Context context;
46
Brian Silverman661eb8d2020-08-12 19:41:01 -070047 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070048
Alex Perrycb7da4b2019-08-28 19:35:56 -070049 // The data.
Brian Silvermana1652f32020-01-29 20:41:44 -080050 char *data(size_t buffer_size) {
51 return RoundChannelData(&actual_data[0], buffer_size);
52 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070053
Brian Silvermana1652f32020-01-29 20:41:44 -080054 // Then the data, including padding on the end so we can align the buffer we
55 // actually return from data().
56 char actual_data[];
Brian Silverman661eb8d2020-08-12 19:41:01 -070057
58 private:
59 SimulatedMessage(SimulatedChannel *channel_in);
60 ~SimulatedMessage();
61
62 static void DestroyAndFree(SimulatedMessage *p) {
63 p->~SimulatedMessage();
64 free(p);
65 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070066};
67
Brian Silverman661eb8d2020-08-12 19:41:01 -070068} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080069
Brian Silverman661eb8d2020-08-12 19:41:01 -070070// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
71// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -080072class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080073 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080074 SimulatedWatcher(
75 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
76 const Channel *channel,
77 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080078
Austin Schuh7d87b672019-12-01 20:23:49 -080079 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080080
81 void Startup(EventLoop * /*event_loop*/) override {}
82
Austin Schuh7d87b672019-12-01 20:23:49 -080083 void Schedule(std::shared_ptr<SimulatedMessage> message);
84
85 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080086
87 void SetSimulatedChannel(SimulatedChannel *channel) {
88 simulated_channel_ = channel;
89 }
90
91 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080092 void DoSchedule(monotonic_clock::time_point event_time);
93
94 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
95
Brian Silverman4f4e0612020-08-12 19:54:41 -070096 SimulatedEventLoop *const simulated_event_loop_;
97 const Channel *const channel_;
98 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -080099 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800100 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800101 SimulatedChannel *simulated_channel_ = nullptr;
102};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700103
104class SimulatedChannel {
105 public:
Brian Silverman661eb8d2020-08-12 19:41:01 -0700106 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler,
107 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800108 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700109 scheduler_(scheduler),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700110 channel_storage_duration_(channel_storage_duration),
111 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
112 available_buffer_indices_.reserve(number_buffers());
113 for (int i = 0; i < number_buffers(); ++i) {
114 available_buffer_indices_.push_back(i);
115 }
116 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117
Brian Silverman661eb8d2020-08-12 19:41:01 -0700118 ~SimulatedChannel() {
119 latest_message_.reset();
120 CHECK_EQ(static_cast<size_t>(number_buffers()),
121 available_buffer_indices_.size());
122 CHECK_EQ(0u, fetchers_.size());
123 CHECK_EQ(0u, watchers_.size());
124 CHECK_EQ(0, sender_count_);
125 }
126
127 // The number of messages we pretend to have in the queue.
128 int queue_size() const {
129 return channel()->frequency() *
130 std::chrono::duration_cast<std::chrono::duration<double>>(
131 channel_storage_duration_)
132 .count();
133 }
134
135 // The number of extra buffers (beyond the queue) we pretend to have.
136 int number_scratch_buffers() const {
137 // We need to start creating messages before we know how many
138 // senders+readers we'll have, so we need to just pick something which is
139 // always big enough.
140 return 50;
141 }
142
143 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
144
145 int GetBufferIndex() {
146 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
147 const int result = available_buffer_indices_.back();
148 available_buffer_indices_.pop_back();
149 return result;
150 }
151
152 void FreeBufferIndex(int i) {
153 DCHECK(std::find(available_buffer_indices_.begin(),
154 available_buffer_indices_.end(),
155 i) == available_buffer_indices_.end())
156 << ": Buffer is not in use: " << i;
157 available_buffer_indices_.push_back(i);
158 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159
160 // Makes a connected raw sender which calls Send below.
161 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
162
163 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800164 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700165
166 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800167 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800168
Austin Schuh7d87b672019-12-01 20:23:49 -0800169 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800170 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
171 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700172
Austin Schuhad154822019-12-27 15:45:13 -0800173 // Sends the message to all the connected receivers and fetchers. Returns the
174 // sent queue index.
175 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700176
177 // Unregisters a fetcher.
178 void UnregisterFetcher(SimulatedFetcher *fetcher);
179
180 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
181
Austin Schuh39788ff2019-12-01 18:22:57 -0800182 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700183
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800184 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800185 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700186 }
187
Austin Schuh39788ff2019-12-01 18:22:57 -0800188 const Channel *channel() const { return channel_; }
189
Austin Schuhe516ab02020-05-06 21:37:04 -0700190 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700191 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700192 if (sender_count_ >= channel()->num_senders()) {
193 LOG(FATAL) << "Failed to create sender on "
194 << configuration::CleanedChannelToString(channel())
195 << ", too many senders.";
196 }
197 ++sender_count_;
198 }
Brian Silverman77162972020-08-12 19:52:40 -0700199
Austin Schuhe516ab02020-05-06 21:37:04 -0700200 void CountSenderDestroyed() {
201 --sender_count_;
202 CHECK_GE(sender_count_, 0);
203 }
204
Alex Perrycb7da4b2019-08-28 19:35:56 -0700205 private:
Brian Silverman77162972020-08-12 19:52:40 -0700206 void CheckBufferCount() {
207 int reader_count = 0;
208 if (channel()->read_method() == ReadMethod::PIN) {
209 reader_count = watchers_.size() + fetchers_.size();
210 }
211 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
212 }
213
214 void CheckReaderCount() {
215 if (channel()->read_method() != ReadMethod::PIN) {
216 return;
217 }
218 CheckBufferCount();
219 const int reader_count = watchers_.size() + fetchers_.size();
220 if (reader_count >= channel()->num_readers()) {
221 LOG(FATAL) << "Failed to create reader on "
222 << configuration::CleanedChannelToString(channel())
223 << ", too many readers.";
224 }
225 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700226
227 const Channel *const channel_;
228 EventScheduler *const scheduler_;
229 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700230
231 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800232 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700233
234 // List of all fetchers.
235 ::std::vector<SimulatedFetcher *> fetchers_;
236 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700237
238 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700239
240 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700241
242 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700243};
244
245namespace {
246
Brian Silverman661eb8d2020-08-12 19:41:01 -0700247std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
248 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800249 // The allocations in here are due to infrastructure and don't count in the no
250 // mallocs in RT code.
251 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700252 const size_t size = channel->max_size();
253 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800254 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700255 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800257 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700258
Brian Silverman661eb8d2020-08-12 19:41:01 -0700259 return std::shared_ptr<SimulatedMessage>(message,
260 &SimulatedMessage::DestroyAndFree);
261}
262
263SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
264 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700265 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700266}
267
268SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700269 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700270}
271
272class SimulatedSender : public RawSender {
273 public:
274 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800275 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800276 simulated_channel_(simulated_channel),
Austin Schuhe516ab02020-05-06 21:37:04 -0700277 event_loop_(event_loop) {
278 simulated_channel_->CountSenderCreated();
279 }
280 ~SimulatedSender() { simulated_channel_->CountSenderDestroyed(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281
282 void *data() override {
283 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700284 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800286 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700287 }
288
289 size_t size() override { return simulated_channel_->max_size(); }
290
Austin Schuhad154822019-12-27 15:45:13 -0800291 bool DoSend(size_t length,
292 aos::monotonic_clock::time_point monotonic_remote_time,
293 aos::realtime_clock::time_point realtime_remote_time,
294 uint32_t remote_queue_index) override {
Austin Schuh62288252020-11-18 23:26:04 -0800295 // The allocations in here are due to infrastructure and don't count in the
296 // no mallocs in RT code.
297 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700298 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuhad154822019-12-27 15:45:13 -0800299 message_->context.monotonic_event_time = event_loop_->monotonic_now();
300 message_->context.monotonic_remote_time = monotonic_remote_time;
301 message_->context.remote_queue_index = remote_queue_index;
302 message_->context.realtime_event_time = event_loop_->realtime_now();
303 message_->context.realtime_remote_time = realtime_remote_time;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700304 CHECK_LE(length, message_->context.size);
305 message_->context.size = length;
306
307 // TODO(austin): Track sending too fast.
Austin Schuhad154822019-12-27 15:45:13 -0800308 sent_queue_index_ = simulated_channel_->Send(message_);
309 monotonic_sent_time_ = event_loop_->monotonic_now();
310 realtime_sent_time_ = event_loop_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700311
312 // Drop the reference to the message so that we allocate a new message for
313 // next time. Otherwise we will continue to reuse the same memory for all
314 // messages and corrupt it.
315 message_.reset();
316 return true;
317 }
318
Austin Schuhad154822019-12-27 15:45:13 -0800319 bool DoSend(const void *msg, size_t size,
320 aos::monotonic_clock::time_point monotonic_remote_time,
321 aos::realtime_clock::time_point realtime_remote_time,
322 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
324
325 // This is wasteful, but since flatbuffers fill from the back end of the
326 // queue, we need it to be full sized.
Brian Silverman661eb8d2020-08-12 19:41:01 -0700327 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700328
329 // Now fill in the message. size is already populated above, and
Austin Schuhac0771c2020-01-07 18:36:30 -0800330 // queue_index will be populated in simulated_channel_. Put this at the
331 // back of the data segment.
Brian Silvermana1652f32020-01-29 20:41:44 -0800332 memcpy(message_->data(simulated_channel_->max_size()) +
333 simulated_channel_->max_size() - size,
334 msg, size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700335
Austin Schuhac0771c2020-01-07 18:36:30 -0800336 return DoSend(size, monotonic_remote_time, realtime_remote_time,
337 remote_queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700338 }
339
Brian Silverman4f4e0612020-08-12 19:54:41 -0700340 int buffer_index() override {
341 // First, ensure message_ is allocated.
342 data();
343 return message_->context.buffer_index;
344 }
345
Alex Perrycb7da4b2019-08-28 19:35:56 -0700346 private:
347 SimulatedChannel *simulated_channel_;
348 EventLoop *event_loop_;
349
350 std::shared_ptr<SimulatedMessage> message_;
351};
352} // namespace
353
354class SimulatedFetcher : public RawFetcher {
355 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800356 explicit SimulatedFetcher(EventLoop *event_loop,
357 SimulatedChannel *simulated_channel)
358 : RawFetcher(event_loop, simulated_channel->channel()),
359 simulated_channel_(simulated_channel) {}
360 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700361
Austin Schuh39788ff2019-12-01 18:22:57 -0800362 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800363 // The allocations in here are due to infrastructure and don't count in the
364 // no mallocs in RT code.
365 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800366 if (msgs_.size() == 0) {
367 return std::make_pair(false, monotonic_clock::min_time);
368 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700369
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700370 CHECK(!fell_behind_) << ": Got behind on "
371 << configuration::StrippedChannelToString(
372 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700373
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374 SetMsg(msgs_.front());
375 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800376 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700377 }
378
Austin Schuh39788ff2019-12-01 18:22:57 -0800379 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800380 // The allocations in here are due to infrastructure and don't count in the
381 // no mallocs in RT code.
382 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700383 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800384 // TODO(austin): Can we just do this logic unconditionally? It is a lot
385 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800386 if (!msg_ && simulated_channel_->latest_message()) {
387 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800388 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700389 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800390 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 }
392 }
393
394 // We've had a message enqueued, so we don't need to go looking for the
395 // latest message from before we started.
396 SetMsg(msgs_.back());
397 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700398 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800399 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400 }
401
402 private:
403 friend class SimulatedChannel;
404
405 // Updates the state inside RawFetcher to point to the data in msg_.
406 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
407 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700409 if (channel()->read_method() != ReadMethod::PIN) {
410 context_.buffer_index = -1;
411 }
Austin Schuhad154822019-12-27 15:45:13 -0800412 if (context_.remote_queue_index == 0xffffffffu) {
413 context_.remote_queue_index = context_.queue_index;
414 }
415 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
416 context_.monotonic_remote_time = context_.monotonic_event_time;
417 }
418 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
419 context_.realtime_remote_time = context_.realtime_event_time;
420 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700421 }
422
423 // Internal method for Simulation to add a message to the buffer.
424 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
425 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700426 if (fell_behind_ ||
427 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
428 fell_behind_ = true;
429 // Might as well empty out all the intermediate messages now.
430 while (msgs_.size() > 1) {
431 msgs_.pop_front();
432 }
433 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434 }
435
Austin Schuhac0771c2020-01-07 18:36:30 -0800436 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700437 std::shared_ptr<SimulatedMessage> msg_;
438
439 // Messages queued up but not in use.
440 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700441
442 // Whether we're currently "behind", which means a FetchNext call will fail.
443 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444};
445
446class SimulatedTimerHandler : public TimerHandler {
447 public:
448 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800449 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800450 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800451 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700452
453 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800454 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700455
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800456 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457
Austin Schuh7d87b672019-12-01 20:23:49 -0800458 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800461 SimulatedEventLoop *simulated_event_loop_;
462 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700463 EventScheduler *scheduler_;
464 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800465
Alex Perrycb7da4b2019-08-28 19:35:56 -0700466 monotonic_clock::time_point base_;
467 monotonic_clock::duration repeat_offset_;
468};
469
470class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
471 public:
472 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800473 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474 ::std::function<void(int)> fn,
475 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800476 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800477 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700478
Austin Schuh7d87b672019-12-01 20:23:49 -0800479 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480
Austin Schuh7d87b672019-12-01 20:23:49 -0800481 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700482
483 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800484 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800485 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700486
Austin Schuh39788ff2019-12-01 18:22:57 -0800487 EventScheduler *scheduler_;
488 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489};
490
491class SimulatedEventLoop : public EventLoop {
492 public:
493 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700494 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700495 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
496 *channels,
497 const Configuration *configuration,
498 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800499 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800500 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800501 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700502 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800503 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700504 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800505 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800506 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800507 tid_(tid) {
508 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
509 if (!has_setup_) {
510 Setup();
511 has_setup_ = true;
512 }
513 set_is_running(value);
514 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515 }
516 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800517 // Trigger any remaining senders or fetchers to be cleared before destroying
518 // the event loop so the book keeping matches.
519 timing_report_sender_.reset();
520
521 // Force everything with a registered fd with epoll to be destroyed now.
522 timers_.clear();
523 phased_loops_.clear();
524 watchers_.clear();
525
Alex Perrycb7da4b2019-08-28 19:35:56 -0700526 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
527 ++it) {
528 if (it->first == this) {
529 raw_event_loops_->erase(it);
530 break;
531 }
532 }
533 }
534
Austin Schuh7d87b672019-12-01 20:23:49 -0800535 std::chrono::nanoseconds send_delay() const { return send_delay_; }
536 void set_send_delay(std::chrono::nanoseconds send_delay) {
537 send_delay_ = send_delay;
538 }
539
Alex Perrycb7da4b2019-08-28 19:35:56 -0700540 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800541 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542 }
543
544 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800545 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546 }
547
548 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
549
550 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
551
552 void MakeRawWatcher(
553 const Channel *channel,
554 ::std::function<void(const Context &context, const void *message)>
555 watcher) override;
556
557 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800558 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800559 return NewTimer(::std::unique_ptr<TimerHandler>(
560 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700561 }
562
563 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
564 const monotonic_clock::duration interval,
565 const monotonic_clock::duration offset =
566 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800567 return NewPhasedLoop(
568 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
569 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570 }
571
572 void OnRun(::std::function<void()> on_run) override {
Austin Schuhcc6070c2020-10-10 20:25:56 -0700573 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
574 ScopedMarkRealtimeRestorer rt(priority() > 0);
575 on_run();
576 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700577 }
578
Austin Schuh217a9782019-12-21 23:02:50 -0800579 const Node *node() const override { return node_; }
580
James Kuszmaul3ae42262019-11-08 12:33:41 -0800581 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700582 name_ = std::string(name);
583 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800584 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700585
586 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
587
Austin Schuh39788ff2019-12-01 18:22:57 -0800588 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700589 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800590 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700591 }
592
Austin Schuh39788ff2019-12-01 18:22:57 -0800593 int priority() const override { return priority_; }
594
Brian Silverman6a54ff32020-04-28 16:41:39 -0700595 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
596 CHECK(!is_running()) << ": Cannot set affinity while running.";
597 }
598
Tyler Chatow67ddb032020-01-12 14:30:04 -0800599 void Setup() {
600 MaybeScheduleTimingReports();
601 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800602 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700603 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800604 }
605 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800606
Brian Silverman4f4e0612020-08-12 19:54:41 -0700607 int NumberBuffers(const Channel *channel) override;
608
Alex Perrycb7da4b2019-08-28 19:35:56 -0700609 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800610 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800611 friend class SimulatedPhasedLoopHandler;
612 friend class SimulatedWatcher;
613
614 void HandleEvent() {
615 while (true) {
616 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
617 break;
618 }
619
620 EventLoopEvent *event = PopEvent();
621 event->HandleEvent();
622 }
623 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800624
Austin Schuh39788ff2019-12-01 18:22:57 -0800625 pid_t GetTid() override { return tid_; }
626
Alex Perrycb7da4b2019-08-28 19:35:56 -0700627 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800628 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700629 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
630 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
631 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700632
633 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800634
635 int priority_ = 0;
636
637 bool has_setup_ = false;
638
Austin Schuh7d87b672019-12-01 20:23:49 -0800639 std::chrono::nanoseconds send_delay_;
640
Austin Schuh217a9782019-12-21 23:02:50 -0800641 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800642 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800643
644 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700645 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700646};
647
Austin Schuh7d87b672019-12-01 20:23:49 -0800648void SimulatedEventLoopFactory::set_send_delay(
649 std::chrono::nanoseconds send_delay) {
650 send_delay_ = send_delay;
651 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
652 raw_event_loops_) {
653 reinterpret_cast<SimulatedEventLoop *>(loop.first)
654 ->set_send_delay(send_delay_);
655 }
656}
657
Alex Perrycb7da4b2019-08-28 19:35:56 -0700658void SimulatedEventLoop::MakeRawWatcher(
659 const Channel *channel,
660 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800661 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800662
Austin Schuh8bd96322020-02-13 21:18:22 -0800663 std::unique_ptr<SimulatedWatcher> shm_watcher(
664 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800665
666 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
667 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700668}
669
670std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
671 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800672 TakeSender(channel);
673
Alex Perrycb7da4b2019-08-28 19:35:56 -0700674 return GetSimulatedChannel(channel)->MakeRawSender(this);
675}
676
677std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
678 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800679 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800680
Austin Schuhca4828c2019-12-28 14:21:35 -0800681 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
682 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
683 << "\", \"type\": \"" << channel->type()->string_view()
684 << "\" } is not able to be fetched on this node. Check your "
685 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800686 }
687
Austin Schuh39788ff2019-12-01 18:22:57 -0800688 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700689}
690
691SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
692 const Channel *channel) {
693 auto it = channels_->find(SimpleChannel(channel));
694 if (it == channels_->end()) {
695 it = channels_
696 ->emplace(SimpleChannel(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700697 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
698 channel, scheduler_,
699 std::chrono::nanoseconds(
700 configuration()->channel_storage_duration()))))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700701 .first;
702 }
703 return it->second.get();
704}
705
Brian Silverman4f4e0612020-08-12 19:54:41 -0700706int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
707 return GetSimulatedChannel(channel)->number_buffers();
708}
709
Austin Schuh7d87b672019-12-01 20:23:49 -0800710SimulatedWatcher::SimulatedWatcher(
711 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800712 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800713 std::function<void(const Context &context, const void *message)> fn)
714 : WatcherState(simulated_event_loop, channel, std::move(fn)),
715 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700716 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800717 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700718 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800719 token_(scheduler_->InvalidToken()) {}
720
721SimulatedWatcher::~SimulatedWatcher() {
722 simulated_event_loop_->RemoveEvent(&event_);
723 if (token_ != scheduler_->InvalidToken()) {
724 scheduler_->Deschedule(token_);
725 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700726 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800727}
728
729void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800730 monotonic_clock::time_point event_time =
731 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800732
733 // Messages are queued in order. If we are the first, add ourselves.
734 // Otherwise, don't.
735 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800736 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800737 simulated_event_loop_->AddEvent(&event_);
738
739 DoSchedule(event_time);
740 }
741
742 msgs_.emplace_back(message);
743}
744
745void SimulatedWatcher::HandleEvent() {
746 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
747
748 const monotonic_clock::time_point monotonic_now =
749 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800750 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700751 if (simulated_event_loop_->log_impl_) {
752 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800753 }
Austin Schuhad154822019-12-27 15:45:13 -0800754 Context context = msgs_.front()->context;
755
Brian Silverman4f4e0612020-08-12 19:54:41 -0700756 if (channel_->read_method() != ReadMethod::PIN) {
757 context.buffer_index = -1;
758 }
Austin Schuhad154822019-12-27 15:45:13 -0800759 if (context.remote_queue_index == 0xffffffffu) {
760 context.remote_queue_index = context.queue_index;
761 }
762 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
763 context.monotonic_remote_time = context.monotonic_event_time;
764 }
765 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
766 context.realtime_remote_time = context.realtime_event_time;
767 }
768
Austin Schuhcc6070c2020-10-10 20:25:56 -0700769 {
770 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
771 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
772 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800773
774 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700775 if (token_ != scheduler_->InvalidToken()) {
776 scheduler_->Deschedule(token_);
777 token_ = scheduler_->InvalidToken();
778 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800779 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800780 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800781 simulated_event_loop_->AddEvent(&event_);
782
783 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800784 }
785}
786
787void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700788 CHECK(token_ == scheduler_->InvalidToken())
789 << ": May not schedule multiple times";
790 token_ = scheduler_->Schedule(
791 event_time + simulated_event_loop_->send_delay(), [this]() {
792 DCHECK(token_ != scheduler_->InvalidToken());
793 token_ = scheduler_->InvalidToken();
794 simulated_event_loop_->HandleEvent();
795 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800796}
797
798void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700799 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800800 watcher->SetSimulatedChannel(this);
801 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700802}
803
804::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
805 EventLoop *event_loop) {
806 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
807}
808
Austin Schuh39788ff2019-12-01 18:22:57 -0800809::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
810 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700811 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800812 ::std::unique_ptr<SimulatedFetcher> fetcher(
813 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700814 fetchers_.push_back(fetcher.get());
815 return ::std::move(fetcher);
816}
817
Austin Schuhad154822019-12-27 15:45:13 -0800818uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
819 const uint32_t queue_index = next_queue_index_.index();
820 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800821 message->context.data = message->data(channel()->max_size()) +
822 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700823 next_queue_index_ = next_queue_index_.Increment();
824
825 latest_message_ = message;
826 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800827 for (SimulatedWatcher *watcher : watchers_) {
828 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700829 }
830 }
831 for (auto &fetcher : fetchers_) {
832 fetcher->Enqueue(message);
833 }
Austin Schuhad154822019-12-27 15:45:13 -0800834
835 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700836}
837
838void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
839 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
840}
841
Austin Schuh39788ff2019-12-01 18:22:57 -0800842SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800843 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
844 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800845 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800846 simulated_event_loop_(simulated_event_loop),
847 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800848 scheduler_(scheduler),
849 token_(scheduler_->InvalidToken()) {}
850
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800851void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
852 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800853 // The allocations in here are due to infrastructure and don't count in the no
854 // mallocs in RT code.
855 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800856 Disable();
857 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800858 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800859 base_ = base;
860 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700861 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
862 DCHECK(token_ != scheduler_->InvalidToken());
863 token_ = scheduler_->InvalidToken();
864 simulated_event_loop_->HandleEvent();
865 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800866 event_.set_event_time(base_);
867 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800868}
869
870void SimulatedTimerHandler::HandleEvent() {
871 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800872 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800873 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700874 if (simulated_event_loop_->log_impl_) {
875 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800876 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700877 if (token_ != scheduler_->InvalidToken()) {
878 scheduler_->Deschedule(token_);
879 token_ = scheduler_->InvalidToken();
880 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800881 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
882 // Reschedule.
883 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700884 token_ = scheduler_->Schedule(base_, [this]() {
885 DCHECK(token_ != scheduler_->InvalidToken());
886 token_ = scheduler_->InvalidToken();
887 simulated_event_loop_->HandleEvent();
888 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800889 event_.set_event_time(base_);
890 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800891 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800892
Austin Schuhcc6070c2020-10-10 20:25:56 -0700893 {
894 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
895 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
896 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800897}
898
Austin Schuh7d87b672019-12-01 20:23:49 -0800899void SimulatedTimerHandler::Disable() {
900 simulated_event_loop_->RemoveEvent(&event_);
901 if (token_ != scheduler_->InvalidToken()) {
902 scheduler_->Deschedule(token_);
903 token_ = scheduler_->InvalidToken();
904 }
905}
906
Austin Schuh39788ff2019-12-01 18:22:57 -0800907SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800908 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
909 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800910 const monotonic_clock::duration offset)
911 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
912 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800913 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800914 scheduler_(scheduler),
915 token_(scheduler_->InvalidToken()) {}
916
Austin Schuh7d87b672019-12-01 20:23:49 -0800917SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
918 if (token_ != scheduler_->InvalidToken()) {
919 scheduler_->Deschedule(token_);
920 token_ = scheduler_->InvalidToken();
921 }
922 simulated_event_loop_->RemoveEvent(&event_);
923}
924
925void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800926 monotonic_clock::time_point monotonic_now =
927 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800928 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700929 if (simulated_event_loop_->log_impl_) {
930 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800931 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700932
933 {
934 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
935 Call([monotonic_now]() { return monotonic_now; },
936 [this](monotonic_clock::time_point sleep_time) {
937 Schedule(sleep_time);
938 });
939 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800940}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800941
Austin Schuh7d87b672019-12-01 20:23:49 -0800942void SimulatedPhasedLoopHandler::Schedule(
943 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -0800944 // The allocations in here are due to infrastructure and don't count in the no
945 // mallocs in RT code.
946 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700947 if (token_ != scheduler_->InvalidToken()) {
948 scheduler_->Deschedule(token_);
949 token_ = scheduler_->InvalidToken();
950 }
951 token_ = scheduler_->Schedule(sleep_time, [this]() {
952 DCHECK(token_ != scheduler_->InvalidToken());
953 token_ = scheduler_->InvalidToken();
954 simulated_event_loop_->HandleEvent();
955 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800956 event_.set_event_time(sleep_time);
957 simulated_event_loop_->AddEvent(&event_);
958}
959
Austin Schuhac0771c2020-01-07 18:36:30 -0800960NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -0800961 EventSchedulerScheduler *scheduler_scheduler,
962 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -0800963 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
964 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -0800965 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
966 scheduler_scheduler->AddEventScheduler(&scheduler_);
967}
Austin Schuhac0771c2020-01-07 18:36:30 -0800968
Alex Perrycb7da4b2019-08-28 19:35:56 -0700969SimulatedEventLoopFactory::SimulatedEventLoopFactory(
970 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800971 : configuration_(CHECK_NOTNULL(configuration)),
972 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -0800973 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -0800974 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800975 node_factories_.emplace_back(new NodeEventLoopFactory(
976 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -0800977 }
Austin Schuh898f4972020-01-11 17:21:25 -0800978
979 if (configuration::MultiNode(configuration)) {
980 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
981 }
Austin Schuh15649d62019-12-28 16:36:38 -0800982}
983
Alex Perrycb7da4b2019-08-28 19:35:56 -0700984SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
985
Austin Schuhac0771c2020-01-07 18:36:30 -0800986NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
987 const Node *node) {
988 auto result = std::find_if(
989 node_factories_.begin(), node_factories_.end(),
990 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
991 return node_factory->node() == node;
992 });
993
994 CHECK(result != node_factories_.end())
995 << ": Failed to find node " << FlatbufferToJson(node);
996
997 return result->get();
998}
999
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001000::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001001 std::string_view name, const Node *node) {
1002 if (node == nullptr) {
1003 CHECK(!configuration::MultiNode(configuration()))
1004 << ": Can't make a single node event loop in a multi-node world.";
1005 } else {
1006 CHECK(configuration::MultiNode(configuration()))
1007 << ": Can't make a multi-node event loop in a single-node world.";
1008 }
1009 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1010}
1011
1012::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001013 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001014 CHECK(!scheduler_.is_running())
1015 << ": Can't create an event loop while running";
1016
Austin Schuh39788ff2019-12-01 18:22:57 -08001017 pid_t tid = tid_;
1018 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001019 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -08001020 &scheduler_, this, &channels_, factory_->configuration(),
1021 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001022 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001023 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001024 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001025}
1026
1027void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1028 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1029 raw_event_loops_) {
1030 event_loop.second(true);
1031 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001032 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001033 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1034 raw_event_loops_) {
1035 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001036 }
1037}
1038
1039void SimulatedEventLoopFactory::Run() {
1040 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1041 raw_event_loops_) {
1042 event_loop.second(true);
1043 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001044 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001045 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1046 raw_event_loops_) {
1047 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001048 }
1049}
1050
Austin Schuh6f3babe2020-01-26 20:34:50 -08001051void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001052 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001053 bridge_->DisableForwarding(channel);
1054}
1055
Austin Schuh4c3b9702020-08-30 11:34:55 -07001056void SimulatedEventLoopFactory::DisableStatistics() {
1057 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1058 bridge_->DisableStatistics();
1059}
1060
Alex Perrycb7da4b2019-08-28 19:35:56 -07001061} // namespace aos