blob: c679b215259e9d414d573df61b510b1e6a5daa29 [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
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700524 bool IsDisabled() override;
525
Alex Perrycb7da4b2019-08-28 19:35:56 -0700526 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800527 SimulatedEventLoop *simulated_event_loop_;
528 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700529 EventScheduler *scheduler_;
530 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800531
Alex Perrycb7da4b2019-08-28 19:35:56 -0700532 monotonic_clock::time_point base_;
533 monotonic_clock::duration repeat_offset_;
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700534 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535};
536
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800537class SimulatedPhasedLoopHandler : public PhasedLoopHandler,
538 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700539 public:
540 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800541 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542 ::std::function<void(int)> fn,
543 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800544 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800545 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546
Austin Schuhf4b09c72021-12-08 12:04:37 -0800547 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700548
Austin Schuh7d87b672019-12-01 20:23:49 -0800549 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800551 void Handle() noexcept override;
552
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800554 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800555 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556
Austin Schuh39788ff2019-12-01 18:22:57 -0800557 EventScheduler *scheduler_;
558 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559};
560
561class SimulatedEventLoop : public EventLoop {
562 public:
563 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700564 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
566 *channels,
567 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700568 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
James Kuszmaul890c2492022-04-06 14:59:31 -0700569 pid_t tid, EventLoopOptions options)
Austin Schuh83c7f702021-01-19 22:36:29 -0800570 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700571 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800572 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700573 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700574 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800575 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700576 tid_(tid),
James Kuszmaul890c2492022-04-06 14:59:31 -0700577 startup_tracker_(std::make_shared<StartupTracker>()),
578 options_(options) {
Austin Schuh0debde12022-08-17 16:25:17 -0700579 ClearContext();
Austin Schuh58646e22021-08-23 23:51:46 -0700580 startup_tracker_->loop = this;
581 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
582 if (startup_tracker->loop) {
583 startup_tracker->loop->Setup();
584 startup_tracker->has_setup = true;
585 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700586 });
587
588 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700589 }
Austin Schuh58646e22021-08-23 23:51:46 -0700590
Alex Perrycb7da4b2019-08-28 19:35:56 -0700591 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800592 // Trigger any remaining senders or fetchers to be cleared before destroying
593 // the event loop so the book keeping matches.
594 timing_report_sender_.reset();
595
596 // Force everything with a registered fd with epoll to be destroyed now.
597 timers_.clear();
598 phased_loops_.clear();
599 watchers_.clear();
600
Austin Schuh58646e22021-08-23 23:51:46 -0700601 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700602 if (*it == this) {
603 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700604 break;
605 }
606 }
Austin Schuh58646e22021-08-23 23:51:46 -0700607 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
608 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
609 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700610 }
611
Austin Schuh057d29f2021-08-21 23:05:15 -0700612 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700613 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
614 << monotonic_now() << " " << name_ << " set_is_running(" << running
615 << ")";
616 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700617
618 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700619 if (running) {
620 has_run_ = true;
621 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700622 }
623
Austin Schuh8fb315a2020-11-19 22:33:58 -0800624 bool has_run() const { return has_run_; }
625
Austin Schuh7d87b672019-12-01 20:23:49 -0800626 std::chrono::nanoseconds send_delay() const { return send_delay_; }
627 void set_send_delay(std::chrono::nanoseconds send_delay) {
628 send_delay_ = send_delay;
629 }
630
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800631 monotonic_clock::time_point monotonic_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800632 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700633 }
634
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800635 realtime_clock::time_point realtime_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800636 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700637 }
638
Austin Schuh58646e22021-08-23 23:51:46 -0700639 distributed_clock::time_point distributed_now() {
640 return scheduler_->distributed_now();
641 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700642
Austin Schuh58646e22021-08-23 23:51:46 -0700643 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
644
645 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700646
647 void MakeRawWatcher(
648 const Channel *channel,
649 ::std::function<void(const Context &context, const void *message)>
650 watcher) override;
651
652 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800653 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800654 return NewTimer(::std::unique_ptr<TimerHandler>(
655 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700656 }
657
658 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
659 const monotonic_clock::duration interval,
660 const monotonic_clock::duration offset =
661 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800662 return NewPhasedLoop(
663 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
664 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700665 }
666
667 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800668 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700669 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800670 logging::ScopedLogRestorer prev_logger;
671 if (log_impl_) {
672 prev_logger.Swap(log_impl_);
673 }
Austin Schuh65493d62022-08-17 15:10:37 -0700674 ScopedMarkRealtimeRestorer rt(runtime_realtime_priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700675 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700676 on_run();
Austin Schuh0debde12022-08-17 16:25:17 -0700677 ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700678 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700679 }
680
Austin Schuh217a9782019-12-21 23:02:50 -0800681 const Node *node() const override { return node_; }
682
James Kuszmaul3ae42262019-11-08 12:33:41 -0800683 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700684 name_ = std::string(name);
685 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800686 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700687
688 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
689
Austin Schuh39788ff2019-12-01 18:22:57 -0800690 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800692 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700693 }
694
Austin Schuh65493d62022-08-17 15:10:37 -0700695 int runtime_realtime_priority() const override { return priority_; }
696 const cpu_set_t &runtime_affinity() const override { return affinity_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800697
Austin Schuh65493d62022-08-17 15:10:37 -0700698 void SetRuntimeAffinity(const cpu_set_t &affinity) override {
Brian Silverman6a54ff32020-04-28 16:41:39 -0700699 CHECK(!is_running()) << ": Cannot set affinity while running.";
Austin Schuh65493d62022-08-17 15:10:37 -0700700 affinity_ = affinity;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700701 }
702
Tyler Chatow67ddb032020-01-12 14:30:04 -0800703 void Setup() {
704 MaybeScheduleTimingReports();
705 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800706 log_sender_.Initialize(&name_,
707 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700708 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800709 }
710 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800711
Brian Silverman4f4e0612020-08-12 19:54:41 -0700712 int NumberBuffers(const Channel *channel) override;
713
Austin Schuh83c7f702021-01-19 22:36:29 -0800714 const UUID &boot_uuid() const override {
715 return node_event_loop_factory_->boot_uuid();
716 }
717
James Kuszmaul890c2492022-04-06 14:59:31 -0700718 const EventLoopOptions &options() const { return options_; }
719
Alex Perrycb7da4b2019-08-28 19:35:56 -0700720 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800721 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800722 friend class SimulatedPhasedLoopHandler;
723 friend class SimulatedWatcher;
724
Austin Schuh58646e22021-08-23 23:51:46 -0700725 // We have a condition where we register a startup handler, but then get shut
726 // down before it runs. This results in a segfault if we are lucky, and
727 // corruption otherwise. To handle that, allocate a small object which points
728 // back to us and can be freed when the function is freed. That object can
729 // then be updated when we get destroyed so setup is not called.
730 struct StartupTracker {
731 SimulatedEventLoop *loop = nullptr;
732 bool has_setup = false;
733 };
734
Austin Schuh7d87b672019-12-01 20:23:49 -0800735 void HandleEvent() {
736 while (true) {
737 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
738 break;
739 }
740
741 EventLoopEvent *event = PopEvent();
742 event->HandleEvent();
743 }
744 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800745
Austin Schuh39788ff2019-12-01 18:22:57 -0800746 pid_t GetTid() override { return tid_; }
747
Alex Perrycb7da4b2019-08-28 19:35:56 -0700748 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800749 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700750 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700751 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700752
753 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800754
755 int priority_ = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700756 cpu_set_t affinity_ = DefaultAffinity();
Austin Schuh39788ff2019-12-01 18:22:57 -0800757
Austin Schuh7d87b672019-12-01 20:23:49 -0800758 std::chrono::nanoseconds send_delay_;
759
Austin Schuh217a9782019-12-21 23:02:50 -0800760 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800761 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800762
763 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700764 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800765
766 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700767
768 std::shared_ptr<StartupTracker> startup_tracker_;
James Kuszmaul890c2492022-04-06 14:59:31 -0700769
770 EventLoopOptions options_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700771};
772
Austin Schuh7d87b672019-12-01 20:23:49 -0800773void SimulatedEventLoopFactory::set_send_delay(
774 std::chrono::nanoseconds send_delay) {
775 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700776 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700777 if (node) {
778 for (SimulatedEventLoop *loop : node->event_loops_) {
779 loop->set_send_delay(send_delay_);
780 }
781 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800782 }
783}
784
James Kuszmaulb67409b2022-06-20 16:25:03 -0700785void SimulatedEventLoopFactory::SetRealtimeReplayRate(double replay_rate) {
786 scheduler_scheduler_.SetReplayRate(replay_rate);
787}
788
Alex Perrycb7da4b2019-08-28 19:35:56 -0700789void SimulatedEventLoop::MakeRawWatcher(
790 const Channel *channel,
791 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800792 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800793
Austin Schuh057d29f2021-08-21 23:05:15 -0700794 std::unique_ptr<SimulatedWatcher> shm_watcher =
795 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
796 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800797
798 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700799
Austin Schuh39788ff2019-12-01 18:22:57 -0800800 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700801 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
802 << " " << name() << " MakeRawWatcher(\""
803 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800804
805 // Order of operations gets kinda wonky if we let people make watchers after
806 // running once. If someone has a valid use case, we can reconsider.
807 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700808}
809
810std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
811 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800812 TakeSender(channel);
813
Austin Schuh58646e22021-08-23 23:51:46 -0700814 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
815 << " " << name() << " MakeRawSender(\""
816 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700817 return GetSimulatedChannel(channel)->MakeRawSender(this);
818}
819
820std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
821 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800822 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800823
Austin Schuhca4828c2019-12-28 14:21:35 -0800824 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
825 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
826 << "\", \"type\": \"" << channel->type()->string_view()
827 << "\" } is not able to be fetched on this node. Check your "
828 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800829 }
830
Austin Schuh58646e22021-08-23 23:51:46 -0700831 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
832 << " " << name() << " MakeRawFetcher(\""
833 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800834 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700835}
836
837SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
838 const Channel *channel) {
839 auto it = channels_->find(SimpleChannel(channel));
840 if (it == channels_->end()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700841 it = channels_
842 ->emplace(SimpleChannel(channel),
843 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
844 channel,
845 std::chrono::nanoseconds(
846 configuration()->channel_storage_duration()),
847 scheduler_)))
848 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700849 }
850 return it->second.get();
851}
852
Brian Silverman4f4e0612020-08-12 19:54:41 -0700853int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
854 return GetSimulatedChannel(channel)->number_buffers();
855}
856
Austin Schuh7d87b672019-12-01 20:23:49 -0800857SimulatedWatcher::SimulatedWatcher(
858 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800859 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800860 std::function<void(const Context &context, const void *message)> fn)
861 : WatcherState(simulated_event_loop, channel, std::move(fn)),
862 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700863 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800864 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700865 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700866 token_(scheduler_->InvalidToken()) {
867 VLOG(1) << simulated_event_loop_->distributed_now() << " "
868 << NodeName(simulated_event_loop_->node())
869 << simulated_event_loop_->monotonic_now() << " "
870 << simulated_event_loop_->name() << " Watching "
871 << configuration::StrippedChannelToString(channel_);
872}
Austin Schuh7d87b672019-12-01 20:23:49 -0800873
874SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700875 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700876 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700877 << simulated_event_loop_->monotonic_now() << " "
878 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700879 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800880 simulated_event_loop_->RemoveEvent(&event_);
881 if (token_ != scheduler_->InvalidToken()) {
882 scheduler_->Deschedule(token_);
883 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700884 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800885}
886
Austin Schuh8fb315a2020-11-19 22:33:58 -0800887bool SimulatedWatcher::has_run() const {
888 return simulated_event_loop_->has_run();
889}
890
Austin Schuh7d87b672019-12-01 20:23:49 -0800891void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800892 monotonic_clock::time_point event_time =
893 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800894
895 // Messages are queued in order. If we are the first, add ourselves.
896 // Otherwise, don't.
897 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800898 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800899 simulated_event_loop_->AddEvent(&event_);
900
901 DoSchedule(event_time);
902 }
903
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800904 msgs_.emplace_back(std::move(message));
Austin Schuh7d87b672019-12-01 20:23:49 -0800905}
906
Austin Schuhf4b09c72021-12-08 12:04:37 -0800907void SimulatedWatcher::HandleEvent() noexcept {
Austin Schuh7d87b672019-12-01 20:23:49 -0800908 const monotonic_clock::time_point monotonic_now =
909 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700910 VLOG(1) << simulated_event_loop_->distributed_now() << " "
911 << NodeName(simulated_event_loop_->node())
912 << simulated_event_loop_->monotonic_now() << " "
913 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700914 << configuration::StrippedChannelToString(channel_);
915 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
916
Tyler Chatow67ddb032020-01-12 14:30:04 -0800917 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700918 if (simulated_event_loop_->log_impl_) {
919 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800920 }
Austin Schuhad154822019-12-27 15:45:13 -0800921 Context context = msgs_.front()->context;
922
Brian Silverman4f4e0612020-08-12 19:54:41 -0700923 if (channel_->read_method() != ReadMethod::PIN) {
924 context.buffer_index = -1;
925 }
Austin Schuhad154822019-12-27 15:45:13 -0800926 if (context.remote_queue_index == 0xffffffffu) {
927 context.remote_queue_index = context.queue_index;
928 }
Austin Schuh58646e22021-08-23 23:51:46 -0700929 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800930 context.monotonic_remote_time = context.monotonic_event_time;
931 }
Austin Schuh58646e22021-08-23 23:51:46 -0700932 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800933 context.realtime_remote_time = context.realtime_event_time;
934 }
935
Austin Schuhcc6070c2020-10-10 20:25:56 -0700936 {
Austin Schuh65493d62022-08-17 15:10:37 -0700937 ScopedMarkRealtimeRestorer rt(
938 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700939 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh0debde12022-08-17 16:25:17 -0700940 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700941 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800942
943 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700944 if (token_ != scheduler_->InvalidToken()) {
945 scheduler_->Deschedule(token_);
946 token_ = scheduler_->InvalidToken();
947 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800948 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800949 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800950 simulated_event_loop_->AddEvent(&event_);
951
952 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800953 }
954}
955
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800956void SimulatedWatcher::Handle() noexcept {
957 DCHECK(token_ != scheduler_->InvalidToken());
958 token_ = scheduler_->InvalidToken();
959 simulated_event_loop_->HandleEvent();
960}
961
Austin Schuh7d87b672019-12-01 20:23:49 -0800962void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700963 CHECK(token_ == scheduler_->InvalidToken())
964 << ": May not schedule multiple times";
965 token_ = scheduler_->Schedule(
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800966 event_time + simulated_event_loop_->send_delay(), this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800967}
968
969void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700970 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800971 watcher->SetSimulatedChannel(this);
972 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700973}
974
975::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800976 SimulatedEventLoop *event_loop) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700977 CHECK(allow_new_senders_)
978 << ": Attempted to create a new sender on exclusive channel "
979 << configuration::StrippedChannelToString(channel_);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700980 std::optional<ExclusiveSenders> per_channel_option;
981 for (const std::pair<const aos::Channel *, ExclusiveSenders> &per_channel :
982 event_loop->options().per_channel_exclusivity) {
983 if (per_channel.first->name()->string_view() ==
984 channel_->name()->string_view() &&
985 per_channel.first->type()->string_view() ==
986 channel_->type()->string_view()) {
987 CHECK(!per_channel_option.has_value())
988 << ": Channel " << configuration::StrippedChannelToString(channel_)
989 << " listed twice in per-channel list.";
990 per_channel_option = per_channel.second;
991 }
992 }
993 if (!per_channel_option.has_value()) {
994 // This could just as easily be implemented by setting
995 // per_channel_option to the global setting when we initialize it, but
996 // then we'd lose track of whether a given channel appears twice in
997 // the list.
998 per_channel_option = event_loop->options().exclusive_senders;
999 }
1000 if (per_channel_option.value() == ExclusiveSenders::kYes) {
James Kuszmaul890c2492022-04-06 14:59:31 -07001001 CHECK_EQ(0, sender_count_)
1002 << ": Attempted to add an exclusive sender on a channel with existing "
1003 "senders: "
1004 << configuration::StrippedChannelToString(channel_);
1005 allow_new_senders_ = false;
1006 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001007 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
1008}
1009
Austin Schuh39788ff2019-12-01 18:22:57 -08001010::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
1011 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -07001012 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -08001013 ::std::unique_ptr<SimulatedFetcher> fetcher(
1014 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -07001015 fetchers_.push_back(fetcher.get());
James Kuszmaul9776b392023-01-14 14:08:08 -08001016 return fetcher;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001017}
1018
milind1f1dca32021-07-03 13:50:07 -07001019std::optional<uint32_t> SimulatedChannel::Send(
Austin Schuh60e77942022-05-16 17:48:24 -07001020 std::shared_ptr<SimulatedMessage> message,
1021 CheckSentTooFast check_sent_too_fast) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001022 const auto now = scheduler_->monotonic_now();
1023 // Remove times that are greater than or equal to a channel_storage_duration_
1024 // ago
1025 while (!last_times_.empty() &&
1026 (now - last_times_.front() >= channel_storage_duration_)) {
1027 last_times_.pop();
1028 }
1029
1030 // Check that we are not sending messages too fast
James Kuszmaul890c2492022-04-06 14:59:31 -07001031 if (check_sent_too_fast == CheckSentTooFast::kYes &&
1032 static_cast<int>(last_times_.size()) >= queue_size()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001033 return std::nullopt;
1034 }
1035
1036 const std::optional<uint32_t> queue_index = {next_queue_index_.index()};
1037 last_times_.push(now);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001038
milind1f1dca32021-07-03 13:50:07 -07001039 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001040 // Points to the actual data depending on the size set in context. Data may
1041 // allocate more than the actual size of the message, so offset from the back
1042 // of that to get the actual start of the data.
1043 message->context.data =
1044 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -07001045
1046 DCHECK(channel()->has_schema())
1047 << ": Missing schema for channel "
1048 << configuration::StrippedChannelToString(channel());
1049 DCHECK(flatbuffers::Verify(
1050 *channel()->schema(), *channel()->schema()->root_table(),
1051 static_cast<const uint8_t *>(message->context.data),
1052 message->context.size))
1053 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
1054 << channel()->type()->c_str();
1055
Alex Perrycb7da4b2019-08-28 19:35:56 -07001056 next_queue_index_ = next_queue_index_.Increment();
1057
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001058 latest_message_ = std::move(message);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001059 for (SimulatedWatcher *watcher : watchers_) {
1060 if (watcher->has_run()) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001061 watcher->Schedule(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001062 }
1063 }
1064 for (auto &fetcher : fetchers_) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001065 fetcher->Enqueue(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001066 }
Austin Schuhad154822019-12-27 15:45:13 -08001067 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001068}
1069
1070void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
1071 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
1072}
1073
Austin Schuh8fb315a2020-11-19 22:33:58 -08001074SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
1075 SimulatedEventLoop *event_loop)
1076 : RawSender(event_loop, simulated_channel->channel()),
1077 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -07001078 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -08001079 simulated_channel_->CountSenderCreated();
1080}
1081
1082SimulatedSender::~SimulatedSender() {
1083 simulated_channel_->CountSenderDestroyed();
1084}
1085
milind1f1dca32021-07-03 13:50:07 -07001086RawSender::Error SimulatedSender::DoSend(
1087 size_t length, monotonic_clock::time_point monotonic_remote_time,
1088 realtime_clock::time_point realtime_remote_time,
1089 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001090 // The allocations in here are due to infrastructure and don't count in the
1091 // no mallocs in RT code.
1092 ScopedNotRealtime nrt;
1093
Austin Schuh58646e22021-08-23 23:51:46 -07001094 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1095 << NodeName(simulated_event_loop_->node())
1096 << simulated_event_loop_->monotonic_now() << " "
1097 << simulated_event_loop_->name() << " Send "
1098 << configuration::StrippedChannelToString(channel());
1099
Austin Schuh8fb315a2020-11-19 22:33:58 -08001100 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -07001101 message_->context.monotonic_event_time =
1102 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001103 message_->context.monotonic_remote_time = monotonic_remote_time;
1104 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001105 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001106 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001107 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001108 CHECK_LE(length, message_->context.size);
1109 message_->context.size = length;
1110
Austin Schuh60e77942022-05-16 17:48:24 -07001111 const std::optional<uint32_t> optional_queue_index = simulated_channel_->Send(
1112 message_, simulated_event_loop_->options().check_sent_too_fast);
milind1f1dca32021-07-03 13:50:07 -07001113
1114 // Check that we are not sending messages too fast
1115 if (!optional_queue_index) {
1116 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1117 << NodeName(simulated_event_loop_->node())
1118 << simulated_event_loop_->monotonic_now() << " "
1119 << simulated_event_loop_->name()
1120 << "\nMessages were sent too fast:\n"
1121 << "For channel: "
1122 << configuration::CleanedChannelToString(
1123 simulated_channel_->channel())
1124 << '\n'
1125 << "Tried to send more than " << simulated_channel_->queue_size()
1126 << " (queue size) messages in the last "
1127 << std::chrono::duration<double>(
1128 simulated_channel_->channel_storage_duration())
1129 .count()
1130 << " seconds (channel storage duration)"
1131 << "\n\n";
1132 return Error::kMessagesSentTooFast;
1133 }
1134
1135 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001136 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1137 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001138
1139 // Drop the reference to the message so that we allocate a new message for
1140 // next time. Otherwise we will continue to reuse the same memory for all
1141 // messages and corrupt it.
1142 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001143 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001144}
1145
milind1f1dca32021-07-03 13:50:07 -07001146RawSender::Error SimulatedSender::DoSend(
1147 const void *msg, size_t size,
1148 monotonic_clock::time_point monotonic_remote_time,
1149 realtime_clock::time_point realtime_remote_time,
1150 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001151 CHECK_LE(size, this->size())
1152 << ": Attempting to send too big a message on "
1153 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001154
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001155 // Allocates an aligned buffer in which to copy unaligned msg.
1156 auto [span, mutable_span] = MakeSharedSpan(size);
1157 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001158
1159 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001160 // queue_index will be populated in simulated_channel_.
1161 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001162
1163 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001164 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001165}
1166
milind1f1dca32021-07-03 13:50:07 -07001167RawSender::Error SimulatedSender::DoSend(
1168 const RawSender::SharedSpan data,
1169 monotonic_clock::time_point monotonic_remote_time,
1170 realtime_clock::time_point realtime_remote_time,
1171 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001172 CHECK_LE(data->size(), this->size())
1173 << ": Attempting to send too big a message on "
1174 << configuration::CleanedChannelToString(simulated_channel_->channel());
1175
1176 // Constructs a message sharing the already allocated and aligned message
1177 // data.
1178 message_ = SimulatedMessage::Make(simulated_channel_, data);
1179
1180 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1181 remote_queue_index, source_boot_uuid);
1182}
1183
Austin Schuh39788ff2019-12-01 18:22:57 -08001184SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001185 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1186 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001187 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001188 simulated_event_loop_(simulated_event_loop),
1189 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001190 scheduler_(scheduler),
1191 token_(scheduler_->InvalidToken()) {}
1192
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001193void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
1194 monotonic_clock::duration repeat_offset) {
James Kuszmaul86e86c32022-07-21 17:39:47 -07001195 CHECK_GE(base, monotonic_clock::epoch());
Austin Schuh62288252020-11-18 23:26:04 -08001196 // The allocations in here are due to infrastructure and don't count in the no
1197 // mallocs in RT code.
1198 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001199 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001200 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001201 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001202 base_ = base;
1203 repeat_offset_ = repeat_offset;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001204 token_ = scheduler_->Schedule(std::max(base, monotonic_now), this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001205 event_.set_event_time(base_);
1206 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001207 disabled_ = false;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001208}
1209
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001210void SimulatedTimerHandler::Handle() noexcept {
1211 DCHECK(token_ != scheduler_->InvalidToken());
1212 token_ = scheduler_->InvalidToken();
1213 simulated_event_loop_->HandleEvent();
1214}
1215
Austin Schuhf4b09c72021-12-08 12:04:37 -08001216void SimulatedTimerHandler::HandleEvent() noexcept {
Austin Schuh58646e22021-08-23 23:51:46 -07001217 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001218 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001219 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1220 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1221 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001222 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001223 if (simulated_event_loop_->log_impl_) {
1224 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001225 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001226 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001227 {
1228 ScopedNotRealtime nrt;
1229 scheduler_->Deschedule(token_);
1230 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001231 token_ = scheduler_->InvalidToken();
1232 }
Austin Schuh58646e22021-08-23 23:51:46 -07001233 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001234 // Reschedule.
1235 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001236 token_ = scheduler_->Schedule(base_, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001237 event_.set_event_time(base_);
1238 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001239 disabled_ = false;
1240 } else {
1241 disabled_ = true;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001242 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001243 {
Austin Schuh65493d62022-08-17 15:10:37 -07001244 ScopedMarkRealtimeRestorer rt(
1245 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -07001246 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuh0debde12022-08-17 16:25:17 -07001247 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001248 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001249}
1250
Austin Schuh7d87b672019-12-01 20:23:49 -08001251void SimulatedTimerHandler::Disable() {
1252 simulated_event_loop_->RemoveEvent(&event_);
1253 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001254 {
1255 ScopedNotRealtime nrt;
1256 scheduler_->Deschedule(token_);
1257 }
Austin Schuh7d87b672019-12-01 20:23:49 -08001258 token_ = scheduler_->InvalidToken();
1259 }
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001260 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -08001261}
1262
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001263bool SimulatedTimerHandler::IsDisabled() { return disabled_; }
1264
Austin Schuh39788ff2019-12-01 18:22:57 -08001265SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001266 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1267 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001268 const monotonic_clock::duration offset)
1269 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1270 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001271 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001272 scheduler_(scheduler),
1273 token_(scheduler_->InvalidToken()) {}
1274
Austin Schuh7d87b672019-12-01 20:23:49 -08001275SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1276 if (token_ != scheduler_->InvalidToken()) {
1277 scheduler_->Deschedule(token_);
1278 token_ = scheduler_->InvalidToken();
1279 }
1280 simulated_event_loop_->RemoveEvent(&event_);
1281}
1282
Austin Schuhf4b09c72021-12-08 12:04:37 -08001283void SimulatedPhasedLoopHandler::HandleEvent() noexcept {
Austin Schuh39788ff2019-12-01 18:22:57 -08001284 monotonic_clock::time_point monotonic_now =
1285 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001286 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1287 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001288 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001289 if (simulated_event_loop_->log_impl_) {
1290 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001291 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001292
1293 {
Austin Schuh65493d62022-08-17 15:10:37 -07001294 ScopedMarkRealtimeRestorer rt(
1295 simulated_event_loop_->runtime_realtime_priority() > 0);
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001296 Call([monotonic_now]() { return monotonic_now; });
Austin Schuh0debde12022-08-17 16:25:17 -07001297 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001298 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001299}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001300
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001301void SimulatedPhasedLoopHandler::Handle() noexcept {
1302 DCHECK(token_ != scheduler_->InvalidToken());
1303 token_ = scheduler_->InvalidToken();
1304 simulated_event_loop_->HandleEvent();
1305}
1306
Austin Schuh7d87b672019-12-01 20:23:49 -08001307void SimulatedPhasedLoopHandler::Schedule(
1308 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001309 // The allocations in here are due to infrastructure and don't count in the no
1310 // mallocs in RT code.
1311 ScopedNotRealtime nrt;
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001312 simulated_event_loop_->RemoveEvent(&event_);
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001313 if (token_ != scheduler_->InvalidToken()) {
1314 scheduler_->Deschedule(token_);
1315 token_ = scheduler_->InvalidToken();
1316 }
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001317 token_ = scheduler_->Schedule(sleep_time, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001318 event_.set_event_time(sleep_time);
1319 simulated_event_loop_->AddEvent(&event_);
1320}
1321
Alex Perrycb7da4b2019-08-28 19:35:56 -07001322SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1323 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001324 : configuration_(CHECK_NOTNULL(configuration)),
1325 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001326 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001327 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001328 node_factories_.emplace_back(
1329 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001330 }
Austin Schuh898f4972020-01-11 17:21:25 -08001331
1332 if (configuration::MultiNode(configuration)) {
1333 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1334 }
Austin Schuh15649d62019-12-28 16:36:38 -08001335}
1336
Brian Silvermane1fe2512022-08-14 23:18:50 -07001337SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {
1338 CHECK_EQ(0, exit_handle_count_)
1339 << ": All ExitHandles must be destroyed before the factory";
1340}
Alex Perrycb7da4b2019-08-28 19:35:56 -07001341
Austin Schuhac0771c2020-01-07 18:36:30 -08001342NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001343 std::string_view node) {
1344 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1345}
1346
1347NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001348 const Node *node) {
1349 auto result = std::find_if(
1350 node_factories_.begin(), node_factories_.end(),
1351 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1352 return node_factory->node() == node;
1353 });
1354
1355 CHECK(result != node_factories_.end())
1356 << ": Failed to find node " << FlatbufferToJson(node);
1357
1358 return result->get();
1359}
1360
Austin Schuh87dd3832021-01-01 23:07:31 -08001361void SimulatedEventLoopFactory::SetTimeConverter(
1362 TimeConverter *time_converter) {
1363 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1364 factory->SetTimeConverter(time_converter);
1365 }
Austin Schuh58646e22021-08-23 23:51:46 -07001366 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001367}
1368
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001369::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001370 std::string_view name, const Node *node) {
1371 if (node == nullptr) {
1372 CHECK(!configuration::MultiNode(configuration()))
1373 << ": Can't make a single node event loop in a multi-node world.";
1374 } else {
1375 CHECK(configuration::MultiNode(configuration()))
1376 << ": Can't make a multi-node event loop in a single-node world.";
1377 }
1378 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1379}
1380
Austin Schuh057d29f2021-08-21 23:05:15 -07001381NodeEventLoopFactory::NodeEventLoopFactory(
1382 EventSchedulerScheduler *scheduler_scheduler,
1383 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001384 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1385 factory_(factory),
1386 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001387 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001388 scheduler_.set_started([this]() {
1389 started_ = true;
1390 for (SimulatedEventLoop *event_loop : event_loops_) {
1391 event_loop->SetIsRunning(true);
1392 }
1393 });
Austin Schuhe33c08d2022-02-03 18:15:21 -08001394 scheduler_.set_stopped([this]() {
1395 for (SimulatedEventLoop *event_loop : event_loops_) {
1396 event_loop->SetIsRunning(false);
1397 }
1398 });
Austin Schuh58646e22021-08-23 23:51:46 -07001399 scheduler_.set_on_shutdown([this]() {
1400 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1401 << monotonic_now() << " Shutting down node.";
1402 Shutdown();
1403 ScheduleStartup();
1404 });
1405 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001406}
1407
1408NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001409 if (started_) {
1410 for (std::function<void()> &fn : on_shutdown_) {
1411 fn();
1412 }
1413
1414 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1415 << monotonic_now() << " Shutting down applications.";
1416 applications_.clear();
1417 started_ = false;
1418 }
1419
1420 if (event_loops_.size() != 0u) {
1421 for (SimulatedEventLoop *event_loop : event_loops_) {
1422 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1423 << monotonic_now() << " Event loop '" << event_loop->name()
1424 << "' failed to shut down";
1425 }
1426 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001427 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1428}
1429
Austin Schuh58646e22021-08-23 23:51:46 -07001430void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001431 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001432 << ": Can only register OnStartup handlers when not running.";
1433 on_startup_.emplace_back(std::move(fn));
1434 if (started_) {
1435 size_t on_startup_index = on_startup_.size() - 1;
1436 scheduler_.ScheduleOnStartup(
1437 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1438 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001439}
1440
Austin Schuh58646e22021-08-23 23:51:46 -07001441void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1442 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001443}
Austin Schuh057d29f2021-08-21 23:05:15 -07001444
Austin Schuh58646e22021-08-23 23:51:46 -07001445void NodeEventLoopFactory::ScheduleStartup() {
1446 scheduler_.ScheduleOnStartup([this]() {
1447 UUID next_uuid = scheduler_.boot_uuid();
1448 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001449 CHECK_EQ(boot_uuid_, UUID::Zero())
1450 << ": Boot UUID changed without restarting. Did TimeConverter "
1451 "change the boot UUID without signaling a restart, or did you "
1452 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001453 boot_uuid_ = next_uuid;
1454 }
1455 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1456 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1457 Startup();
1458 });
1459}
1460
1461void NodeEventLoopFactory::Startup() {
1462 CHECK(!started_);
1463 for (size_t i = 0; i < on_startup_.size(); ++i) {
1464 on_startup_[i]();
1465 }
1466}
1467
1468void NodeEventLoopFactory::Shutdown() {
1469 for (SimulatedEventLoop *event_loop : event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001470 CHECK(!event_loop->is_running());
Austin Schuh58646e22021-08-23 23:51:46 -07001471 }
1472
1473 CHECK(started_);
1474 started_ = false;
1475 for (std::function<void()> &fn : on_shutdown_) {
1476 fn();
1477 }
1478
1479 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1480 << monotonic_now() << " Shutting down applications.";
1481 applications_.clear();
1482
1483 if (event_loops_.size() != 0u) {
1484 for (SimulatedEventLoop *event_loop : event_loops_) {
1485 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1486 << monotonic_now() << " Event loop '" << event_loop->name()
1487 << "' failed to shut down";
1488 }
1489 }
1490 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1491 boot_uuid_ = UUID::Zero();
1492
1493 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001494}
1495
Alex Perrycb7da4b2019-08-28 19:35:56 -07001496void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001497 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001498 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001499 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1500 if (node) {
1501 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001502 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001503 }
1504 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001505 }
1506}
1507
1508void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001509 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001510 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001511 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1512 if (node) {
1513 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001514 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001515 }
1516 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001517 }
1518}
1519
Austin Schuh87dd3832021-01-01 23:07:31 -08001520void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001521
Brian Silvermane1fe2512022-08-14 23:18:50 -07001522std::unique_ptr<ExitHandle> SimulatedEventLoopFactory::MakeExitHandle() {
1523 return std::make_unique<SimulatedFactoryExitHandle>(this);
1524}
1525
Austin Schuh6f3babe2020-01-26 20:34:50 -08001526void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001527 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001528 bridge_->DisableForwarding(channel);
1529}
1530
Austin Schuh4c3b9702020-08-30 11:34:55 -07001531void SimulatedEventLoopFactory::DisableStatistics() {
1532 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
James Kuszmaul94ca5132022-07-19 09:11:08 -07001533 bridge_->DisableStatistics(
1534 message_bridge::SimulatedMessageBridge::DestroySenders::kNo);
1535}
1536
1537void SimulatedEventLoopFactory::PermanentlyDisableStatistics() {
1538 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1539 bridge_->DisableStatistics(
1540 message_bridge::SimulatedMessageBridge::DestroySenders::kYes);
Austin Schuh4c3b9702020-08-30 11:34:55 -07001541}
1542
Austin Schuh48205e62021-11-12 14:13:18 -08001543void SimulatedEventLoopFactory::EnableStatistics() {
1544 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1545 bridge_->EnableStatistics();
1546}
1547
Austin Schuh2928ebe2021-02-07 22:10:27 -08001548void SimulatedEventLoopFactory::SkipTimingReport() {
1549 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001550
1551 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1552 if (node) {
1553 node->SkipTimingReport();
1554 }
1555 }
1556}
1557
1558void NodeEventLoopFactory::SkipTimingReport() {
1559 for (SimulatedEventLoop *event_loop : event_loops_) {
1560 event_loop->SkipTimingReport();
1561 }
1562 skip_timing_report_ = true;
1563}
1564
1565void NodeEventLoopFactory::EnableStatistics() {
1566 CHECK(factory_->bridge_)
1567 << ": Can't enable statistics without a message bridge.";
1568 factory_->bridge_->EnableStatistics(node_);
1569}
1570
1571void NodeEventLoopFactory::DisableStatistics() {
1572 CHECK(factory_->bridge_)
1573 << ": Can't disable statistics without a message bridge.";
1574 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001575}
1576
Austin Schuh58646e22021-08-23 23:51:46 -07001577::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
James Kuszmaul890c2492022-04-06 14:59:31 -07001578 std::string_view name, EventLoopOptions options) {
Austin Schuh58646e22021-08-23 23:51:46 -07001579 CHECK(!scheduler_.is_running() || !started_)
1580 << ": Can't create an event loop while running";
1581
1582 pid_t tid = tid_;
1583 ++tid_;
1584 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1585 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
James Kuszmaul890c2492022-04-06 14:59:31 -07001586 node_, tid, options));
Austin Schuh58646e22021-08-23 23:51:46 -07001587 result->set_name(name);
1588 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001589 if (skip_timing_report_) {
1590 result->SkipTimingReport();
1591 }
Austin Schuh58646e22021-08-23 23:51:46 -07001592
1593 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1594 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
James Kuszmaul9776b392023-01-14 14:08:08 -08001595 return result;
Austin Schuh58646e22021-08-23 23:51:46 -07001596}
1597
Austin Schuhe33c08d2022-02-03 18:15:21 -08001598void SimulatedEventLoopFactory::AllowApplicationCreationDuring(
1599 std::function<void()> fn) {
1600 scheduler_scheduler_.TemporarilyStopAndRun(std::move(fn));
1601}
1602
Austin Schuh58646e22021-08-23 23:51:46 -07001603void NodeEventLoopFactory::Disconnect(const Node *other) {
1604 factory_->bridge_->Disconnect(node_, other);
1605}
1606
1607void NodeEventLoopFactory::Connect(const Node *other) {
1608 factory_->bridge_->Connect(node_, other);
1609}
1610
Alex Perrycb7da4b2019-08-28 19:35:56 -07001611} // namespace aos