blob: 944a22b096e5e23b033331db88e76dd4ccc9d2e6 [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>
milind1f1dca32021-07-03 13:50:07 -07005#include <optional>
6#include <queue>
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08007#include <string_view>
Brian Silverman661eb8d2020-08-12 19:41:01 -07008#include <vector>
Alex Perrycb7da4b2019-08-28 19:35:56 -07009
10#include "absl/container/btree_map.h"
Brian Silverman661eb8d2020-08-12 19:41:01 -070011#include "aos/events/aos_logging.h"
Austin Schuh898f4972020-01-11 17:21:25 -080012#include "aos/events/simulated_network_bridge.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080013#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/json_to_flatbuffer.h"
Austin Schuhcc6070c2020-10-10 20:25:56 -070015#include "aos/realtime.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "aos/util/phased_loop.h"
17
Austin Schuh9b1d6282022-06-10 17:03:21 -070018// TODO(austin): If someone runs a SimulatedEventLoop on a RT thread with
19// die_on_malloc set, it won't die. Really, we need to go RT, or fall back to
20// the base thread's original RT state to be actually accurate.
21
Alex Perrycb7da4b2019-08-28 19:35:56 -070022namespace aos {
23
Brian Silverman661eb8d2020-08-12 19:41:01 -070024class SimulatedEventLoop;
25class SimulatedFetcher;
26class SimulatedChannel;
27
James Kuszmaul890c2492022-04-06 14:59:31 -070028using CheckSentTooFast = NodeEventLoopFactory::CheckSentTooFast;
29using ExclusiveSenders = NodeEventLoopFactory::ExclusiveSenders;
30using EventLoopOptions = NodeEventLoopFactory::EventLoopOptions;
31
Brian Silverman661eb8d2020-08-12 19:41:01 -070032namespace {
33
Austin Schuh057d29f2021-08-21 23:05:15 -070034std::string NodeName(const Node *node) {
35 if (node == nullptr) {
36 return "";
37 }
38
39 return absl::StrCat(node->name()->string_view(), " ");
40}
41
Austin Schuhcc6070c2020-10-10 20:25:56 -070042class ScopedMarkRealtimeRestorer {
43 public:
44 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
45 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
46
47 private:
48 const bool rt_;
49 const bool prior_;
50};
51
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070052// Holds storage for a span object and the data referenced by that span for
53// compatibility with RawSender::SharedSpan users. If constructed with
54// MakeSharedSpan, span points to only the aligned segment of the entire data.
55struct AlignedOwningSpan {
56 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
57 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
58 absl::Span<const uint8_t> span;
59 char data[];
60};
61
62// Constructs a span which owns its data through a shared_ptr. The owning span
63// points to a const view of the data; also returns a temporary mutable span
64// which is only valid while the const shared span is kept alive.
65std::pair<RawSender::SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(
66 size_t size) {
67 AlignedOwningSpan *const span = reinterpret_cast<AlignedOwningSpan *>(
68 malloc(sizeof(AlignedOwningSpan) + size + kChannelDataAlignment - 1));
69
James Kuszmaul9776b392023-01-14 14:08:08 -080070 absl::Span<uint8_t> mutable_span(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070071 reinterpret_cast<uint8_t *>(RoundChannelData(&span->data[0], size)),
72 size);
James Kuszmaul9776b392023-01-14 14:08:08 -080073 // Use the placement new operator to construct an actual absl::Span in place.
74 new (&span->span) absl::Span(mutable_span);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070075
76 return std::make_pair(
77 RawSender::SharedSpan(
78 std::shared_ptr<AlignedOwningSpan>(span,
79 [](AlignedOwningSpan *s) {
80 s->~AlignedOwningSpan();
81 free(s);
82 }),
83 &span->span),
84 mutable_span);
85}
86
Alex Perrycb7da4b2019-08-28 19:35:56 -070087// Container for both a message, and the context for it for simulation. This
88// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070089struct SimulatedMessage final {
90 SimulatedMessage(const SimulatedMessage &) = delete;
91 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070092 ~SimulatedMessage();
Brian Silverman661eb8d2020-08-12 19:41:01 -070093
94 // Creates a SimulatedMessage with size bytes of storage.
95 // This is a shared_ptr so we don't have to implement refcounting or copying.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070096 static std::shared_ptr<SimulatedMessage> Make(
97 SimulatedChannel *channel, const RawSender::SharedSpan data);
Brian Silverman661eb8d2020-08-12 19:41:01 -070098
Alex Perrycb7da4b2019-08-28 19:35:56 -070099 // Context for the data.
100 Context context;
101
Brian Silverman661eb8d2020-08-12 19:41:01 -0700102 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700103
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700104 // Owning span to this message's data. Depending on the sender may either
105 // represent the data of just the flatbuffer, or max channel size.
106 RawSender::SharedSpan data;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700107
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700108 // Mutable view of above data. If empty, this message is not mutable.
109 absl::Span<uint8_t> mutable_data;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700110
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700111 // Determines whether this message is mutable. Used for Send where the user
112 // fills out a message stored internally then gives us the size of data used.
113 bool is_mutable() const { return data->size() == mutable_data.size(); }
114
115 // Note: this should be private but make_shared requires it to be public. Use
116 // Make() above to construct.
Brian Silverman661eb8d2020-08-12 19:41:01 -0700117 SimulatedMessage(SimulatedChannel *channel_in);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700118};
119
Brian Silverman661eb8d2020-08-12 19:41:01 -0700120} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -0800121
Brian Silverman661eb8d2020-08-12 19:41:01 -0700122// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
123// for some reason...
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800124class SimulatedWatcher : public WatcherState, public EventScheduler::Event {
Austin Schuh39788ff2019-12-01 18:22:57 -0800125 public:
Austin Schuh7d87b672019-12-01 20:23:49 -0800126 SimulatedWatcher(
127 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
128 const Channel *channel,
129 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -0800130
Austin Schuh7d87b672019-12-01 20:23:49 -0800131 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -0800132
Austin Schuh8fb315a2020-11-19 22:33:58 -0800133 bool has_run() const;
134
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800135 void Handle() noexcept override;
136
Austin Schuh39788ff2019-12-01 18:22:57 -0800137 void Startup(EventLoop * /*event_loop*/) override {}
138
Austin Schuh7d87b672019-12-01 20:23:49 -0800139 void Schedule(std::shared_ptr<SimulatedMessage> message);
140
Austin Schuhf4b09c72021-12-08 12:04:37 -0800141 void HandleEvent() noexcept;
Austin Schuh39788ff2019-12-01 18:22:57 -0800142
143 void SetSimulatedChannel(SimulatedChannel *channel) {
144 simulated_channel_ = channel;
145 }
146
147 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800148 void DoSchedule(monotonic_clock::time_point event_time);
149
150 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
151
Brian Silverman4f4e0612020-08-12 19:54:41 -0700152 SimulatedEventLoop *const simulated_event_loop_;
153 const Channel *const channel_;
154 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800155 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800156 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800157 SimulatedChannel *simulated_channel_ = nullptr;
158};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159
Brian Silvermane1fe2512022-08-14 23:18:50 -0700160class SimulatedFactoryExitHandle : public ExitHandle {
161 public:
162 SimulatedFactoryExitHandle(SimulatedEventLoopFactory *factory)
163 : factory_(factory) {
164 ++factory_->exit_handle_count_;
165 }
166 ~SimulatedFactoryExitHandle() override {
167 CHECK_GT(factory_->exit_handle_count_, 0);
168 --factory_->exit_handle_count_;
169 }
170
171 void Exit() override { factory_->Exit(); }
172
173 private:
174 SimulatedEventLoopFactory *const factory_;
175};
176
Alex Perrycb7da4b2019-08-28 19:35:56 -0700177class SimulatedChannel {
178 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800179 explicit SimulatedChannel(const Channel *channel,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700180 std::chrono::nanoseconds channel_storage_duration,
181 const EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -0800182 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700183 channel_storage_duration_(channel_storage_duration),
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700184 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())),
185 scheduler_(scheduler) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700186 available_buffer_indices_.resize(number_buffers());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700187 for (int i = 0; i < number_buffers(); ++i) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700188 available_buffer_indices_[i] = i;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700189 }
190 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700191
Brian Silverman661eb8d2020-08-12 19:41:01 -0700192 ~SimulatedChannel() {
193 latest_message_.reset();
194 CHECK_EQ(static_cast<size_t>(number_buffers()),
195 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800196 CHECK_EQ(0u, fetchers_.size())
197 << configuration::StrippedChannelToString(channel());
198 CHECK_EQ(0u, watchers_.size())
199 << configuration::StrippedChannelToString(channel());
200 CHECK_EQ(0, sender_count_)
201 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700202 }
203
204 // The number of messages we pretend to have in the queue.
205 int queue_size() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700206 return configuration::QueueSize(channel()->frequency(),
207 channel_storage_duration_);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700208 }
209
milind1f1dca32021-07-03 13:50:07 -0700210 std::chrono::nanoseconds channel_storage_duration() const {
211 return channel_storage_duration_;
212 }
213
Brian Silverman661eb8d2020-08-12 19:41:01 -0700214 // The number of extra buffers (beyond the queue) we pretend to have.
215 int number_scratch_buffers() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700216 return configuration::QueueScratchBufferSize(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700217 }
218
219 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
220
221 int GetBufferIndex() {
222 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
223 const int result = available_buffer_indices_.back();
224 available_buffer_indices_.pop_back();
225 return result;
226 }
227
228 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700229 // This extra checking has a large performance hit with sanitizers that
230 // track memory accesses, so just skip it.
231#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700232 DCHECK(std::find(available_buffer_indices_.begin(),
233 available_buffer_indices_.end(),
234 i) == available_buffer_indices_.end())
235 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800236#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700237 available_buffer_indices_.push_back(i);
238 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700239
240 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800241 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700242
243 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800244 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700245
246 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800247 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800248
Austin Schuh7d87b672019-12-01 20:23:49 -0800249 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800250 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
251 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700252
Austin Schuhad154822019-12-27 15:45:13 -0800253 // Sends the message to all the connected receivers and fetchers. Returns the
milind1f1dca32021-07-03 13:50:07 -0700254 // sent queue index, or std::nullopt if messages were sent too fast.
James Kuszmaul890c2492022-04-06 14:59:31 -0700255 std::optional<uint32_t> Send(std::shared_ptr<SimulatedMessage> message,
256 CheckSentTooFast check_sent_too_fast);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700257
258 // Unregisters a fetcher.
259 void UnregisterFetcher(SimulatedFetcher *fetcher);
260
261 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
262
Austin Schuh39788ff2019-12-01 18:22:57 -0800263 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700264
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800265 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800266 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700267 }
268
Austin Schuh39788ff2019-12-01 18:22:57 -0800269 const Channel *channel() const { return channel_; }
270
Austin Schuhe516ab02020-05-06 21:37:04 -0700271 void CountSenderCreated() {
272 if (sender_count_ >= channel()->num_senders()) {
273 LOG(FATAL) << "Failed to create sender on "
274 << configuration::CleanedChannelToString(channel())
275 << ", too many senders.";
276 }
Austin Schuhfb37c612022-08-11 15:24:51 -0700277 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700278 ++sender_count_;
279 }
Brian Silverman77162972020-08-12 19:52:40 -0700280
Austin Schuhe516ab02020-05-06 21:37:04 -0700281 void CountSenderDestroyed() {
282 --sender_count_;
283 CHECK_GE(sender_count_, 0);
James Kuszmaul890c2492022-04-06 14:59:31 -0700284 if (sender_count_ == 0) {
285 allow_new_senders_ = true;
286 }
Austin Schuhe516ab02020-05-06 21:37:04 -0700287 }
288
Alex Perrycb7da4b2019-08-28 19:35:56 -0700289 private:
Brian Silverman77162972020-08-12 19:52:40 -0700290 void CheckBufferCount() {
291 int reader_count = 0;
292 if (channel()->read_method() == ReadMethod::PIN) {
293 reader_count = watchers_.size() + fetchers_.size();
294 }
295 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
296 }
297
298 void CheckReaderCount() {
299 if (channel()->read_method() != ReadMethod::PIN) {
300 return;
301 }
302 CheckBufferCount();
303 const int reader_count = watchers_.size() + fetchers_.size();
304 if (reader_count >= channel()->num_readers()) {
305 LOG(FATAL) << "Failed to create reader on "
306 << configuration::CleanedChannelToString(channel())
307 << ", too many readers.";
308 }
309 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700310
311 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700312 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700313
314 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800315 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700316
317 // List of all fetchers.
318 ::std::vector<SimulatedFetcher *> fetchers_;
319 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320
321 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700322
323 int sender_count_ = 0;
James Kuszmaul890c2492022-04-06 14:59:31 -0700324 // Used to track when an exclusive sender has been created (e.g., for log
325 // replay) and we want to prevent new senders from being accidentally created.
326 bool allow_new_senders_ = true;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700327
328 std::vector<uint16_t> available_buffer_indices_;
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700329
330 const EventScheduler *scheduler_;
331
332 // Queue of all the message send times in the last channel_storage_duration_
333 std::queue<monotonic_clock::time_point> last_times_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334};
335
336namespace {
337
Brian Silverman661eb8d2020-08-12 19:41:01 -0700338std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700339 SimulatedChannel *channel, RawSender::SharedSpan data) {
Austin Schuh62288252020-11-18 23:26:04 -0800340 // The allocations in here are due to infrastructure and don't count in the no
341 // mallocs in RT code.
342 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700344 auto message = std::make_shared<SimulatedMessage>(channel);
345 message->context.size = data->size();
346 message->context.data = data->data();
347 message->data = std::move(data);
348
349 return message;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700350}
351
352SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
353 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700354 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700355}
356
357SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700358 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700359}
360
361class SimulatedSender : public RawSender {
362 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800363 SimulatedSender(SimulatedChannel *simulated_channel,
364 SimulatedEventLoop *event_loop);
365 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366
367 void *data() override {
368 if (!message_) {
Austin Schuh9b1d6282022-06-10 17:03:21 -0700369 // This API is safe to use in a RT context on a RT system. So annotate it
370 // accordingly.
371 ScopedNotRealtime nrt;
372
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700373 auto [span, mutable_span] =
374 MakeSharedSpan(simulated_channel_->max_size());
375 message_ = SimulatedMessage::Make(simulated_channel_, span);
376 message_->mutable_data = mutable_span;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700377 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700378 CHECK(message_->is_mutable());
379 return message_->mutable_data.data();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700380 }
381
382 size_t size() override { return simulated_channel_->max_size(); }
383
milind1f1dca32021-07-03 13:50:07 -0700384 Error DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
385 realtime_clock::time_point realtime_remote_time,
386 uint32_t remote_queue_index,
387 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700388
milind1f1dca32021-07-03 13:50:07 -0700389 Error DoSend(const void *msg, size_t size,
390 monotonic_clock::time_point monotonic_remote_time,
391 realtime_clock::time_point realtime_remote_time,
392 uint32_t remote_queue_index,
393 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394
milind1f1dca32021-07-03 13:50:07 -0700395 Error DoSend(const SharedSpan data,
396 aos::monotonic_clock::time_point monotonic_remote_time,
397 aos::realtime_clock::time_point realtime_remote_time,
398 uint32_t remote_queue_index,
399 const UUID &source_boot_uuid) override;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700400
Brian Silverman4f4e0612020-08-12 19:54:41 -0700401 int buffer_index() override {
402 // First, ensure message_ is allocated.
403 data();
404 return message_->context.buffer_index;
405 }
406
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407 private:
408 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700409 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700410
411 std::shared_ptr<SimulatedMessage> message_;
412};
413} // namespace
414
415class SimulatedFetcher : public RawFetcher {
416 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800417 explicit SimulatedFetcher(EventLoop *event_loop,
418 SimulatedChannel *simulated_channel)
419 : RawFetcher(event_loop, simulated_channel->channel()),
420 simulated_channel_(simulated_channel) {}
421 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700422
Austin Schuh39788ff2019-12-01 18:22:57 -0800423 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800424 // The allocations in here are due to infrastructure and don't count in the
425 // no mallocs in RT code.
426 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800427 if (msgs_.size() == 0) {
428 return std::make_pair(false, monotonic_clock::min_time);
429 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700430
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700431 CHECK(!fell_behind_) << ": Got behind on "
432 << configuration::StrippedChannelToString(
433 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700434
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435 SetMsg(msgs_.front());
436 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800437 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438 }
439
Austin Schuh39788ff2019-12-01 18:22:57 -0800440 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800441 // The allocations in here are due to infrastructure and don't count in the
442 // no mallocs in RT code.
443 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800445 // TODO(austin): Can we just do this logic unconditionally? It is a lot
446 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800447 if (!msg_ && simulated_channel_->latest_message()) {
448 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800449 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800451 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700452 }
453 }
454
455 // We've had a message enqueued, so we don't need to go looking for the
456 // latest message from before we started.
457 SetMsg(msgs_.back());
458 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700459 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800460 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700461 }
462
463 private:
464 friend class SimulatedChannel;
465
466 // Updates the state inside RawFetcher to point to the data in msg_.
467 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800468 msg_ = std::move(msg);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700470 if (channel()->read_method() != ReadMethod::PIN) {
471 context_.buffer_index = -1;
472 }
Austin Schuhad154822019-12-27 15:45:13 -0800473 if (context_.remote_queue_index == 0xffffffffu) {
474 context_.remote_queue_index = context_.queue_index;
475 }
Austin Schuh58646e22021-08-23 23:51:46 -0700476 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800477 context_.monotonic_remote_time = context_.monotonic_event_time;
478 }
Austin Schuh58646e22021-08-23 23:51:46 -0700479 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800480 context_.realtime_remote_time = context_.realtime_event_time;
481 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700482 }
483
484 // Internal method for Simulation to add a message to the buffer.
485 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800486 msgs_.emplace_back(std::move(buffer));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700487 if (fell_behind_ ||
488 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
489 fell_behind_ = true;
490 // Might as well empty out all the intermediate messages now.
491 while (msgs_.size() > 1) {
492 msgs_.pop_front();
493 }
494 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700495 }
496
Austin Schuhac0771c2020-01-07 18:36:30 -0800497 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700498 std::shared_ptr<SimulatedMessage> msg_;
499
500 // Messages queued up but not in use.
501 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700502
503 // Whether we're currently "behind", which means a FetchNext call will fail.
504 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700505};
506
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800507class SimulatedTimerHandler : public TimerHandler,
508 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509 public:
510 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800511 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800512 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800513 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514
515 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800516 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700517
Austin Schuhf4b09c72021-12-08 12:04:37 -0800518 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700519
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800520 void Handle() noexcept override;
521
Austin Schuh7d87b672019-12-01 20:23:49 -0800522 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700523
Alex Perrycb7da4b2019-08-28 19:35:56 -0700524 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800525 SimulatedEventLoop *simulated_event_loop_;
526 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700527 EventScheduler *scheduler_;
528 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800529
Alex Perrycb7da4b2019-08-28 19:35:56 -0700530 monotonic_clock::time_point base_;
531 monotonic_clock::duration repeat_offset_;
532};
533
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800534class SimulatedPhasedLoopHandler : public PhasedLoopHandler,
535 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700536 public:
537 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800538 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700539 ::std::function<void(int)> fn,
540 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800541 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800542 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700543
Austin Schuhf4b09c72021-12-08 12:04:37 -0800544 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545
Austin Schuh7d87b672019-12-01 20:23:49 -0800546 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800548 void Handle() noexcept override;
549
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800551 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800552 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553
Austin Schuh39788ff2019-12-01 18:22:57 -0800554 EventScheduler *scheduler_;
555 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556};
557
558class SimulatedEventLoop : public EventLoop {
559 public:
560 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700561 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
563 *channels,
564 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700565 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
James Kuszmaul890c2492022-04-06 14:59:31 -0700566 pid_t tid, EventLoopOptions options)
Austin Schuh83c7f702021-01-19 22:36:29 -0800567 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700568 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800569 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700571 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800572 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700573 tid_(tid),
James Kuszmaul890c2492022-04-06 14:59:31 -0700574 startup_tracker_(std::make_shared<StartupTracker>()),
575 options_(options) {
Austin Schuh0debde12022-08-17 16:25:17 -0700576 ClearContext();
Austin Schuh58646e22021-08-23 23:51:46 -0700577 startup_tracker_->loop = this;
578 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
579 if (startup_tracker->loop) {
580 startup_tracker->loop->Setup();
581 startup_tracker->has_setup = true;
582 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700583 });
584
585 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700586 }
Austin Schuh58646e22021-08-23 23:51:46 -0700587
Alex Perrycb7da4b2019-08-28 19:35:56 -0700588 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800589 // Trigger any remaining senders or fetchers to be cleared before destroying
590 // the event loop so the book keeping matches.
591 timing_report_sender_.reset();
592
593 // Force everything with a registered fd with epoll to be destroyed now.
594 timers_.clear();
595 phased_loops_.clear();
596 watchers_.clear();
597
Austin Schuh58646e22021-08-23 23:51:46 -0700598 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700599 if (*it == this) {
600 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700601 break;
602 }
603 }
Austin Schuh58646e22021-08-23 23:51:46 -0700604 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
605 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
606 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700607 }
608
Austin Schuh057d29f2021-08-21 23:05:15 -0700609 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700610 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
611 << monotonic_now() << " " << name_ << " set_is_running(" << running
612 << ")";
613 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700614
615 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700616 if (running) {
617 has_run_ = true;
618 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700619 }
620
Austin Schuh8fb315a2020-11-19 22:33:58 -0800621 bool has_run() const { return has_run_; }
622
Austin Schuh7d87b672019-12-01 20:23:49 -0800623 std::chrono::nanoseconds send_delay() const { return send_delay_; }
624 void set_send_delay(std::chrono::nanoseconds send_delay) {
625 send_delay_ = send_delay;
626 }
627
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800628 monotonic_clock::time_point monotonic_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800629 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630 }
631
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800632 realtime_clock::time_point realtime_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800633 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634 }
635
Austin Schuh58646e22021-08-23 23:51:46 -0700636 distributed_clock::time_point distributed_now() {
637 return scheduler_->distributed_now();
638 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700639
Austin Schuh58646e22021-08-23 23:51:46 -0700640 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
641
642 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700643
644 void MakeRawWatcher(
645 const Channel *channel,
646 ::std::function<void(const Context &context, const void *message)>
647 watcher) override;
648
649 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800650 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800651 return NewTimer(::std::unique_ptr<TimerHandler>(
652 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700653 }
654
655 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
656 const monotonic_clock::duration interval,
657 const monotonic_clock::duration offset =
658 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800659 return NewPhasedLoop(
660 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
661 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700662 }
663
664 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800665 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700666 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800667 logging::ScopedLogRestorer prev_logger;
668 if (log_impl_) {
669 prev_logger.Swap(log_impl_);
670 }
Austin Schuh65493d62022-08-17 15:10:37 -0700671 ScopedMarkRealtimeRestorer rt(runtime_realtime_priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700672 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700673 on_run();
Austin Schuh0debde12022-08-17 16:25:17 -0700674 ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700675 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700676 }
677
Austin Schuh217a9782019-12-21 23:02:50 -0800678 const Node *node() const override { return node_; }
679
James Kuszmaul3ae42262019-11-08 12:33:41 -0800680 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700681 name_ = std::string(name);
682 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800683 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700684
685 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
686
Austin Schuh39788ff2019-12-01 18:22:57 -0800687 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700688 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800689 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700690 }
691
Austin Schuh65493d62022-08-17 15:10:37 -0700692 int runtime_realtime_priority() const override { return priority_; }
693 const cpu_set_t &runtime_affinity() const override { return affinity_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800694
Austin Schuh65493d62022-08-17 15:10:37 -0700695 void SetRuntimeAffinity(const cpu_set_t &affinity) override {
Brian Silverman6a54ff32020-04-28 16:41:39 -0700696 CHECK(!is_running()) << ": Cannot set affinity while running.";
Austin Schuh65493d62022-08-17 15:10:37 -0700697 affinity_ = affinity;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700698 }
699
Tyler Chatow67ddb032020-01-12 14:30:04 -0800700 void Setup() {
701 MaybeScheduleTimingReports();
702 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800703 log_sender_.Initialize(&name_,
704 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700705 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800706 }
707 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800708
Brian Silverman4f4e0612020-08-12 19:54:41 -0700709 int NumberBuffers(const Channel *channel) override;
710
Austin Schuh83c7f702021-01-19 22:36:29 -0800711 const UUID &boot_uuid() const override {
712 return node_event_loop_factory_->boot_uuid();
713 }
714
James Kuszmaul890c2492022-04-06 14:59:31 -0700715 const EventLoopOptions &options() const { return options_; }
716
Alex Perrycb7da4b2019-08-28 19:35:56 -0700717 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800718 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800719 friend class SimulatedPhasedLoopHandler;
720 friend class SimulatedWatcher;
721
Austin Schuh58646e22021-08-23 23:51:46 -0700722 // We have a condition where we register a startup handler, but then get shut
723 // down before it runs. This results in a segfault if we are lucky, and
724 // corruption otherwise. To handle that, allocate a small object which points
725 // back to us and can be freed when the function is freed. That object can
726 // then be updated when we get destroyed so setup is not called.
727 struct StartupTracker {
728 SimulatedEventLoop *loop = nullptr;
729 bool has_setup = false;
730 };
731
Austin Schuh7d87b672019-12-01 20:23:49 -0800732 void HandleEvent() {
733 while (true) {
734 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
735 break;
736 }
737
738 EventLoopEvent *event = PopEvent();
739 event->HandleEvent();
740 }
741 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800742
Austin Schuh39788ff2019-12-01 18:22:57 -0800743 pid_t GetTid() override { return tid_; }
744
Alex Perrycb7da4b2019-08-28 19:35:56 -0700745 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800746 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700747 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700748 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700749
750 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800751
752 int priority_ = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700753 cpu_set_t affinity_ = DefaultAffinity();
Austin Schuh39788ff2019-12-01 18:22:57 -0800754
Austin Schuh7d87b672019-12-01 20:23:49 -0800755 std::chrono::nanoseconds send_delay_;
756
Austin Schuh217a9782019-12-21 23:02:50 -0800757 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800758 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800759
760 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700761 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800762
763 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700764
765 std::shared_ptr<StartupTracker> startup_tracker_;
James Kuszmaul890c2492022-04-06 14:59:31 -0700766
767 EventLoopOptions options_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700768};
769
Austin Schuh7d87b672019-12-01 20:23:49 -0800770void SimulatedEventLoopFactory::set_send_delay(
771 std::chrono::nanoseconds send_delay) {
772 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700773 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700774 if (node) {
775 for (SimulatedEventLoop *loop : node->event_loops_) {
776 loop->set_send_delay(send_delay_);
777 }
778 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800779 }
780}
781
James Kuszmaulb67409b2022-06-20 16:25:03 -0700782void SimulatedEventLoopFactory::SetRealtimeReplayRate(double replay_rate) {
783 scheduler_scheduler_.SetReplayRate(replay_rate);
784}
785
Alex Perrycb7da4b2019-08-28 19:35:56 -0700786void SimulatedEventLoop::MakeRawWatcher(
787 const Channel *channel,
788 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800789 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800790
Austin Schuh057d29f2021-08-21 23:05:15 -0700791 std::unique_ptr<SimulatedWatcher> shm_watcher =
792 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
793 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800794
795 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700796
Austin Schuh39788ff2019-12-01 18:22:57 -0800797 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700798 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
799 << " " << name() << " MakeRawWatcher(\""
800 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800801
802 // Order of operations gets kinda wonky if we let people make watchers after
803 // running once. If someone has a valid use case, we can reconsider.
804 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700805}
806
807std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
808 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800809 TakeSender(channel);
810
Austin Schuh58646e22021-08-23 23:51:46 -0700811 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
812 << " " << name() << " MakeRawSender(\""
813 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700814 return GetSimulatedChannel(channel)->MakeRawSender(this);
815}
816
817std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
818 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800819 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800820
Austin Schuhca4828c2019-12-28 14:21:35 -0800821 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
822 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
823 << "\", \"type\": \"" << channel->type()->string_view()
824 << "\" } is not able to be fetched on this node. Check your "
825 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800826 }
827
Austin Schuh58646e22021-08-23 23:51:46 -0700828 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
829 << " " << name() << " MakeRawFetcher(\""
830 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800831 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700832}
833
834SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
835 const Channel *channel) {
836 auto it = channels_->find(SimpleChannel(channel));
837 if (it == channels_->end()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700838 it = channels_
839 ->emplace(SimpleChannel(channel),
840 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
841 channel,
842 std::chrono::nanoseconds(
843 configuration()->channel_storage_duration()),
844 scheduler_)))
845 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700846 }
847 return it->second.get();
848}
849
Brian Silverman4f4e0612020-08-12 19:54:41 -0700850int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
851 return GetSimulatedChannel(channel)->number_buffers();
852}
853
Austin Schuh7d87b672019-12-01 20:23:49 -0800854SimulatedWatcher::SimulatedWatcher(
855 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800856 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800857 std::function<void(const Context &context, const void *message)> fn)
858 : WatcherState(simulated_event_loop, channel, std::move(fn)),
859 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700860 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800861 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700862 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700863 token_(scheduler_->InvalidToken()) {
864 VLOG(1) << simulated_event_loop_->distributed_now() << " "
865 << NodeName(simulated_event_loop_->node())
866 << simulated_event_loop_->monotonic_now() << " "
867 << simulated_event_loop_->name() << " Watching "
868 << configuration::StrippedChannelToString(channel_);
869}
Austin Schuh7d87b672019-12-01 20:23:49 -0800870
871SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700872 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700873 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700874 << simulated_event_loop_->monotonic_now() << " "
875 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700876 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800877 simulated_event_loop_->RemoveEvent(&event_);
878 if (token_ != scheduler_->InvalidToken()) {
879 scheduler_->Deschedule(token_);
880 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700881 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800882}
883
Austin Schuh8fb315a2020-11-19 22:33:58 -0800884bool SimulatedWatcher::has_run() const {
885 return simulated_event_loop_->has_run();
886}
887
Austin Schuh7d87b672019-12-01 20:23:49 -0800888void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800889 monotonic_clock::time_point event_time =
890 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800891
892 // Messages are queued in order. If we are the first, add ourselves.
893 // Otherwise, don't.
894 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800895 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800896 simulated_event_loop_->AddEvent(&event_);
897
898 DoSchedule(event_time);
899 }
900
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800901 msgs_.emplace_back(std::move(message));
Austin Schuh7d87b672019-12-01 20:23:49 -0800902}
903
Austin Schuhf4b09c72021-12-08 12:04:37 -0800904void SimulatedWatcher::HandleEvent() noexcept {
Austin Schuh7d87b672019-12-01 20:23:49 -0800905 const monotonic_clock::time_point monotonic_now =
906 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700907 VLOG(1) << simulated_event_loop_->distributed_now() << " "
908 << NodeName(simulated_event_loop_->node())
909 << simulated_event_loop_->monotonic_now() << " "
910 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700911 << configuration::StrippedChannelToString(channel_);
912 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
913
Tyler Chatow67ddb032020-01-12 14:30:04 -0800914 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700915 if (simulated_event_loop_->log_impl_) {
916 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800917 }
Austin Schuhad154822019-12-27 15:45:13 -0800918 Context context = msgs_.front()->context;
919
Brian Silverman4f4e0612020-08-12 19:54:41 -0700920 if (channel_->read_method() != ReadMethod::PIN) {
921 context.buffer_index = -1;
922 }
Austin Schuhad154822019-12-27 15:45:13 -0800923 if (context.remote_queue_index == 0xffffffffu) {
924 context.remote_queue_index = context.queue_index;
925 }
Austin Schuh58646e22021-08-23 23:51:46 -0700926 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800927 context.monotonic_remote_time = context.monotonic_event_time;
928 }
Austin Schuh58646e22021-08-23 23:51:46 -0700929 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800930 context.realtime_remote_time = context.realtime_event_time;
931 }
932
Austin Schuhcc6070c2020-10-10 20:25:56 -0700933 {
Austin Schuh65493d62022-08-17 15:10:37 -0700934 ScopedMarkRealtimeRestorer rt(
935 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700936 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh0debde12022-08-17 16:25:17 -0700937 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700938 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800939
940 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700941 if (token_ != scheduler_->InvalidToken()) {
942 scheduler_->Deschedule(token_);
943 token_ = scheduler_->InvalidToken();
944 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800945 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800946 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800947 simulated_event_loop_->AddEvent(&event_);
948
949 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800950 }
951}
952
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800953void SimulatedWatcher::Handle() noexcept {
954 DCHECK(token_ != scheduler_->InvalidToken());
955 token_ = scheduler_->InvalidToken();
956 simulated_event_loop_->HandleEvent();
957}
958
Austin Schuh7d87b672019-12-01 20:23:49 -0800959void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700960 CHECK(token_ == scheduler_->InvalidToken())
961 << ": May not schedule multiple times";
962 token_ = scheduler_->Schedule(
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800963 event_time + simulated_event_loop_->send_delay(), this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800964}
965
966void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700967 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800968 watcher->SetSimulatedChannel(this);
969 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700970}
971
972::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800973 SimulatedEventLoop *event_loop) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700974 CHECK(allow_new_senders_)
975 << ": Attempted to create a new sender on exclusive channel "
976 << configuration::StrippedChannelToString(channel_);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700977 std::optional<ExclusiveSenders> per_channel_option;
978 for (const std::pair<const aos::Channel *, ExclusiveSenders> &per_channel :
979 event_loop->options().per_channel_exclusivity) {
980 if (per_channel.first->name()->string_view() ==
981 channel_->name()->string_view() &&
982 per_channel.first->type()->string_view() ==
983 channel_->type()->string_view()) {
984 CHECK(!per_channel_option.has_value())
985 << ": Channel " << configuration::StrippedChannelToString(channel_)
986 << " listed twice in per-channel list.";
987 per_channel_option = per_channel.second;
988 }
989 }
990 if (!per_channel_option.has_value()) {
991 // This could just as easily be implemented by setting
992 // per_channel_option to the global setting when we initialize it, but
993 // then we'd lose track of whether a given channel appears twice in
994 // the list.
995 per_channel_option = event_loop->options().exclusive_senders;
996 }
997 if (per_channel_option.value() == ExclusiveSenders::kYes) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700998 CHECK_EQ(0, sender_count_)
999 << ": Attempted to add an exclusive sender on a channel with existing "
1000 "senders: "
1001 << configuration::StrippedChannelToString(channel_);
1002 allow_new_senders_ = false;
1003 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001004 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
1005}
1006
Austin Schuh39788ff2019-12-01 18:22:57 -08001007::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
1008 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -07001009 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -08001010 ::std::unique_ptr<SimulatedFetcher> fetcher(
1011 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -07001012 fetchers_.push_back(fetcher.get());
James Kuszmaul9776b392023-01-14 14:08:08 -08001013 return fetcher;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001014}
1015
milind1f1dca32021-07-03 13:50:07 -07001016std::optional<uint32_t> SimulatedChannel::Send(
Austin Schuh60e77942022-05-16 17:48:24 -07001017 std::shared_ptr<SimulatedMessage> message,
1018 CheckSentTooFast check_sent_too_fast) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001019 const auto now = scheduler_->monotonic_now();
1020 // Remove times that are greater than or equal to a channel_storage_duration_
1021 // ago
1022 while (!last_times_.empty() &&
1023 (now - last_times_.front() >= channel_storage_duration_)) {
1024 last_times_.pop();
1025 }
1026
1027 // Check that we are not sending messages too fast
James Kuszmaul890c2492022-04-06 14:59:31 -07001028 if (check_sent_too_fast == CheckSentTooFast::kYes &&
1029 static_cast<int>(last_times_.size()) >= queue_size()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001030 return std::nullopt;
1031 }
1032
1033 const std::optional<uint32_t> queue_index = {next_queue_index_.index()};
1034 last_times_.push(now);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001035
milind1f1dca32021-07-03 13:50:07 -07001036 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001037 // Points to the actual data depending on the size set in context. Data may
1038 // allocate more than the actual size of the message, so offset from the back
1039 // of that to get the actual start of the data.
1040 message->context.data =
1041 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -07001042
1043 DCHECK(channel()->has_schema())
1044 << ": Missing schema for channel "
1045 << configuration::StrippedChannelToString(channel());
1046 DCHECK(flatbuffers::Verify(
1047 *channel()->schema(), *channel()->schema()->root_table(),
1048 static_cast<const uint8_t *>(message->context.data),
1049 message->context.size))
1050 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
1051 << channel()->type()->c_str();
1052
Alex Perrycb7da4b2019-08-28 19:35:56 -07001053 next_queue_index_ = next_queue_index_.Increment();
1054
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001055 latest_message_ = std::move(message);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001056 for (SimulatedWatcher *watcher : watchers_) {
1057 if (watcher->has_run()) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001058 watcher->Schedule(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001059 }
1060 }
1061 for (auto &fetcher : fetchers_) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001062 fetcher->Enqueue(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001063 }
Austin Schuhad154822019-12-27 15:45:13 -08001064 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001065}
1066
1067void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
1068 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
1069}
1070
Austin Schuh8fb315a2020-11-19 22:33:58 -08001071SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
1072 SimulatedEventLoop *event_loop)
1073 : RawSender(event_loop, simulated_channel->channel()),
1074 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -07001075 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -08001076 simulated_channel_->CountSenderCreated();
1077}
1078
1079SimulatedSender::~SimulatedSender() {
1080 simulated_channel_->CountSenderDestroyed();
1081}
1082
milind1f1dca32021-07-03 13:50:07 -07001083RawSender::Error SimulatedSender::DoSend(
1084 size_t length, monotonic_clock::time_point monotonic_remote_time,
1085 realtime_clock::time_point realtime_remote_time,
1086 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001087 // The allocations in here are due to infrastructure and don't count in the
1088 // no mallocs in RT code.
1089 ScopedNotRealtime nrt;
1090
Austin Schuh58646e22021-08-23 23:51:46 -07001091 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1092 << NodeName(simulated_event_loop_->node())
1093 << simulated_event_loop_->monotonic_now() << " "
1094 << simulated_event_loop_->name() << " Send "
1095 << configuration::StrippedChannelToString(channel());
1096
Austin Schuh8fb315a2020-11-19 22:33:58 -08001097 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -07001098 message_->context.monotonic_event_time =
1099 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001100 message_->context.monotonic_remote_time = monotonic_remote_time;
1101 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001102 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001103 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001104 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001105 CHECK_LE(length, message_->context.size);
1106 message_->context.size = length;
1107
Austin Schuh60e77942022-05-16 17:48:24 -07001108 const std::optional<uint32_t> optional_queue_index = simulated_channel_->Send(
1109 message_, simulated_event_loop_->options().check_sent_too_fast);
milind1f1dca32021-07-03 13:50:07 -07001110
1111 // Check that we are not sending messages too fast
1112 if (!optional_queue_index) {
1113 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1114 << NodeName(simulated_event_loop_->node())
1115 << simulated_event_loop_->monotonic_now() << " "
1116 << simulated_event_loop_->name()
1117 << "\nMessages were sent too fast:\n"
1118 << "For channel: "
1119 << configuration::CleanedChannelToString(
1120 simulated_channel_->channel())
1121 << '\n'
1122 << "Tried to send more than " << simulated_channel_->queue_size()
1123 << " (queue size) messages in the last "
1124 << std::chrono::duration<double>(
1125 simulated_channel_->channel_storage_duration())
1126 .count()
1127 << " seconds (channel storage duration)"
1128 << "\n\n";
1129 return Error::kMessagesSentTooFast;
1130 }
1131
1132 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001133 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1134 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001135
1136 // Drop the reference to the message so that we allocate a new message for
1137 // next time. Otherwise we will continue to reuse the same memory for all
1138 // messages and corrupt it.
1139 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001140 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001141}
1142
milind1f1dca32021-07-03 13:50:07 -07001143RawSender::Error SimulatedSender::DoSend(
1144 const void *msg, size_t size,
1145 monotonic_clock::time_point monotonic_remote_time,
1146 realtime_clock::time_point realtime_remote_time,
1147 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001148 CHECK_LE(size, this->size())
1149 << ": Attempting to send too big a message on "
1150 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001151
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001152 // Allocates an aligned buffer in which to copy unaligned msg.
1153 auto [span, mutable_span] = MakeSharedSpan(size);
1154 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001155
1156 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001157 // queue_index will be populated in simulated_channel_.
1158 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001159
1160 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001161 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001162}
1163
milind1f1dca32021-07-03 13:50:07 -07001164RawSender::Error SimulatedSender::DoSend(
1165 const RawSender::SharedSpan data,
1166 monotonic_clock::time_point monotonic_remote_time,
1167 realtime_clock::time_point realtime_remote_time,
1168 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001169 CHECK_LE(data->size(), this->size())
1170 << ": Attempting to send too big a message on "
1171 << configuration::CleanedChannelToString(simulated_channel_->channel());
1172
1173 // Constructs a message sharing the already allocated and aligned message
1174 // data.
1175 message_ = SimulatedMessage::Make(simulated_channel_, data);
1176
1177 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1178 remote_queue_index, source_boot_uuid);
1179}
1180
Austin Schuh39788ff2019-12-01 18:22:57 -08001181SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001182 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1183 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001184 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001185 simulated_event_loop_(simulated_event_loop),
1186 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001187 scheduler_(scheduler),
1188 token_(scheduler_->InvalidToken()) {}
1189
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001190void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
1191 monotonic_clock::duration repeat_offset) {
James Kuszmaul86e86c32022-07-21 17:39:47 -07001192 CHECK_GE(base, monotonic_clock::epoch());
Austin Schuh62288252020-11-18 23:26:04 -08001193 // The allocations in here are due to infrastructure and don't count in the no
1194 // mallocs in RT code.
1195 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001196 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001197 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001198 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001199 base_ = base;
1200 repeat_offset_ = repeat_offset;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001201 token_ = scheduler_->Schedule(std::max(base, monotonic_now), this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001202 event_.set_event_time(base_);
1203 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001204}
1205
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001206void SimulatedTimerHandler::Handle() noexcept {
1207 DCHECK(token_ != scheduler_->InvalidToken());
1208 token_ = scheduler_->InvalidToken();
1209 simulated_event_loop_->HandleEvent();
1210}
1211
Austin Schuhf4b09c72021-12-08 12:04:37 -08001212void SimulatedTimerHandler::HandleEvent() noexcept {
Austin Schuh58646e22021-08-23 23:51:46 -07001213 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001214 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001215 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1216 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1217 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001218 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001219 if (simulated_event_loop_->log_impl_) {
1220 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001221 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001222 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001223 {
1224 ScopedNotRealtime nrt;
1225 scheduler_->Deschedule(token_);
1226 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001227 token_ = scheduler_->InvalidToken();
1228 }
Austin Schuh58646e22021-08-23 23:51:46 -07001229 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001230 // Reschedule.
1231 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001232 token_ = scheduler_->Schedule(base_, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001233 event_.set_event_time(base_);
1234 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001235 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001236
Austin Schuhcc6070c2020-10-10 20:25:56 -07001237 {
Austin Schuh65493d62022-08-17 15:10:37 -07001238 ScopedMarkRealtimeRestorer rt(
1239 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -07001240 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuh0debde12022-08-17 16:25:17 -07001241 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001242 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001243}
1244
Austin Schuh7d87b672019-12-01 20:23:49 -08001245void SimulatedTimerHandler::Disable() {
1246 simulated_event_loop_->RemoveEvent(&event_);
1247 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001248 {
1249 ScopedNotRealtime nrt;
1250 scheduler_->Deschedule(token_);
1251 }
Austin Schuh7d87b672019-12-01 20:23:49 -08001252 token_ = scheduler_->InvalidToken();
1253 }
1254}
1255
Austin Schuh39788ff2019-12-01 18:22:57 -08001256SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001257 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1258 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001259 const monotonic_clock::duration offset)
1260 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1261 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001262 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001263 scheduler_(scheduler),
1264 token_(scheduler_->InvalidToken()) {}
1265
Austin Schuh7d87b672019-12-01 20:23:49 -08001266SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1267 if (token_ != scheduler_->InvalidToken()) {
1268 scheduler_->Deschedule(token_);
1269 token_ = scheduler_->InvalidToken();
1270 }
1271 simulated_event_loop_->RemoveEvent(&event_);
1272}
1273
Austin Schuhf4b09c72021-12-08 12:04:37 -08001274void SimulatedPhasedLoopHandler::HandleEvent() noexcept {
Austin Schuh39788ff2019-12-01 18:22:57 -08001275 monotonic_clock::time_point monotonic_now =
1276 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001277 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1278 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001279 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001280 if (simulated_event_loop_->log_impl_) {
1281 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001282 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001283
1284 {
Austin Schuh65493d62022-08-17 15:10:37 -07001285 ScopedMarkRealtimeRestorer rt(
1286 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -07001287 Call([monotonic_now]() { return monotonic_now; },
1288 [this](monotonic_clock::time_point sleep_time) {
1289 Schedule(sleep_time);
1290 });
Austin Schuh0debde12022-08-17 16:25:17 -07001291 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001292 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001293}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001294
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001295void SimulatedPhasedLoopHandler::Handle() noexcept {
1296 DCHECK(token_ != scheduler_->InvalidToken());
1297 token_ = scheduler_->InvalidToken();
1298 simulated_event_loop_->HandleEvent();
1299}
1300
Austin Schuh7d87b672019-12-01 20:23:49 -08001301void SimulatedPhasedLoopHandler::Schedule(
1302 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001303 // The allocations in here are due to infrastructure and don't count in the no
1304 // mallocs in RT code.
1305 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001306 if (token_ != scheduler_->InvalidToken()) {
1307 scheduler_->Deschedule(token_);
1308 token_ = scheduler_->InvalidToken();
1309 }
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001310 token_ = scheduler_->Schedule(sleep_time, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001311 event_.set_event_time(sleep_time);
1312 simulated_event_loop_->AddEvent(&event_);
1313}
1314
Alex Perrycb7da4b2019-08-28 19:35:56 -07001315SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1316 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001317 : configuration_(CHECK_NOTNULL(configuration)),
1318 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001319 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001320 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001321 node_factories_.emplace_back(
1322 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001323 }
Austin Schuh898f4972020-01-11 17:21:25 -08001324
1325 if (configuration::MultiNode(configuration)) {
1326 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1327 }
Austin Schuh15649d62019-12-28 16:36:38 -08001328}
1329
Brian Silvermane1fe2512022-08-14 23:18:50 -07001330SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {
1331 CHECK_EQ(0, exit_handle_count_)
1332 << ": All ExitHandles must be destroyed before the factory";
1333}
Alex Perrycb7da4b2019-08-28 19:35:56 -07001334
Austin Schuhac0771c2020-01-07 18:36:30 -08001335NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001336 std::string_view node) {
1337 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1338}
1339
1340NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001341 const Node *node) {
1342 auto result = std::find_if(
1343 node_factories_.begin(), node_factories_.end(),
1344 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1345 return node_factory->node() == node;
1346 });
1347
1348 CHECK(result != node_factories_.end())
1349 << ": Failed to find node " << FlatbufferToJson(node);
1350
1351 return result->get();
1352}
1353
Austin Schuh87dd3832021-01-01 23:07:31 -08001354void SimulatedEventLoopFactory::SetTimeConverter(
1355 TimeConverter *time_converter) {
1356 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1357 factory->SetTimeConverter(time_converter);
1358 }
Austin Schuh58646e22021-08-23 23:51:46 -07001359 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001360}
1361
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001362::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001363 std::string_view name, const Node *node) {
1364 if (node == nullptr) {
1365 CHECK(!configuration::MultiNode(configuration()))
1366 << ": Can't make a single node event loop in a multi-node world.";
1367 } else {
1368 CHECK(configuration::MultiNode(configuration()))
1369 << ": Can't make a multi-node event loop in a single-node world.";
1370 }
1371 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1372}
1373
Austin Schuh057d29f2021-08-21 23:05:15 -07001374NodeEventLoopFactory::NodeEventLoopFactory(
1375 EventSchedulerScheduler *scheduler_scheduler,
1376 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001377 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1378 factory_(factory),
1379 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001380 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001381 scheduler_.set_started([this]() {
1382 started_ = true;
1383 for (SimulatedEventLoop *event_loop : event_loops_) {
1384 event_loop->SetIsRunning(true);
1385 }
1386 });
Austin Schuhe33c08d2022-02-03 18:15:21 -08001387 scheduler_.set_stopped([this]() {
1388 for (SimulatedEventLoop *event_loop : event_loops_) {
1389 event_loop->SetIsRunning(false);
1390 }
1391 });
Austin Schuh58646e22021-08-23 23:51:46 -07001392 scheduler_.set_on_shutdown([this]() {
1393 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1394 << monotonic_now() << " Shutting down node.";
1395 Shutdown();
1396 ScheduleStartup();
1397 });
1398 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001399}
1400
1401NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001402 if (started_) {
1403 for (std::function<void()> &fn : on_shutdown_) {
1404 fn();
1405 }
1406
1407 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1408 << monotonic_now() << " Shutting down applications.";
1409 applications_.clear();
1410 started_ = false;
1411 }
1412
1413 if (event_loops_.size() != 0u) {
1414 for (SimulatedEventLoop *event_loop : event_loops_) {
1415 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1416 << monotonic_now() << " Event loop '" << event_loop->name()
1417 << "' failed to shut down";
1418 }
1419 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001420 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1421}
1422
Austin Schuh58646e22021-08-23 23:51:46 -07001423void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001424 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001425 << ": Can only register OnStartup handlers when not running.";
1426 on_startup_.emplace_back(std::move(fn));
1427 if (started_) {
1428 size_t on_startup_index = on_startup_.size() - 1;
1429 scheduler_.ScheduleOnStartup(
1430 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1431 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001432}
1433
Austin Schuh58646e22021-08-23 23:51:46 -07001434void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1435 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001436}
Austin Schuh057d29f2021-08-21 23:05:15 -07001437
Austin Schuh58646e22021-08-23 23:51:46 -07001438void NodeEventLoopFactory::ScheduleStartup() {
1439 scheduler_.ScheduleOnStartup([this]() {
1440 UUID next_uuid = scheduler_.boot_uuid();
1441 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001442 CHECK_EQ(boot_uuid_, UUID::Zero())
1443 << ": Boot UUID changed without restarting. Did TimeConverter "
1444 "change the boot UUID without signaling a restart, or did you "
1445 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001446 boot_uuid_ = next_uuid;
1447 }
1448 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1449 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1450 Startup();
1451 });
1452}
1453
1454void NodeEventLoopFactory::Startup() {
1455 CHECK(!started_);
1456 for (size_t i = 0; i < on_startup_.size(); ++i) {
1457 on_startup_[i]();
1458 }
1459}
1460
1461void NodeEventLoopFactory::Shutdown() {
1462 for (SimulatedEventLoop *event_loop : event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001463 CHECK(!event_loop->is_running());
Austin Schuh58646e22021-08-23 23:51:46 -07001464 }
1465
1466 CHECK(started_);
1467 started_ = false;
1468 for (std::function<void()> &fn : on_shutdown_) {
1469 fn();
1470 }
1471
1472 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1473 << monotonic_now() << " Shutting down applications.";
1474 applications_.clear();
1475
1476 if (event_loops_.size() != 0u) {
1477 for (SimulatedEventLoop *event_loop : event_loops_) {
1478 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1479 << monotonic_now() << " Event loop '" << event_loop->name()
1480 << "' failed to shut down";
1481 }
1482 }
1483 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1484 boot_uuid_ = UUID::Zero();
1485
1486 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001487}
1488
Alex Perrycb7da4b2019-08-28 19:35:56 -07001489void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001490 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001491 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001492 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1493 if (node) {
1494 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001495 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001496 }
1497 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001498 }
1499}
1500
1501void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001502 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001503 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001504 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1505 if (node) {
1506 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001507 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001508 }
1509 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001510 }
1511}
1512
Austin Schuh87dd3832021-01-01 23:07:31 -08001513void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001514
Brian Silvermane1fe2512022-08-14 23:18:50 -07001515std::unique_ptr<ExitHandle> SimulatedEventLoopFactory::MakeExitHandle() {
1516 return std::make_unique<SimulatedFactoryExitHandle>(this);
1517}
1518
Austin Schuh6f3babe2020-01-26 20:34:50 -08001519void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001520 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001521 bridge_->DisableForwarding(channel);
1522}
1523
Austin Schuh4c3b9702020-08-30 11:34:55 -07001524void SimulatedEventLoopFactory::DisableStatistics() {
1525 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
James Kuszmaul94ca5132022-07-19 09:11:08 -07001526 bridge_->DisableStatistics(
1527 message_bridge::SimulatedMessageBridge::DestroySenders::kNo);
1528}
1529
1530void SimulatedEventLoopFactory::PermanentlyDisableStatistics() {
1531 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1532 bridge_->DisableStatistics(
1533 message_bridge::SimulatedMessageBridge::DestroySenders::kYes);
Austin Schuh4c3b9702020-08-30 11:34:55 -07001534}
1535
Austin Schuh48205e62021-11-12 14:13:18 -08001536void SimulatedEventLoopFactory::EnableStatistics() {
1537 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1538 bridge_->EnableStatistics();
1539}
1540
Austin Schuh2928ebe2021-02-07 22:10:27 -08001541void SimulatedEventLoopFactory::SkipTimingReport() {
1542 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001543
1544 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1545 if (node) {
1546 node->SkipTimingReport();
1547 }
1548 }
1549}
1550
1551void NodeEventLoopFactory::SkipTimingReport() {
1552 for (SimulatedEventLoop *event_loop : event_loops_) {
1553 event_loop->SkipTimingReport();
1554 }
1555 skip_timing_report_ = true;
1556}
1557
1558void NodeEventLoopFactory::EnableStatistics() {
1559 CHECK(factory_->bridge_)
1560 << ": Can't enable statistics without a message bridge.";
1561 factory_->bridge_->EnableStatistics(node_);
1562}
1563
1564void NodeEventLoopFactory::DisableStatistics() {
1565 CHECK(factory_->bridge_)
1566 << ": Can't disable statistics without a message bridge.";
1567 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001568}
1569
Austin Schuh58646e22021-08-23 23:51:46 -07001570::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
James Kuszmaul890c2492022-04-06 14:59:31 -07001571 std::string_view name, EventLoopOptions options) {
Austin Schuh58646e22021-08-23 23:51:46 -07001572 CHECK(!scheduler_.is_running() || !started_)
1573 << ": Can't create an event loop while running";
1574
1575 pid_t tid = tid_;
1576 ++tid_;
1577 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1578 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
James Kuszmaul890c2492022-04-06 14:59:31 -07001579 node_, tid, options));
Austin Schuh58646e22021-08-23 23:51:46 -07001580 result->set_name(name);
1581 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001582 if (skip_timing_report_) {
1583 result->SkipTimingReport();
1584 }
Austin Schuh58646e22021-08-23 23:51:46 -07001585
1586 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1587 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
James Kuszmaul9776b392023-01-14 14:08:08 -08001588 return result;
Austin Schuh58646e22021-08-23 23:51:46 -07001589}
1590
Austin Schuhe33c08d2022-02-03 18:15:21 -08001591void SimulatedEventLoopFactory::AllowApplicationCreationDuring(
1592 std::function<void()> fn) {
1593 scheduler_scheduler_.TemporarilyStopAndRun(std::move(fn));
1594}
1595
Austin Schuh58646e22021-08-23 23:51:46 -07001596void NodeEventLoopFactory::Disconnect(const Node *other) {
1597 factory_->bridge_->Disconnect(node_, other);
1598}
1599
1600void NodeEventLoopFactory::Connect(const Node *other) {
1601 factory_->bridge_->Connect(node_, other);
1602}
1603
Alex Perrycb7da4b2019-08-28 19:35:56 -07001604} // namespace aos