blob: afa1f1a9c503caee107f1b9097ca5b45c5c90069 [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 Schuh057d29f2021-08-21 23:05:15 -070024std::string NodeName(const Node *node) {
25 if (node == nullptr) {
26 return "";
27 }
28
29 return absl::StrCat(node->name()->string_view(), " ");
30}
31
Austin Schuhcc6070c2020-10-10 20:25:56 -070032class ScopedMarkRealtimeRestorer {
33 public:
34 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
35 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
36
37 private:
38 const bool rt_;
39 const bool prior_;
40};
41
Alex Perrycb7da4b2019-08-28 19:35:56 -070042// Container for both a message, and the context for it for simulation. This
43// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070044struct SimulatedMessage final {
45 SimulatedMessage(const SimulatedMessage &) = delete;
46 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
47
48 // Creates a SimulatedMessage with size bytes of storage.
49 // This is a shared_ptr so we don't have to implement refcounting or copying.
50 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel);
51
Alex Perrycb7da4b2019-08-28 19:35:56 -070052 // Context for the data.
53 Context context;
54
Brian Silverman661eb8d2020-08-12 19:41:01 -070055 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070056
Alex Perrycb7da4b2019-08-28 19:35:56 -070057 // The data.
Brian Silvermana1652f32020-01-29 20:41:44 -080058 char *data(size_t buffer_size) {
59 return RoundChannelData(&actual_data[0], buffer_size);
60 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070061
Brian Silvermana1652f32020-01-29 20:41:44 -080062 // Then the data, including padding on the end so we can align the buffer we
63 // actually return from data().
64 char actual_data[];
Brian Silverman661eb8d2020-08-12 19:41:01 -070065
66 private:
67 SimulatedMessage(SimulatedChannel *channel_in);
68 ~SimulatedMessage();
69
70 static void DestroyAndFree(SimulatedMessage *p) {
71 p->~SimulatedMessage();
72 free(p);
73 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070074};
75
Brian Silverman661eb8d2020-08-12 19:41:01 -070076} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080077
Brian Silverman661eb8d2020-08-12 19:41:01 -070078// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
79// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -080080class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080081 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080082 SimulatedWatcher(
83 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
84 const Channel *channel,
85 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080086
Austin Schuh7d87b672019-12-01 20:23:49 -080087 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080088
Austin Schuh8fb315a2020-11-19 22:33:58 -080089 bool has_run() const;
90
Austin Schuh39788ff2019-12-01 18:22:57 -080091 void Startup(EventLoop * /*event_loop*/) override {}
92
Austin Schuh7d87b672019-12-01 20:23:49 -080093 void Schedule(std::shared_ptr<SimulatedMessage> message);
94
95 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080096
97 void SetSimulatedChannel(SimulatedChannel *channel) {
98 simulated_channel_ = channel;
99 }
100
101 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800102 void DoSchedule(monotonic_clock::time_point event_time);
103
104 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
105
Brian Silverman4f4e0612020-08-12 19:54:41 -0700106 SimulatedEventLoop *const simulated_event_loop_;
107 const Channel *const channel_;
108 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800109 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800110 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800111 SimulatedChannel *simulated_channel_ = nullptr;
112};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700113
114class SimulatedChannel {
115 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800116 explicit SimulatedChannel(const Channel *channel,
Brian Silverman661eb8d2020-08-12 19:41:01 -0700117 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800118 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700119 channel_storage_duration_(channel_storage_duration),
120 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
121 available_buffer_indices_.reserve(number_buffers());
122 for (int i = 0; i < number_buffers(); ++i) {
123 available_buffer_indices_.push_back(i);
124 }
125 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700126
Brian Silverman661eb8d2020-08-12 19:41:01 -0700127 ~SimulatedChannel() {
128 latest_message_.reset();
129 CHECK_EQ(static_cast<size_t>(number_buffers()),
130 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800131 CHECK_EQ(0u, fetchers_.size())
132 << configuration::StrippedChannelToString(channel());
133 CHECK_EQ(0u, watchers_.size())
134 << configuration::StrippedChannelToString(channel());
135 CHECK_EQ(0, sender_count_)
136 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700137 }
138
139 // The number of messages we pretend to have in the queue.
140 int queue_size() const {
141 return channel()->frequency() *
142 std::chrono::duration_cast<std::chrono::duration<double>>(
143 channel_storage_duration_)
144 .count();
145 }
146
147 // The number of extra buffers (beyond the queue) we pretend to have.
148 int number_scratch_buffers() const {
149 // We need to start creating messages before we know how many
150 // senders+readers we'll have, so we need to just pick something which is
151 // always big enough.
152 return 50;
153 }
154
155 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
156
157 int GetBufferIndex() {
158 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
159 const int result = available_buffer_indices_.back();
160 available_buffer_indices_.pop_back();
161 return result;
162 }
163
164 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700165 // This extra checking has a large performance hit with sanitizers that
166 // track memory accesses, so just skip it.
167#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700168 DCHECK(std::find(available_buffer_indices_.begin(),
169 available_buffer_indices_.end(),
170 i) == available_buffer_indices_.end())
171 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800172#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700173 available_buffer_indices_.push_back(i);
174 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700175
176 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800177 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700178
179 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800180 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700181
182 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800183 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800184
Austin Schuh7d87b672019-12-01 20:23:49 -0800185 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800186 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
187 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700188
Austin Schuhad154822019-12-27 15:45:13 -0800189 // Sends the message to all the connected receivers and fetchers. Returns the
190 // sent queue index.
191 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700192
193 // Unregisters a fetcher.
194 void UnregisterFetcher(SimulatedFetcher *fetcher);
195
196 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
197
Austin Schuh39788ff2019-12-01 18:22:57 -0800198 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700199
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800200 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800201 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700202 }
203
Austin Schuh39788ff2019-12-01 18:22:57 -0800204 const Channel *channel() const { return channel_; }
205
Austin Schuhe516ab02020-05-06 21:37:04 -0700206 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700207 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700208 if (sender_count_ >= channel()->num_senders()) {
209 LOG(FATAL) << "Failed to create sender on "
210 << configuration::CleanedChannelToString(channel())
211 << ", too many senders.";
212 }
213 ++sender_count_;
214 }
Brian Silverman77162972020-08-12 19:52:40 -0700215
Austin Schuhe516ab02020-05-06 21:37:04 -0700216 void CountSenderDestroyed() {
217 --sender_count_;
218 CHECK_GE(sender_count_, 0);
219 }
220
Alex Perrycb7da4b2019-08-28 19:35:56 -0700221 private:
Brian Silverman77162972020-08-12 19:52:40 -0700222 void CheckBufferCount() {
223 int reader_count = 0;
224 if (channel()->read_method() == ReadMethod::PIN) {
225 reader_count = watchers_.size() + fetchers_.size();
226 }
227 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
228 }
229
230 void CheckReaderCount() {
231 if (channel()->read_method() != ReadMethod::PIN) {
232 return;
233 }
234 CheckBufferCount();
235 const int reader_count = watchers_.size() + fetchers_.size();
236 if (reader_count >= channel()->num_readers()) {
237 LOG(FATAL) << "Failed to create reader on "
238 << configuration::CleanedChannelToString(channel())
239 << ", too many readers.";
240 }
241 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700242
243 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700244 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700245
246 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800247 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700248
249 // List of all fetchers.
250 ::std::vector<SimulatedFetcher *> fetchers_;
251 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700252
253 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700254
255 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700256
257 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700258};
259
260namespace {
261
Brian Silverman661eb8d2020-08-12 19:41:01 -0700262std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
263 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800264 // The allocations in here are due to infrastructure and don't count in the no
265 // mallocs in RT code.
266 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700267 const size_t size = channel->max_size();
268 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800269 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700270 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700271 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800272 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700273
Brian Silverman661eb8d2020-08-12 19:41:01 -0700274 return std::shared_ptr<SimulatedMessage>(message,
275 &SimulatedMessage::DestroyAndFree);
276}
277
278SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
279 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700280 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700281}
282
283SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700284 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285}
286
287class SimulatedSender : public RawSender {
288 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800289 SimulatedSender(SimulatedChannel *simulated_channel,
290 SimulatedEventLoop *event_loop);
291 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700292
293 void *data() override {
294 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700295 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800297 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700298 }
299
300 size_t size() override { return simulated_channel_->max_size(); }
301
Austin Schuhad154822019-12-27 15:45:13 -0800302 bool DoSend(size_t length,
303 aos::monotonic_clock::time_point monotonic_remote_time,
304 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700305 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700306 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307
Austin Schuhad154822019-12-27 15:45:13 -0800308 bool DoSend(const void *msg, size_t size,
309 aos::monotonic_clock::time_point monotonic_remote_time,
310 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700311 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700312 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700313
Brian Silverman4f4e0612020-08-12 19:54:41 -0700314 int buffer_index() override {
315 // First, ensure message_ is allocated.
316 data();
317 return message_->context.buffer_index;
318 }
319
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 private:
321 SimulatedChannel *simulated_channel_;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800322 SimulatedEventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323
324 std::shared_ptr<SimulatedMessage> message_;
325};
326} // namespace
327
328class SimulatedFetcher : public RawFetcher {
329 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800330 explicit SimulatedFetcher(EventLoop *event_loop,
331 SimulatedChannel *simulated_channel)
332 : RawFetcher(event_loop, simulated_channel->channel()),
333 simulated_channel_(simulated_channel) {}
334 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700335
Austin Schuh39788ff2019-12-01 18:22:57 -0800336 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800337 // The allocations in here are due to infrastructure and don't count in the
338 // no mallocs in RT code.
339 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800340 if (msgs_.size() == 0) {
341 return std::make_pair(false, monotonic_clock::min_time);
342 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700344 CHECK(!fell_behind_) << ": Got behind on "
345 << configuration::StrippedChannelToString(
346 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700347
Alex Perrycb7da4b2019-08-28 19:35:56 -0700348 SetMsg(msgs_.front());
349 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800350 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700351 }
352
Austin Schuh39788ff2019-12-01 18:22:57 -0800353 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800354 // The allocations in here are due to infrastructure and don't count in the
355 // no mallocs in RT code.
356 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800358 // TODO(austin): Can we just do this logic unconditionally? It is a lot
359 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800360 if (!msg_ && simulated_channel_->latest_message()) {
361 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800362 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700363 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800364 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365 }
366 }
367
368 // We've had a message enqueued, so we don't need to go looking for the
369 // latest message from before we started.
370 SetMsg(msgs_.back());
371 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700372 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800373 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374 }
375
376 private:
377 friend class SimulatedChannel;
378
379 // Updates the state inside RawFetcher to point to the data in msg_.
380 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
381 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700382 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700383 if (channel()->read_method() != ReadMethod::PIN) {
384 context_.buffer_index = -1;
385 }
Austin Schuhad154822019-12-27 15:45:13 -0800386 if (context_.remote_queue_index == 0xffffffffu) {
387 context_.remote_queue_index = context_.queue_index;
388 }
389 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
390 context_.monotonic_remote_time = context_.monotonic_event_time;
391 }
392 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
393 context_.realtime_remote_time = context_.realtime_event_time;
394 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395 }
396
397 // Internal method for Simulation to add a message to the buffer.
398 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
399 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700400 if (fell_behind_ ||
401 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
402 fell_behind_ = true;
403 // Might as well empty out all the intermediate messages now.
404 while (msgs_.size() > 1) {
405 msgs_.pop_front();
406 }
407 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408 }
409
Austin Schuhac0771c2020-01-07 18:36:30 -0800410 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411 std::shared_ptr<SimulatedMessage> msg_;
412
413 // Messages queued up but not in use.
414 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700415
416 // Whether we're currently "behind", which means a FetchNext call will fail.
417 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700418};
419
420class SimulatedTimerHandler : public TimerHandler {
421 public:
422 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800423 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800424 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800425 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426
427 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800428 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700429
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800430 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700431
Austin Schuh7d87b672019-12-01 20:23:49 -0800432 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800435 SimulatedEventLoop *simulated_event_loop_;
436 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700437 EventScheduler *scheduler_;
438 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800439
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440 monotonic_clock::time_point base_;
441 monotonic_clock::duration repeat_offset_;
442};
443
444class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
445 public:
446 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800447 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 ::std::function<void(int)> fn,
449 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800450 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800451 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700452
Austin Schuh7d87b672019-12-01 20:23:49 -0800453 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454
Austin Schuh7d87b672019-12-01 20:23:49 -0800455 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700456
457 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800458 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800459 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460
Austin Schuh39788ff2019-12-01 18:22:57 -0800461 EventScheduler *scheduler_;
462 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700463};
464
465class SimulatedEventLoop : public EventLoop {
466 public:
467 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700468 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
470 *channels,
471 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700472 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
473 pid_t tid)
Austin Schuh83c7f702021-01-19 22:36:29 -0800474 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700475 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800476 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700478 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800479 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800480 tid_(tid) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700481 scheduler_->ScheduleOnStartup([this]() {
482 Setup();
483 has_setup_ = true;
484 });
485
486 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700487 }
488 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800489 // Trigger any remaining senders or fetchers to be cleared before destroying
490 // the event loop so the book keeping matches.
491 timing_report_sender_.reset();
492
493 // Force everything with a registered fd with epoll to be destroyed now.
494 timers_.clear();
495 phased_loops_.clear();
496 watchers_.clear();
497
Austin Schuh057d29f2021-08-21 23:05:15 -0700498 for (auto it = event_loops_->begin(); it != event_loops_->end();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700499 ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700500 if (*it == this) {
501 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700502 break;
503 }
504 }
505 }
506
Austin Schuh057d29f2021-08-21 23:05:15 -0700507 void SetIsRunning(bool running) {
508 CHECK(has_setup_);
509
510 set_is_running(running);
511 has_run_ = true;
512 }
513
Austin Schuh8fb315a2020-11-19 22:33:58 -0800514 bool has_run() const { return has_run_; }
515
Austin Schuh7d87b672019-12-01 20:23:49 -0800516 std::chrono::nanoseconds send_delay() const { return send_delay_; }
517 void set_send_delay(std::chrono::nanoseconds send_delay) {
518 send_delay_ = send_delay;
519 }
520
Alex Perrycb7da4b2019-08-28 19:35:56 -0700521 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800522 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700523 }
524
525 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800526 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700527 }
528
529 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
530
531 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
532
533 void MakeRawWatcher(
534 const Channel *channel,
535 ::std::function<void(const Context &context, const void *message)>
536 watcher) override;
537
538 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800539 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800540 return NewTimer(::std::unique_ptr<TimerHandler>(
541 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542 }
543
544 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
545 const monotonic_clock::duration interval,
546 const monotonic_clock::duration offset =
547 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800548 return NewPhasedLoop(
549 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
550 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700551 }
552
553 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800554 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700555 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
556 ScopedMarkRealtimeRestorer rt(priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700557 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700558 on_run();
559 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560 }
561
Austin Schuh217a9782019-12-21 23:02:50 -0800562 const Node *node() const override { return node_; }
563
James Kuszmaul3ae42262019-11-08 12:33:41 -0800564 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565 name_ = std::string(name);
566 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800567 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700568
569 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
570
Austin Schuh39788ff2019-12-01 18:22:57 -0800571 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700572 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800573 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700574 }
575
Austin Schuh39788ff2019-12-01 18:22:57 -0800576 int priority() const override { return priority_; }
577
Brian Silverman6a54ff32020-04-28 16:41:39 -0700578 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
579 CHECK(!is_running()) << ": Cannot set affinity while running.";
580 }
581
Tyler Chatow67ddb032020-01-12 14:30:04 -0800582 void Setup() {
583 MaybeScheduleTimingReports();
584 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800585 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700586 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800587 }
588 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800589
Brian Silverman4f4e0612020-08-12 19:54:41 -0700590 int NumberBuffers(const Channel *channel) override;
591
Austin Schuh83c7f702021-01-19 22:36:29 -0800592 const UUID &boot_uuid() const override {
593 return node_event_loop_factory_->boot_uuid();
594 }
595
Alex Perrycb7da4b2019-08-28 19:35:56 -0700596 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800597 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800598 friend class SimulatedPhasedLoopHandler;
599 friend class SimulatedWatcher;
600
601 void HandleEvent() {
602 while (true) {
603 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
604 break;
605 }
606
607 EventLoopEvent *event = PopEvent();
608 event->HandleEvent();
609 }
610 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800611
Austin Schuh39788ff2019-12-01 18:22:57 -0800612 pid_t GetTid() override { return tid_; }
613
Alex Perrycb7da4b2019-08-28 19:35:56 -0700614 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800615 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700616 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700617 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618
619 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800620
621 int priority_ = 0;
622
623 bool has_setup_ = false;
624
Austin Schuh7d87b672019-12-01 20:23:49 -0800625 std::chrono::nanoseconds send_delay_;
626
Austin Schuh217a9782019-12-21 23:02:50 -0800627 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800628 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800629
630 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700631 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800632
633 bool has_run_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634};
635
Austin Schuh7d87b672019-12-01 20:23:49 -0800636void SimulatedEventLoopFactory::set_send_delay(
637 std::chrono::nanoseconds send_delay) {
638 send_delay_ = send_delay;
Austin Schuh057d29f2021-08-21 23:05:15 -0700639 for (std::unique_ptr<NodeEventLoopFactory> & node : node_factories_) {
640 if (node) {
641 for (SimulatedEventLoop *loop : node->event_loops_) {
642 loop->set_send_delay(send_delay_);
643 }
644 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800645 }
646}
647
Alex Perrycb7da4b2019-08-28 19:35:56 -0700648void SimulatedEventLoop::MakeRawWatcher(
649 const Channel *channel,
650 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800651 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800652
Austin Schuh057d29f2021-08-21 23:05:15 -0700653 std::unique_ptr<SimulatedWatcher> shm_watcher =
654 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
655 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800656
657 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700658
Austin Schuh39788ff2019-12-01 18:22:57 -0800659 NewWatcher(std::move(shm_watcher));
Austin Schuh057d29f2021-08-21 23:05:15 -0700660 VLOG(1) << monotonic_now() << " " << NodeName(node()) << name()
661 << " MakeRawWatcher "
662 << configuration::StrippedChannelToString(channel);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800663
664 // Order of operations gets kinda wonky if we let people make watchers after
665 // running once. If someone has a valid use case, we can reconsider.
666 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700667}
668
669std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
670 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800671 TakeSender(channel);
672
Austin Schuh057d29f2021-08-21 23:05:15 -0700673 VLOG(1) << monotonic_now() << " " << NodeName(node()) << name()
674 << " MakeRawSender "
675 << configuration::StrippedChannelToString(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700676 return GetSimulatedChannel(channel)->MakeRawSender(this);
677}
678
679std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
680 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800681 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800682
Austin Schuhca4828c2019-12-28 14:21:35 -0800683 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
684 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
685 << "\", \"type\": \"" << channel->type()->string_view()
686 << "\" } is not able to be fetched on this node. Check your "
687 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800688 }
689
Austin Schuh057d29f2021-08-21 23:05:15 -0700690 VLOG(1) << monotonic_now() << " " << NodeName(node()) << name()
691 << " MakeRawFetcher "
692 << configuration::StrippedChannelToString(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800693 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700694}
695
696SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
697 const Channel *channel) {
698 auto it = channels_->find(SimpleChannel(channel));
699 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800700 it =
701 channels_
702 ->emplace(
703 SimpleChannel(channel),
704 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
705 channel, std::chrono::nanoseconds(
706 configuration()->channel_storage_duration()))))
707 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700708 }
709 return it->second.get();
710}
711
Brian Silverman4f4e0612020-08-12 19:54:41 -0700712int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
713 return GetSimulatedChannel(channel)->number_buffers();
714}
715
Austin Schuh7d87b672019-12-01 20:23:49 -0800716SimulatedWatcher::SimulatedWatcher(
717 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800718 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800719 std::function<void(const Context &context, const void *message)> fn)
720 : WatcherState(simulated_event_loop, channel, std::move(fn)),
721 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700722 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800723 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700724 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800725 token_(scheduler_->InvalidToken()) {}
726
727SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh057d29f2021-08-21 23:05:15 -0700728 VLOG(1) << simulated_event_loop_->monotonic_now() << " "
729 << NodeName(simulated_event_loop_->node())
730 << simulated_event_loop_->name() << " Stopped Watching "
731 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800732 simulated_event_loop_->RemoveEvent(&event_);
733 if (token_ != scheduler_->InvalidToken()) {
734 scheduler_->Deschedule(token_);
735 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700736 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800737}
738
Austin Schuh8fb315a2020-11-19 22:33:58 -0800739bool SimulatedWatcher::has_run() const {
740 return simulated_event_loop_->has_run();
741}
742
Austin Schuh7d87b672019-12-01 20:23:49 -0800743void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800744 monotonic_clock::time_point event_time =
745 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800746
747 // Messages are queued in order. If we are the first, add ourselves.
748 // Otherwise, don't.
749 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800750 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800751 simulated_event_loop_->AddEvent(&event_);
752
753 DoSchedule(event_time);
754 }
755
756 msgs_.emplace_back(message);
757}
758
759void SimulatedWatcher::HandleEvent() {
Austin Schuh7d87b672019-12-01 20:23:49 -0800760 const monotonic_clock::time_point monotonic_now =
761 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -0700762 VLOG(1) << monotonic_now << " " << NodeName(simulated_event_loop_->node())
763 << "Watcher " << simulated_event_loop_->name() << ", "
764 << configuration::StrippedChannelToString(channel_);
765 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
766
Tyler Chatow67ddb032020-01-12 14:30:04 -0800767 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700768 if (simulated_event_loop_->log_impl_) {
769 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800770 }
Austin Schuhad154822019-12-27 15:45:13 -0800771 Context context = msgs_.front()->context;
772
Brian Silverman4f4e0612020-08-12 19:54:41 -0700773 if (channel_->read_method() != ReadMethod::PIN) {
774 context.buffer_index = -1;
775 }
Austin Schuhad154822019-12-27 15:45:13 -0800776 if (context.remote_queue_index == 0xffffffffu) {
777 context.remote_queue_index = context.queue_index;
778 }
779 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
780 context.monotonic_remote_time = context.monotonic_event_time;
781 }
782 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
783 context.realtime_remote_time = context.realtime_event_time;
784 }
785
Austin Schuhcc6070c2020-10-10 20:25:56 -0700786 {
787 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
788 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
789 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800790
791 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700792 if (token_ != scheduler_->InvalidToken()) {
793 scheduler_->Deschedule(token_);
794 token_ = scheduler_->InvalidToken();
795 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800796 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800797 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800798 simulated_event_loop_->AddEvent(&event_);
799
800 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800801 }
802}
803
804void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700805 CHECK(token_ == scheduler_->InvalidToken())
806 << ": May not schedule multiple times";
807 token_ = scheduler_->Schedule(
808 event_time + simulated_event_loop_->send_delay(), [this]() {
809 DCHECK(token_ != scheduler_->InvalidToken());
810 token_ = scheduler_->InvalidToken();
811 simulated_event_loop_->HandleEvent();
812 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800813}
814
815void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700816 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800817 watcher->SetSimulatedChannel(this);
818 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700819}
820
821::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800822 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700823 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
824}
825
Austin Schuh39788ff2019-12-01 18:22:57 -0800826::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
827 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700828 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800829 ::std::unique_ptr<SimulatedFetcher> fetcher(
830 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700831 fetchers_.push_back(fetcher.get());
832 return ::std::move(fetcher);
833}
834
Austin Schuhad154822019-12-27 15:45:13 -0800835uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
836 const uint32_t queue_index = next_queue_index_.index();
837 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800838 message->context.data = message->data(channel()->max_size()) +
839 channel()->max_size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -0700840
841 DCHECK(channel()->has_schema())
842 << ": Missing schema for channel "
843 << configuration::StrippedChannelToString(channel());
844 DCHECK(flatbuffers::Verify(
845 *channel()->schema(), *channel()->schema()->root_table(),
846 static_cast<const uint8_t *>(message->context.data),
847 message->context.size))
848 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
849 << channel()->type()->c_str();
850
Alex Perrycb7da4b2019-08-28 19:35:56 -0700851 next_queue_index_ = next_queue_index_.Increment();
852
853 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800854 for (SimulatedWatcher *watcher : watchers_) {
855 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800856 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700857 }
858 }
859 for (auto &fetcher : fetchers_) {
860 fetcher->Enqueue(message);
861 }
Austin Schuhad154822019-12-27 15:45:13 -0800862
863 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700864}
865
866void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
867 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
868}
869
Austin Schuh8fb315a2020-11-19 22:33:58 -0800870SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
871 SimulatedEventLoop *event_loop)
872 : RawSender(event_loop, simulated_channel->channel()),
873 simulated_channel_(simulated_channel),
874 event_loop_(event_loop) {
875 simulated_channel_->CountSenderCreated();
876}
877
878SimulatedSender::~SimulatedSender() {
879 simulated_channel_->CountSenderDestroyed();
880}
881
Austin Schuh8902fa52021-03-14 22:39:24 -0700882bool SimulatedSender::DoSend(size_t length,
883 monotonic_clock::time_point monotonic_remote_time,
884 realtime_clock::time_point realtime_remote_time,
885 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700886 const UUID &source_boot_uuid) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700887 VLOG(1) << event_loop_->monotonic_now() << " "
888 << NodeName(event_loop_->node()) << event_loop_->name()
889 << " Send " << configuration::StrippedChannelToString(channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -0800890 // The allocations in here are due to infrastructure and don't count in the
891 // no mallocs in RT code.
892 ScopedNotRealtime nrt;
893 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
894 message_->context.monotonic_event_time = event_loop_->monotonic_now();
895 message_->context.monotonic_remote_time = monotonic_remote_time;
896 message_->context.remote_queue_index = remote_queue_index;
897 message_->context.realtime_event_time = event_loop_->realtime_now();
898 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -0700899 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800900 CHECK_LE(length, message_->context.size);
901 message_->context.size = length;
902
903 // TODO(austin): Track sending too fast.
904 sent_queue_index_ = simulated_channel_->Send(message_);
905 monotonic_sent_time_ = event_loop_->monotonic_now();
906 realtime_sent_time_ = event_loop_->realtime_now();
907
908 // Drop the reference to the message so that we allocate a new message for
909 // next time. Otherwise we will continue to reuse the same memory for all
910 // messages and corrupt it.
911 message_.reset();
912 return true;
913}
914
Austin Schuh8902fa52021-03-14 22:39:24 -0700915bool SimulatedSender::DoSend(const void *msg, size_t size,
916 monotonic_clock::time_point monotonic_remote_time,
917 realtime_clock::time_point realtime_remote_time,
918 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700919 const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -0800920 CHECK_LE(size, this->size())
921 << ": Attempting to send too big a message on "
922 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -0800923
924 // This is wasteful, but since flatbuffers fill from the back end of the
925 // queue, we need it to be full sized.
926 message_ = SimulatedMessage::Make(simulated_channel_);
927
928 // Now fill in the message. size is already populated above, and
929 // queue_index will be populated in simulated_channel_. Put this at the
930 // back of the data segment.
931 memcpy(message_->data(simulated_channel_->max_size()) +
932 simulated_channel_->max_size() - size,
933 msg, size);
934
935 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700936 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800937}
938
Austin Schuh39788ff2019-12-01 18:22:57 -0800939SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800940 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
941 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800942 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800943 simulated_event_loop_(simulated_event_loop),
944 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800945 scheduler_(scheduler),
946 token_(scheduler_->InvalidToken()) {}
947
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800948void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
949 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800950 // The allocations in here are due to infrastructure and don't count in the no
951 // mallocs in RT code.
952 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800953 Disable();
954 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800955 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800956 base_ = base;
957 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700958 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
959 DCHECK(token_ != scheduler_->InvalidToken());
960 token_ = scheduler_->InvalidToken();
961 simulated_event_loop_->HandleEvent();
962 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800963 event_.set_event_time(base_);
964 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800965}
966
967void SimulatedTimerHandler::HandleEvent() {
968 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800969 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -0700970 VLOG(1) << monotonic_now << " " << NodeName(simulated_event_loop_->node())
971 << "Timer '" << simulated_event_loop_->name() << "', '" << name()
972 << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -0800973 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700974 if (simulated_event_loop_->log_impl_) {
975 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800976 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700977 if (token_ != scheduler_->InvalidToken()) {
978 scheduler_->Deschedule(token_);
979 token_ = scheduler_->InvalidToken();
980 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800981 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
982 // Reschedule.
983 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700984 token_ = scheduler_->Schedule(base_, [this]() {
985 DCHECK(token_ != scheduler_->InvalidToken());
986 token_ = scheduler_->InvalidToken();
987 simulated_event_loop_->HandleEvent();
988 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800989 event_.set_event_time(base_);
990 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800991 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800992
Austin Schuhcc6070c2020-10-10 20:25:56 -0700993 {
994 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
995 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
996 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800997}
998
Austin Schuh7d87b672019-12-01 20:23:49 -0800999void SimulatedTimerHandler::Disable() {
1000 simulated_event_loop_->RemoveEvent(&event_);
1001 if (token_ != scheduler_->InvalidToken()) {
1002 scheduler_->Deschedule(token_);
1003 token_ = scheduler_->InvalidToken();
1004 }
1005}
1006
Austin Schuh39788ff2019-12-01 18:22:57 -08001007SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001008 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1009 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001010 const monotonic_clock::duration offset)
1011 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1012 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001013 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001014 scheduler_(scheduler),
1015 token_(scheduler_->InvalidToken()) {}
1016
Austin Schuh7d87b672019-12-01 20:23:49 -08001017SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1018 if (token_ != scheduler_->InvalidToken()) {
1019 scheduler_->Deschedule(token_);
1020 token_ = scheduler_->InvalidToken();
1021 }
1022 simulated_event_loop_->RemoveEvent(&event_);
1023}
1024
1025void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -08001026 monotonic_clock::time_point monotonic_now =
1027 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001028 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1029 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001030 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001031 if (simulated_event_loop_->log_impl_) {
1032 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001033 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001034
1035 {
1036 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1037 Call([monotonic_now]() { return monotonic_now; },
1038 [this](monotonic_clock::time_point sleep_time) {
1039 Schedule(sleep_time);
1040 });
1041 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001042}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001043
Austin Schuh7d87b672019-12-01 20:23:49 -08001044void SimulatedPhasedLoopHandler::Schedule(
1045 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001046 // The allocations in here are due to infrastructure and don't count in the no
1047 // mallocs in RT code.
1048 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001049 if (token_ != scheduler_->InvalidToken()) {
1050 scheduler_->Deschedule(token_);
1051 token_ = scheduler_->InvalidToken();
1052 }
1053 token_ = scheduler_->Schedule(sleep_time, [this]() {
1054 DCHECK(token_ != scheduler_->InvalidToken());
1055 token_ = scheduler_->InvalidToken();
1056 simulated_event_loop_->HandleEvent();
1057 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001058 event_.set_event_time(sleep_time);
1059 simulated_event_loop_->AddEvent(&event_);
1060}
1061
Alex Perrycb7da4b2019-08-28 19:35:56 -07001062SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1063 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001064 : configuration_(CHECK_NOTNULL(configuration)),
1065 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001066 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001067 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001068 node_factories_.emplace_back(new NodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001069 &scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001070 }
Austin Schuh898f4972020-01-11 17:21:25 -08001071
1072 if (configuration::MultiNode(configuration)) {
1073 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1074 }
Austin Schuh15649d62019-12-28 16:36:38 -08001075}
1076
Alex Perrycb7da4b2019-08-28 19:35:56 -07001077SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1078
Austin Schuhac0771c2020-01-07 18:36:30 -08001079NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001080 std::string_view node) {
1081 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1082}
1083
1084NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001085 const Node *node) {
1086 auto result = std::find_if(
1087 node_factories_.begin(), node_factories_.end(),
1088 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1089 return node_factory->node() == node;
1090 });
1091
1092 CHECK(result != node_factories_.end())
1093 << ": Failed to find node " << FlatbufferToJson(node);
1094
1095 return result->get();
1096}
1097
Austin Schuh87dd3832021-01-01 23:07:31 -08001098void SimulatedEventLoopFactory::SetTimeConverter(
1099 TimeConverter *time_converter) {
1100 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1101 factory->SetTimeConverter(time_converter);
1102 }
1103}
1104
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001105::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001106 std::string_view name, const Node *node) {
1107 if (node == nullptr) {
1108 CHECK(!configuration::MultiNode(configuration()))
1109 << ": Can't make a single node event loop in a multi-node world.";
1110 } else {
1111 CHECK(configuration::MultiNode(configuration()))
1112 << ": Can't make a multi-node event loop in a single-node world.";
1113 }
1114 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1115}
1116
Austin Schuh057d29f2021-08-21 23:05:15 -07001117NodeEventLoopFactory::NodeEventLoopFactory(
1118 EventSchedulerScheduler *scheduler_scheduler,
1119 SimulatedEventLoopFactory *factory, const Node *node)
1120 : factory_(factory), node_(node) {
1121 scheduler_scheduler->AddEventScheduler(&scheduler_);
1122}
1123
1124NodeEventLoopFactory::~NodeEventLoopFactory() {
1125 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1126}
1127
Austin Schuhac0771c2020-01-07 18:36:30 -08001128::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001129 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001130 CHECK(!scheduler_.is_running())
1131 << ": Can't create an event loop while running";
1132
Austin Schuh39788ff2019-12-01 18:22:57 -08001133 pid_t tid = tid_;
1134 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001135 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh057d29f2021-08-21 23:05:15 -07001136 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
1137 node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001138 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001139 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001140 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001141}
1142
Austin Schuhc0b0f722020-12-12 18:36:06 -08001143void NodeEventLoopFactory::Disconnect(const Node *other) {
1144 factory_->bridge_->Disconnect(node_, other);
1145}
Austin Schuh057d29f2021-08-21 23:05:15 -07001146
Austin Schuhc0b0f722020-12-12 18:36:06 -08001147void NodeEventLoopFactory::Connect(const Node *other) {
1148 factory_->bridge_->Connect(node_, other);
1149}
1150
Alex Perrycb7da4b2019-08-28 19:35:56 -07001151void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001152 scheduler_scheduler_.RunOnStartup();
1153 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1154 if (node) {
1155 for (SimulatedEventLoop *loop : node->event_loops_) {
1156 loop->SetIsRunning(true);
1157 }
1158 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001159 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001160 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001161 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1162 if (node) {
1163 for (SimulatedEventLoop *loop : node->event_loops_) {
1164 loop->SetIsRunning(false);
1165 }
1166 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001167 }
1168}
1169
1170void SimulatedEventLoopFactory::Run() {
Austin Schuh057d29f2021-08-21 23:05:15 -07001171 scheduler_scheduler_.RunOnStartup();
1172 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1173 if (node) {
1174 for (SimulatedEventLoop *loop : node->event_loops_) {
1175 loop->SetIsRunning(true);
1176 }
1177 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001178 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001179 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001180 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1181 if (node) {
1182 for (SimulatedEventLoop *loop : node->event_loops_) {
1183 loop->SetIsRunning(false);
1184 }
1185 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001186 }
1187}
1188
Austin Schuh87dd3832021-01-01 23:07:31 -08001189void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001190
Austin Schuh6f3babe2020-01-26 20:34:50 -08001191void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001192 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001193 bridge_->DisableForwarding(channel);
1194}
1195
Austin Schuh4c3b9702020-08-30 11:34:55 -07001196void SimulatedEventLoopFactory::DisableStatistics() {
1197 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1198 bridge_->DisableStatistics();
1199}
1200
Austin Schuh2928ebe2021-02-07 22:10:27 -08001201void SimulatedEventLoopFactory::SkipTimingReport() {
1202 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
1203 bridge_->SkipTimingReport();
1204}
1205
Alex Perrycb7da4b2019-08-28 19:35:56 -07001206} // namespace aos