blob: ef3483978d31d4ce12ea4387631a82ef63b5b6e7 [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
Austin Schuh8fb315a2020-11-19 22:33:58 -080081 bool has_run() const;
82
Austin Schuh39788ff2019-12-01 18:22:57 -080083 void Startup(EventLoop * /*event_loop*/) override {}
84
Austin Schuh7d87b672019-12-01 20:23:49 -080085 void Schedule(std::shared_ptr<SimulatedMessage> message);
86
87 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080088
89 void SetSimulatedChannel(SimulatedChannel *channel) {
90 simulated_channel_ = channel;
91 }
92
93 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080094 void DoSchedule(monotonic_clock::time_point event_time);
95
96 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
97
Brian Silverman4f4e0612020-08-12 19:54:41 -070098 SimulatedEventLoop *const simulated_event_loop_;
99 const Channel *const channel_;
100 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800101 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800102 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 SimulatedChannel *simulated_channel_ = nullptr;
104};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700105
106class SimulatedChannel {
107 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800108 explicit SimulatedChannel(const Channel *channel,
Brian Silverman661eb8d2020-08-12 19:41:01 -0700109 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800110 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700111 channel_storage_duration_(channel_storage_duration),
112 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
113 available_buffer_indices_.reserve(number_buffers());
114 for (int i = 0; i < number_buffers(); ++i) {
115 available_buffer_indices_.push_back(i);
116 }
117 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700118
Brian Silverman661eb8d2020-08-12 19:41:01 -0700119 ~SimulatedChannel() {
120 latest_message_.reset();
121 CHECK_EQ(static_cast<size_t>(number_buffers()),
122 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800123 CHECK_EQ(0u, fetchers_.size())
124 << configuration::StrippedChannelToString(channel());
125 CHECK_EQ(0u, watchers_.size())
126 << configuration::StrippedChannelToString(channel());
127 CHECK_EQ(0, sender_count_)
128 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700129 }
130
131 // The number of messages we pretend to have in the queue.
132 int queue_size() const {
133 return channel()->frequency() *
134 std::chrono::duration_cast<std::chrono::duration<double>>(
135 channel_storage_duration_)
136 .count();
137 }
138
139 // The number of extra buffers (beyond the queue) we pretend to have.
140 int number_scratch_buffers() const {
141 // We need to start creating messages before we know how many
142 // senders+readers we'll have, so we need to just pick something which is
143 // always big enough.
144 return 50;
145 }
146
147 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
148
149 int GetBufferIndex() {
150 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
151 const int result = available_buffer_indices_.back();
152 available_buffer_indices_.pop_back();
153 return result;
154 }
155
156 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700157 // This extra checking has a large performance hit with sanitizers that
158 // track memory accesses, so just skip it.
159#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700160 DCHECK(std::find(available_buffer_indices_.begin(),
161 available_buffer_indices_.end(),
162 i) == available_buffer_indices_.end())
163 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800164#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700165 available_buffer_indices_.push_back(i);
166 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700167
168 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800169 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700170
171 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800172 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700173
174 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800175 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800176
Austin Schuh7d87b672019-12-01 20:23:49 -0800177 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800178 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
179 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700180
Austin Schuhad154822019-12-27 15:45:13 -0800181 // Sends the message to all the connected receivers and fetchers. Returns the
182 // sent queue index.
183 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700184
185 // Unregisters a fetcher.
186 void UnregisterFetcher(SimulatedFetcher *fetcher);
187
188 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
189
Austin Schuh39788ff2019-12-01 18:22:57 -0800190 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700191
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800192 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800193 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700194 }
195
Austin Schuh39788ff2019-12-01 18:22:57 -0800196 const Channel *channel() const { return channel_; }
197
Austin Schuhe516ab02020-05-06 21:37:04 -0700198 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700199 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700200 if (sender_count_ >= channel()->num_senders()) {
201 LOG(FATAL) << "Failed to create sender on "
202 << configuration::CleanedChannelToString(channel())
203 << ", too many senders.";
204 }
205 ++sender_count_;
206 }
Brian Silverman77162972020-08-12 19:52:40 -0700207
Austin Schuhe516ab02020-05-06 21:37:04 -0700208 void CountSenderDestroyed() {
209 --sender_count_;
210 CHECK_GE(sender_count_, 0);
211 }
212
Alex Perrycb7da4b2019-08-28 19:35:56 -0700213 private:
Brian Silverman77162972020-08-12 19:52:40 -0700214 void CheckBufferCount() {
215 int reader_count = 0;
216 if (channel()->read_method() == ReadMethod::PIN) {
217 reader_count = watchers_.size() + fetchers_.size();
218 }
219 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
220 }
221
222 void CheckReaderCount() {
223 if (channel()->read_method() != ReadMethod::PIN) {
224 return;
225 }
226 CheckBufferCount();
227 const int reader_count = watchers_.size() + fetchers_.size();
228 if (reader_count >= channel()->num_readers()) {
229 LOG(FATAL) << "Failed to create reader on "
230 << configuration::CleanedChannelToString(channel())
231 << ", too many readers.";
232 }
233 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700234
235 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700236 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700237
238 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800239 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700240
241 // List of all fetchers.
242 ::std::vector<SimulatedFetcher *> fetchers_;
243 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700244
245 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700246
247 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700248
249 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700250};
251
252namespace {
253
Brian Silverman661eb8d2020-08-12 19:41:01 -0700254std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
255 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800256 // The allocations in here are due to infrastructure and don't count in the no
257 // mallocs in RT code.
258 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700259 const size_t size = channel->max_size();
260 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800261 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700262 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700263 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800264 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700265
Brian Silverman661eb8d2020-08-12 19:41:01 -0700266 return std::shared_ptr<SimulatedMessage>(message,
267 &SimulatedMessage::DestroyAndFree);
268}
269
270SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
271 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700272 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700273}
274
275SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700276 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277}
278
279class SimulatedSender : public RawSender {
280 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800281 SimulatedSender(SimulatedChannel *simulated_channel,
282 SimulatedEventLoop *event_loop);
283 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284
285 void *data() override {
286 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700287 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700288 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800289 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700290 }
291
292 size_t size() override { return simulated_channel_->max_size(); }
293
Austin Schuhad154822019-12-27 15:45:13 -0800294 bool DoSend(size_t length,
295 aos::monotonic_clock::time_point monotonic_remote_time,
296 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700297 uint32_t remote_queue_index,
298 const UUID &remote_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700299
Austin Schuhad154822019-12-27 15:45:13 -0800300 bool DoSend(const void *msg, size_t size,
301 aos::monotonic_clock::time_point monotonic_remote_time,
302 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700303 uint32_t remote_queue_index,
304 const UUID &remote_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700305
Brian Silverman4f4e0612020-08-12 19:54:41 -0700306 int buffer_index() override {
307 // First, ensure message_ is allocated.
308 data();
309 return message_->context.buffer_index;
310 }
311
Alex Perrycb7da4b2019-08-28 19:35:56 -0700312 private:
313 SimulatedChannel *simulated_channel_;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800314 SimulatedEventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315
316 std::shared_ptr<SimulatedMessage> message_;
317};
318} // namespace
319
320class SimulatedFetcher : public RawFetcher {
321 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800322 explicit SimulatedFetcher(EventLoop *event_loop,
323 SimulatedChannel *simulated_channel)
324 : RawFetcher(event_loop, simulated_channel->channel()),
325 simulated_channel_(simulated_channel) {}
326 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327
Austin Schuh39788ff2019-12-01 18:22:57 -0800328 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800329 // The allocations in here are due to infrastructure and don't count in the
330 // no mallocs in RT code.
331 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800332 if (msgs_.size() == 0) {
333 return std::make_pair(false, monotonic_clock::min_time);
334 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700335
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700336 CHECK(!fell_behind_) << ": Got behind on "
337 << configuration::StrippedChannelToString(
338 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700339
Alex Perrycb7da4b2019-08-28 19:35:56 -0700340 SetMsg(msgs_.front());
341 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800342 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343 }
344
Austin Schuh39788ff2019-12-01 18:22:57 -0800345 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800346 // The allocations in here are due to infrastructure and don't count in the
347 // no mallocs in RT code.
348 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700349 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800350 // TODO(austin): Can we just do this logic unconditionally? It is a lot
351 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800352 if (!msg_ && simulated_channel_->latest_message()) {
353 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800354 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700355 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800356 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357 }
358 }
359
360 // We've had a message enqueued, so we don't need to go looking for the
361 // latest message from before we started.
362 SetMsg(msgs_.back());
363 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700364 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800365 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366 }
367
368 private:
369 friend class SimulatedChannel;
370
371 // Updates the state inside RawFetcher to point to the data in msg_.
372 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
373 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700375 if (channel()->read_method() != ReadMethod::PIN) {
376 context_.buffer_index = -1;
377 }
Austin Schuhad154822019-12-27 15:45:13 -0800378 if (context_.remote_queue_index == 0xffffffffu) {
379 context_.remote_queue_index = context_.queue_index;
380 }
381 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
382 context_.monotonic_remote_time = context_.monotonic_event_time;
383 }
384 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
385 context_.realtime_remote_time = context_.realtime_event_time;
386 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700387 }
388
389 // Internal method for Simulation to add a message to the buffer.
390 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
391 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700392 if (fell_behind_ ||
393 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
394 fell_behind_ = true;
395 // Might as well empty out all the intermediate messages now.
396 while (msgs_.size() > 1) {
397 msgs_.pop_front();
398 }
399 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400 }
401
Austin Schuhac0771c2020-01-07 18:36:30 -0800402 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403 std::shared_ptr<SimulatedMessage> msg_;
404
405 // Messages queued up but not in use.
406 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700407
408 // Whether we're currently "behind", which means a FetchNext call will fail.
409 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700410};
411
412class SimulatedTimerHandler : public TimerHandler {
413 public:
414 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800415 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800416 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800417 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700418
419 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800420 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700421
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800422 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700423
Austin Schuh7d87b672019-12-01 20:23:49 -0800424 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700425
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800427 SimulatedEventLoop *simulated_event_loop_;
428 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700429 EventScheduler *scheduler_;
430 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800431
Alex Perrycb7da4b2019-08-28 19:35:56 -0700432 monotonic_clock::time_point base_;
433 monotonic_clock::duration repeat_offset_;
434};
435
436class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
437 public:
438 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800439 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440 ::std::function<void(int)> fn,
441 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800442 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800443 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444
Austin Schuh7d87b672019-12-01 20:23:49 -0800445 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446
Austin Schuh7d87b672019-12-01 20:23:49 -0800447 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448
449 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800450 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800451 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700452
Austin Schuh39788ff2019-12-01 18:22:57 -0800453 EventScheduler *scheduler_;
454 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700455};
456
457class SimulatedEventLoop : public EventLoop {
458 public:
459 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700460 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700461 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
462 *channels,
463 const Configuration *configuration,
464 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800465 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800466 const Node *node, pid_t tid)
Austin Schuh83c7f702021-01-19 22:36:29 -0800467 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800469 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800471 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800472 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800473 tid_(tid) {
474 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
475 if (!has_setup_) {
476 Setup();
477 has_setup_ = true;
478 }
479 set_is_running(value);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800480 has_run_ = true;
Austin Schuh39788ff2019-12-01 18:22:57 -0800481 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700482 }
483 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800484 // Trigger any remaining senders or fetchers to be cleared before destroying
485 // the event loop so the book keeping matches.
486 timing_report_sender_.reset();
487
488 // Force everything with a registered fd with epoll to be destroyed now.
489 timers_.clear();
490 phased_loops_.clear();
491 watchers_.clear();
492
Alex Perrycb7da4b2019-08-28 19:35:56 -0700493 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
494 ++it) {
495 if (it->first == this) {
496 raw_event_loops_->erase(it);
497 break;
498 }
499 }
500 }
501
Austin Schuh8fb315a2020-11-19 22:33:58 -0800502 bool has_run() const { return has_run_; }
503
Austin Schuh7d87b672019-12-01 20:23:49 -0800504 std::chrono::nanoseconds send_delay() const { return send_delay_; }
505 void set_send_delay(std::chrono::nanoseconds send_delay) {
506 send_delay_ = send_delay;
507 }
508
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800510 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511 }
512
513 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800514 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515 }
516
517 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
518
519 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
520
521 void MakeRawWatcher(
522 const Channel *channel,
523 ::std::function<void(const Context &context, const void *message)>
524 watcher) override;
525
526 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800527 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800528 return NewTimer(::std::unique_ptr<TimerHandler>(
529 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700530 }
531
532 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
533 const monotonic_clock::duration interval,
534 const monotonic_clock::duration offset =
535 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800536 return NewPhasedLoop(
537 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
538 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700539 }
540
541 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800542 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700543 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
544 ScopedMarkRealtimeRestorer rt(priority() > 0);
545 on_run();
546 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547 }
548
Austin Schuh217a9782019-12-21 23:02:50 -0800549 const Node *node() const override { return node_; }
550
James Kuszmaul3ae42262019-11-08 12:33:41 -0800551 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 name_ = std::string(name);
553 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800554 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555
556 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
557
Austin Schuh39788ff2019-12-01 18:22:57 -0800558 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800560 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700561 }
562
Austin Schuh39788ff2019-12-01 18:22:57 -0800563 int priority() const override { return priority_; }
564
Brian Silverman6a54ff32020-04-28 16:41:39 -0700565 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
566 CHECK(!is_running()) << ": Cannot set affinity while running.";
567 }
568
Tyler Chatow67ddb032020-01-12 14:30:04 -0800569 void Setup() {
570 MaybeScheduleTimingReports();
571 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800572 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700573 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800574 }
575 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800576
Brian Silverman4f4e0612020-08-12 19:54:41 -0700577 int NumberBuffers(const Channel *channel) override;
578
Austin Schuh83c7f702021-01-19 22:36:29 -0800579 const UUID &boot_uuid() const override {
580 return node_event_loop_factory_->boot_uuid();
581 }
582
Alex Perrycb7da4b2019-08-28 19:35:56 -0700583 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800584 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800585 friend class SimulatedPhasedLoopHandler;
586 friend class SimulatedWatcher;
587
588 void HandleEvent() {
589 while (true) {
590 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
591 break;
592 }
593
594 EventLoopEvent *event = PopEvent();
595 event->HandleEvent();
596 }
597 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800598
Austin Schuh39788ff2019-12-01 18:22:57 -0800599 pid_t GetTid() override { return tid_; }
600
Alex Perrycb7da4b2019-08-28 19:35:56 -0700601 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800602 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700603 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
604 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
605 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700606
607 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800608
609 int priority_ = 0;
610
611 bool has_setup_ = false;
612
Austin Schuh7d87b672019-12-01 20:23:49 -0800613 std::chrono::nanoseconds send_delay_;
614
Austin Schuh217a9782019-12-21 23:02:50 -0800615 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800616 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800617
618 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700619 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800620
621 bool has_run_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700622};
623
Austin Schuh7d87b672019-12-01 20:23:49 -0800624void SimulatedEventLoopFactory::set_send_delay(
625 std::chrono::nanoseconds send_delay) {
626 send_delay_ = send_delay;
627 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
628 raw_event_loops_) {
629 reinterpret_cast<SimulatedEventLoop *>(loop.first)
630 ->set_send_delay(send_delay_);
631 }
632}
633
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634void SimulatedEventLoop::MakeRawWatcher(
635 const Channel *channel,
636 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800637 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800638
Austin Schuh8bd96322020-02-13 21:18:22 -0800639 std::unique_ptr<SimulatedWatcher> shm_watcher(
640 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800641
642 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
643 NewWatcher(std::move(shm_watcher));
Austin Schuh8fb315a2020-11-19 22:33:58 -0800644
645 // Order of operations gets kinda wonky if we let people make watchers after
646 // running once. If someone has a valid use case, we can reconsider.
647 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700648}
649
650std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
651 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800652 TakeSender(channel);
653
Alex Perrycb7da4b2019-08-28 19:35:56 -0700654 return GetSimulatedChannel(channel)->MakeRawSender(this);
655}
656
657std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
658 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800659 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800660
Austin Schuhca4828c2019-12-28 14:21:35 -0800661 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
662 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
663 << "\", \"type\": \"" << channel->type()->string_view()
664 << "\" } is not able to be fetched on this node. Check your "
665 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800666 }
667
Austin Schuh39788ff2019-12-01 18:22:57 -0800668 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700669}
670
671SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
672 const Channel *channel) {
673 auto it = channels_->find(SimpleChannel(channel));
674 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800675 it =
676 channels_
677 ->emplace(
678 SimpleChannel(channel),
679 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
680 channel, std::chrono::nanoseconds(
681 configuration()->channel_storage_duration()))))
682 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700683 }
684 return it->second.get();
685}
686
Brian Silverman4f4e0612020-08-12 19:54:41 -0700687int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
688 return GetSimulatedChannel(channel)->number_buffers();
689}
690
Austin Schuh7d87b672019-12-01 20:23:49 -0800691SimulatedWatcher::SimulatedWatcher(
692 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800693 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800694 std::function<void(const Context &context, const void *message)> fn)
695 : WatcherState(simulated_event_loop, channel, std::move(fn)),
696 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700697 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800698 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700699 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800700 token_(scheduler_->InvalidToken()) {}
701
702SimulatedWatcher::~SimulatedWatcher() {
703 simulated_event_loop_->RemoveEvent(&event_);
704 if (token_ != scheduler_->InvalidToken()) {
705 scheduler_->Deschedule(token_);
706 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700707 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800708}
709
Austin Schuh8fb315a2020-11-19 22:33:58 -0800710bool SimulatedWatcher::has_run() const {
711 return simulated_event_loop_->has_run();
712}
713
Austin Schuh7d87b672019-12-01 20:23:49 -0800714void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800715 monotonic_clock::time_point event_time =
716 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800717
718 // Messages are queued in order. If we are the first, add ourselves.
719 // Otherwise, don't.
720 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800721 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800722 simulated_event_loop_->AddEvent(&event_);
723
724 DoSchedule(event_time);
725 }
726
727 msgs_.emplace_back(message);
728}
729
730void SimulatedWatcher::HandleEvent() {
Austin Schuh76883b62021-03-31 21:51:23 -0700731 VLOG(1) << "Watcher " << configuration::CleanedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800732 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
733
734 const monotonic_clock::time_point monotonic_now =
735 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800736 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700737 if (simulated_event_loop_->log_impl_) {
738 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800739 }
Austin Schuhad154822019-12-27 15:45:13 -0800740 Context context = msgs_.front()->context;
741
Brian Silverman4f4e0612020-08-12 19:54:41 -0700742 if (channel_->read_method() != ReadMethod::PIN) {
743 context.buffer_index = -1;
744 }
Austin Schuhad154822019-12-27 15:45:13 -0800745 if (context.remote_queue_index == 0xffffffffu) {
746 context.remote_queue_index = context.queue_index;
747 }
748 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
749 context.monotonic_remote_time = context.monotonic_event_time;
750 }
751 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
752 context.realtime_remote_time = context.realtime_event_time;
753 }
754
Austin Schuhcc6070c2020-10-10 20:25:56 -0700755 {
756 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
757 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
758 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800759
760 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700761 if (token_ != scheduler_->InvalidToken()) {
762 scheduler_->Deschedule(token_);
763 token_ = scheduler_->InvalidToken();
764 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800765 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800766 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800767 simulated_event_loop_->AddEvent(&event_);
768
769 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800770 }
771}
772
773void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700774 CHECK(token_ == scheduler_->InvalidToken())
775 << ": May not schedule multiple times";
776 token_ = scheduler_->Schedule(
777 event_time + simulated_event_loop_->send_delay(), [this]() {
778 DCHECK(token_ != scheduler_->InvalidToken());
779 token_ = scheduler_->InvalidToken();
780 simulated_event_loop_->HandleEvent();
781 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800782}
783
784void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700785 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800786 watcher->SetSimulatedChannel(this);
787 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700788}
789
790::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800791 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700792 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
793}
794
Austin Schuh39788ff2019-12-01 18:22:57 -0800795::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
796 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700797 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800798 ::std::unique_ptr<SimulatedFetcher> fetcher(
799 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700800 fetchers_.push_back(fetcher.get());
801 return ::std::move(fetcher);
802}
803
Austin Schuhad154822019-12-27 15:45:13 -0800804uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
805 const uint32_t queue_index = next_queue_index_.index();
806 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800807 message->context.data = message->data(channel()->max_size()) +
808 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700809 next_queue_index_ = next_queue_index_.Increment();
810
811 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800812 for (SimulatedWatcher *watcher : watchers_) {
813 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800814 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700815 }
816 }
817 for (auto &fetcher : fetchers_) {
818 fetcher->Enqueue(message);
819 }
Austin Schuhad154822019-12-27 15:45:13 -0800820
821 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700822}
823
824void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
825 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
826}
827
Austin Schuh8fb315a2020-11-19 22:33:58 -0800828SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
829 SimulatedEventLoop *event_loop)
830 : RawSender(event_loop, simulated_channel->channel()),
831 simulated_channel_(simulated_channel),
832 event_loop_(event_loop) {
833 simulated_channel_->CountSenderCreated();
834}
835
836SimulatedSender::~SimulatedSender() {
837 simulated_channel_->CountSenderDestroyed();
838}
839
Austin Schuh8902fa52021-03-14 22:39:24 -0700840bool SimulatedSender::DoSend(size_t length,
841 monotonic_clock::time_point monotonic_remote_time,
842 realtime_clock::time_point realtime_remote_time,
843 uint32_t remote_queue_index,
844 const UUID &remote_boot_uuid) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800845 // The allocations in here are due to infrastructure and don't count in the
846 // no mallocs in RT code.
847 ScopedNotRealtime nrt;
848 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
849 message_->context.monotonic_event_time = event_loop_->monotonic_now();
850 message_->context.monotonic_remote_time = monotonic_remote_time;
851 message_->context.remote_queue_index = remote_queue_index;
852 message_->context.realtime_event_time = event_loop_->realtime_now();
853 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuh8902fa52021-03-14 22:39:24 -0700854 message_->context.remote_boot_uuid = remote_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800855 CHECK_LE(length, message_->context.size);
856 message_->context.size = length;
857
858 // TODO(austin): Track sending too fast.
859 sent_queue_index_ = simulated_channel_->Send(message_);
860 monotonic_sent_time_ = event_loop_->monotonic_now();
861 realtime_sent_time_ = event_loop_->realtime_now();
862
863 // Drop the reference to the message so that we allocate a new message for
864 // next time. Otherwise we will continue to reuse the same memory for all
865 // messages and corrupt it.
866 message_.reset();
867 return true;
868}
869
Austin Schuh8902fa52021-03-14 22:39:24 -0700870bool SimulatedSender::DoSend(const void *msg, size_t size,
871 monotonic_clock::time_point monotonic_remote_time,
872 realtime_clock::time_point realtime_remote_time,
873 uint32_t remote_queue_index,
874 const UUID &remote_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -0800875 CHECK_LE(size, this->size())
876 << ": Attempting to send too big a message on "
877 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -0800878
879 // This is wasteful, but since flatbuffers fill from the back end of the
880 // queue, we need it to be full sized.
881 message_ = SimulatedMessage::Make(simulated_channel_);
882
883 // Now fill in the message. size is already populated above, and
884 // queue_index will be populated in simulated_channel_. Put this at the
885 // back of the data segment.
886 memcpy(message_->data(simulated_channel_->max_size()) +
887 simulated_channel_->max_size() - size,
888 msg, size);
889
890 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700891 remote_queue_index, remote_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800892}
893
Austin Schuh39788ff2019-12-01 18:22:57 -0800894SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800895 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
896 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800897 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800898 simulated_event_loop_(simulated_event_loop),
899 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800900 scheduler_(scheduler),
901 token_(scheduler_->InvalidToken()) {}
902
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800903void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
904 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800905 // The allocations in here are due to infrastructure and don't count in the no
906 // mallocs in RT code.
907 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800908 Disable();
909 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800910 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800911 base_ = base;
912 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700913 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
914 DCHECK(token_ != scheduler_->InvalidToken());
915 token_ = scheduler_->InvalidToken();
916 simulated_event_loop_->HandleEvent();
917 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800918 event_.set_event_time(base_);
919 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800920}
921
922void SimulatedTimerHandler::HandleEvent() {
Austin Schuh76883b62021-03-31 21:51:23 -0700923 VLOG(1) << "Timer " << name();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800924 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800925 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800926 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700927 if (simulated_event_loop_->log_impl_) {
928 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800929 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700930 if (token_ != scheduler_->InvalidToken()) {
931 scheduler_->Deschedule(token_);
932 token_ = scheduler_->InvalidToken();
933 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800934 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
935 // Reschedule.
936 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700937 token_ = scheduler_->Schedule(base_, [this]() {
938 DCHECK(token_ != scheduler_->InvalidToken());
939 token_ = scheduler_->InvalidToken();
940 simulated_event_loop_->HandleEvent();
941 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800942 event_.set_event_time(base_);
943 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800944 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800945
Austin Schuhcc6070c2020-10-10 20:25:56 -0700946 {
947 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
948 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
949 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800950}
951
Austin Schuh7d87b672019-12-01 20:23:49 -0800952void SimulatedTimerHandler::Disable() {
953 simulated_event_loop_->RemoveEvent(&event_);
954 if (token_ != scheduler_->InvalidToken()) {
955 scheduler_->Deschedule(token_);
956 token_ = scheduler_->InvalidToken();
957 }
958}
959
Austin Schuh39788ff2019-12-01 18:22:57 -0800960SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800961 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
962 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800963 const monotonic_clock::duration offset)
964 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
965 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800966 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800967 scheduler_(scheduler),
968 token_(scheduler_->InvalidToken()) {}
969
Austin Schuh7d87b672019-12-01 20:23:49 -0800970SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
971 if (token_ != scheduler_->InvalidToken()) {
972 scheduler_->Deschedule(token_);
973 token_ = scheduler_->InvalidToken();
974 }
975 simulated_event_loop_->RemoveEvent(&event_);
976}
977
978void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh76883b62021-03-31 21:51:23 -0700979 VLOG(1) << "Phased loop " << name();
Austin Schuh39788ff2019-12-01 18:22:57 -0800980 monotonic_clock::time_point monotonic_now =
981 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800982 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700983 if (simulated_event_loop_->log_impl_) {
984 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800985 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700986
987 {
988 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
989 Call([monotonic_now]() { return monotonic_now; },
990 [this](monotonic_clock::time_point sleep_time) {
991 Schedule(sleep_time);
992 });
993 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800994}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800995
Austin Schuh7d87b672019-12-01 20:23:49 -0800996void SimulatedPhasedLoopHandler::Schedule(
997 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -0800998 // The allocations in here are due to infrastructure and don't count in the no
999 // mallocs in RT code.
1000 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001001 if (token_ != scheduler_->InvalidToken()) {
1002 scheduler_->Deschedule(token_);
1003 token_ = scheduler_->InvalidToken();
1004 }
1005 token_ = scheduler_->Schedule(sleep_time, [this]() {
1006 DCHECK(token_ != scheduler_->InvalidToken());
1007 token_ = scheduler_->InvalidToken();
1008 simulated_event_loop_->HandleEvent();
1009 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001010 event_.set_event_time(sleep_time);
1011 simulated_event_loop_->AddEvent(&event_);
1012}
1013
Austin Schuhac0771c2020-01-07 18:36:30 -08001014NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -08001015 EventSchedulerScheduler *scheduler_scheduler,
1016 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -08001017 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
1018 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -08001019 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
1020 scheduler_scheduler->AddEventScheduler(&scheduler_);
1021}
Austin Schuhac0771c2020-01-07 18:36:30 -08001022
Alex Perrycb7da4b2019-08-28 19:35:56 -07001023SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1024 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001025 : configuration_(CHECK_NOTNULL(configuration)),
1026 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001027 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001028 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001029 node_factories_.emplace_back(new NodeEventLoopFactory(
1030 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -08001031 }
Austin Schuh898f4972020-01-11 17:21:25 -08001032
1033 if (configuration::MultiNode(configuration)) {
1034 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1035 }
Austin Schuh15649d62019-12-28 16:36:38 -08001036}
1037
Alex Perrycb7da4b2019-08-28 19:35:56 -07001038SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1039
Austin Schuhac0771c2020-01-07 18:36:30 -08001040NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
1041 const Node *node) {
1042 auto result = std::find_if(
1043 node_factories_.begin(), node_factories_.end(),
1044 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1045 return node_factory->node() == node;
1046 });
1047
1048 CHECK(result != node_factories_.end())
1049 << ": Failed to find node " << FlatbufferToJson(node);
1050
1051 return result->get();
1052}
1053
Austin Schuh87dd3832021-01-01 23:07:31 -08001054void SimulatedEventLoopFactory::SetTimeConverter(
1055 TimeConverter *time_converter) {
1056 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1057 factory->SetTimeConverter(time_converter);
1058 }
1059}
1060
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001061::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001062 std::string_view name, const Node *node) {
1063 if (node == nullptr) {
1064 CHECK(!configuration::MultiNode(configuration()))
1065 << ": Can't make a single node event loop in a multi-node world.";
1066 } else {
1067 CHECK(configuration::MultiNode(configuration()))
1068 << ": Can't make a multi-node event loop in a single-node world.";
1069 }
1070 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1071}
1072
1073::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001074 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001075 CHECK(!scheduler_.is_running())
1076 << ": Can't create an event loop while running";
1077
Austin Schuh39788ff2019-12-01 18:22:57 -08001078 pid_t tid = tid_;
1079 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001080 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -08001081 &scheduler_, this, &channels_, factory_->configuration(),
1082 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001083 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001084 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001085 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001086}
1087
Austin Schuhc0b0f722020-12-12 18:36:06 -08001088void NodeEventLoopFactory::Disconnect(const Node *other) {
1089 factory_->bridge_->Disconnect(node_, other);
1090}
1091void NodeEventLoopFactory::Connect(const Node *other) {
1092 factory_->bridge_->Connect(node_, other);
1093}
1094
Alex Perrycb7da4b2019-08-28 19:35:56 -07001095void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1096 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1097 raw_event_loops_) {
1098 event_loop.second(true);
1099 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001100 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001101 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1102 raw_event_loops_) {
1103 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001104 }
1105}
1106
1107void SimulatedEventLoopFactory::Run() {
1108 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1109 raw_event_loops_) {
1110 event_loop.second(true);
1111 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001112 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001113 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1114 raw_event_loops_) {
1115 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001116 }
1117}
1118
Austin Schuh87dd3832021-01-01 23:07:31 -08001119void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001120
Austin Schuh6f3babe2020-01-26 20:34:50 -08001121void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001122 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001123 bridge_->DisableForwarding(channel);
1124}
1125
Austin Schuh4c3b9702020-08-30 11:34:55 -07001126void SimulatedEventLoopFactory::DisableStatistics() {
1127 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1128 bridge_->DisableStatistics();
1129}
1130
Austin Schuh2928ebe2021-02-07 22:10:27 -08001131void SimulatedEventLoopFactory::SkipTimingReport() {
1132 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
1133 bridge_->SkipTimingReport();
1134}
1135
Alex Perrycb7da4b2019-08-28 19:35:56 -07001136} // namespace aos