blob: f570296e652b243e210ee5dd47974d8d32d243be [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
70 absl::Span mutable_span(
71 reinterpret_cast<uint8_t *>(RoundChannelData(&span->data[0], size)),
72 size);
73 new (span) AlignedOwningSpan{.span = mutable_span};
74
75 return std::make_pair(
76 RawSender::SharedSpan(
77 std::shared_ptr<AlignedOwningSpan>(span,
78 [](AlignedOwningSpan *s) {
79 s->~AlignedOwningSpan();
80 free(s);
81 }),
82 &span->span),
83 mutable_span);
84}
85
Alex Perrycb7da4b2019-08-28 19:35:56 -070086// Container for both a message, and the context for it for simulation. This
87// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070088struct SimulatedMessage final {
89 SimulatedMessage(const SimulatedMessage &) = delete;
90 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070091 ~SimulatedMessage();
Brian Silverman661eb8d2020-08-12 19:41:01 -070092
93 // Creates a SimulatedMessage with size bytes of storage.
94 // This is a shared_ptr so we don't have to implement refcounting or copying.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070095 static std::shared_ptr<SimulatedMessage> Make(
96 SimulatedChannel *channel, const RawSender::SharedSpan data);
Brian Silverman661eb8d2020-08-12 19:41:01 -070097
Alex Perrycb7da4b2019-08-28 19:35:56 -070098 // Context for the data.
99 Context context;
100
Brian Silverman661eb8d2020-08-12 19:41:01 -0700101 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700102
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700103 // Owning span to this message's data. Depending on the sender may either
104 // represent the data of just the flatbuffer, or max channel size.
105 RawSender::SharedSpan data;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700106
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700107 // Mutable view of above data. If empty, this message is not mutable.
108 absl::Span<uint8_t> mutable_data;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700109
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700110 // Determines whether this message is mutable. Used for Send where the user
111 // fills out a message stored internally then gives us the size of data used.
112 bool is_mutable() const { return data->size() == mutable_data.size(); }
113
114 // Note: this should be private but make_shared requires it to be public. Use
115 // Make() above to construct.
Brian Silverman661eb8d2020-08-12 19:41:01 -0700116 SimulatedMessage(SimulatedChannel *channel_in);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117};
118
Brian Silverman661eb8d2020-08-12 19:41:01 -0700119} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -0800120
Brian Silverman661eb8d2020-08-12 19:41:01 -0700121// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
122// for some reason...
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800123class SimulatedWatcher : public WatcherState, public EventScheduler::Event {
Austin Schuh39788ff2019-12-01 18:22:57 -0800124 public:
Austin Schuh7d87b672019-12-01 20:23:49 -0800125 SimulatedWatcher(
126 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
127 const Channel *channel,
128 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -0800129
Austin Schuh7d87b672019-12-01 20:23:49 -0800130 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -0800131
Austin Schuh8fb315a2020-11-19 22:33:58 -0800132 bool has_run() const;
133
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800134 void Handle() noexcept override;
135
Austin Schuh39788ff2019-12-01 18:22:57 -0800136 void Startup(EventLoop * /*event_loop*/) override {}
137
Austin Schuh7d87b672019-12-01 20:23:49 -0800138 void Schedule(std::shared_ptr<SimulatedMessage> message);
139
Austin Schuhf4b09c72021-12-08 12:04:37 -0800140 void HandleEvent() noexcept;
Austin Schuh39788ff2019-12-01 18:22:57 -0800141
142 void SetSimulatedChannel(SimulatedChannel *channel) {
143 simulated_channel_ = channel;
144 }
145
146 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800147 void DoSchedule(monotonic_clock::time_point event_time);
148
149 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
150
Brian Silverman4f4e0612020-08-12 19:54:41 -0700151 SimulatedEventLoop *const simulated_event_loop_;
152 const Channel *const channel_;
153 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800154 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800155 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800156 SimulatedChannel *simulated_channel_ = nullptr;
157};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700158
Brian Silvermane1fe2512022-08-14 23:18:50 -0700159class SimulatedFactoryExitHandle : public ExitHandle {
160 public:
161 SimulatedFactoryExitHandle(SimulatedEventLoopFactory *factory)
162 : factory_(factory) {
163 ++factory_->exit_handle_count_;
164 }
165 ~SimulatedFactoryExitHandle() override {
166 CHECK_GT(factory_->exit_handle_count_, 0);
167 --factory_->exit_handle_count_;
168 }
169
170 void Exit() override { factory_->Exit(); }
171
172 private:
173 SimulatedEventLoopFactory *const factory_;
174};
175
Alex Perrycb7da4b2019-08-28 19:35:56 -0700176class SimulatedChannel {
177 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800178 explicit SimulatedChannel(const Channel *channel,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700179 std::chrono::nanoseconds channel_storage_duration,
180 const EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -0800181 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700182 channel_storage_duration_(channel_storage_duration),
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700183 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())),
184 scheduler_(scheduler) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700185 available_buffer_indices_.resize(number_buffers());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700186 for (int i = 0; i < number_buffers(); ++i) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700187 available_buffer_indices_[i] = i;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700188 }
189 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700190
Brian Silverman661eb8d2020-08-12 19:41:01 -0700191 ~SimulatedChannel() {
192 latest_message_.reset();
193 CHECK_EQ(static_cast<size_t>(number_buffers()),
194 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800195 CHECK_EQ(0u, fetchers_.size())
196 << configuration::StrippedChannelToString(channel());
197 CHECK_EQ(0u, watchers_.size())
198 << configuration::StrippedChannelToString(channel());
199 CHECK_EQ(0, sender_count_)
200 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700201 }
202
203 // The number of messages we pretend to have in the queue.
204 int queue_size() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700205 return configuration::QueueSize(channel()->frequency(),
206 channel_storage_duration_);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700207 }
208
milind1f1dca32021-07-03 13:50:07 -0700209 std::chrono::nanoseconds channel_storage_duration() const {
210 return channel_storage_duration_;
211 }
212
Brian Silverman661eb8d2020-08-12 19:41:01 -0700213 // The number of extra buffers (beyond the queue) we pretend to have.
214 int number_scratch_buffers() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700215 return configuration::QueueScratchBufferSize(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700216 }
217
218 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
219
220 int GetBufferIndex() {
221 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
222 const int result = available_buffer_indices_.back();
223 available_buffer_indices_.pop_back();
224 return result;
225 }
226
227 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700228 // This extra checking has a large performance hit with sanitizers that
229 // track memory accesses, so just skip it.
230#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700231 DCHECK(std::find(available_buffer_indices_.begin(),
232 available_buffer_indices_.end(),
233 i) == available_buffer_indices_.end())
234 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800235#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700236 available_buffer_indices_.push_back(i);
237 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700238
239 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800240 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700241
242 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800243 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700244
245 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800246 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800247
Austin Schuh7d87b672019-12-01 20:23:49 -0800248 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800249 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
250 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700251
Austin Schuhad154822019-12-27 15:45:13 -0800252 // Sends the message to all the connected receivers and fetchers. Returns the
milind1f1dca32021-07-03 13:50:07 -0700253 // sent queue index, or std::nullopt if messages were sent too fast.
James Kuszmaul890c2492022-04-06 14:59:31 -0700254 std::optional<uint32_t> Send(std::shared_ptr<SimulatedMessage> message,
255 CheckSentTooFast check_sent_too_fast);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256
257 // Unregisters a fetcher.
258 void UnregisterFetcher(SimulatedFetcher *fetcher);
259
260 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
261
Austin Schuh39788ff2019-12-01 18:22:57 -0800262 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700263
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800264 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800265 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700266 }
267
Austin Schuh39788ff2019-12-01 18:22:57 -0800268 const Channel *channel() const { return channel_; }
269
Austin Schuhe516ab02020-05-06 21:37:04 -0700270 void CountSenderCreated() {
271 if (sender_count_ >= channel()->num_senders()) {
272 LOG(FATAL) << "Failed to create sender on "
273 << configuration::CleanedChannelToString(channel())
274 << ", too many senders.";
275 }
Austin Schuhfb37c612022-08-11 15:24:51 -0700276 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700277 ++sender_count_;
278 }
Brian Silverman77162972020-08-12 19:52:40 -0700279
Austin Schuhe516ab02020-05-06 21:37:04 -0700280 void CountSenderDestroyed() {
281 --sender_count_;
282 CHECK_GE(sender_count_, 0);
James Kuszmaul890c2492022-04-06 14:59:31 -0700283 if (sender_count_ == 0) {
284 allow_new_senders_ = true;
285 }
Austin Schuhe516ab02020-05-06 21:37:04 -0700286 }
287
Alex Perrycb7da4b2019-08-28 19:35:56 -0700288 private:
Brian Silverman77162972020-08-12 19:52:40 -0700289 void CheckBufferCount() {
290 int reader_count = 0;
291 if (channel()->read_method() == ReadMethod::PIN) {
292 reader_count = watchers_.size() + fetchers_.size();
293 }
294 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
295 }
296
297 void CheckReaderCount() {
298 if (channel()->read_method() != ReadMethod::PIN) {
299 return;
300 }
301 CheckBufferCount();
302 const int reader_count = watchers_.size() + fetchers_.size();
303 if (reader_count >= channel()->num_readers()) {
304 LOG(FATAL) << "Failed to create reader on "
305 << configuration::CleanedChannelToString(channel())
306 << ", too many readers.";
307 }
308 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700309
310 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700311 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700312
313 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800314 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315
316 // List of all fetchers.
317 ::std::vector<SimulatedFetcher *> fetchers_;
318 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700319
320 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700321
322 int sender_count_ = 0;
James Kuszmaul890c2492022-04-06 14:59:31 -0700323 // Used to track when an exclusive sender has been created (e.g., for log
324 // replay) and we want to prevent new senders from being accidentally created.
325 bool allow_new_senders_ = true;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700326
327 std::vector<uint16_t> available_buffer_indices_;
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700328
329 const EventScheduler *scheduler_;
330
331 // Queue of all the message send times in the last channel_storage_duration_
332 std::queue<monotonic_clock::time_point> last_times_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700333};
334
335namespace {
336
Brian Silverman661eb8d2020-08-12 19:41:01 -0700337std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700338 SimulatedChannel *channel, RawSender::SharedSpan data) {
Austin Schuh62288252020-11-18 23:26:04 -0800339 // The allocations in here are due to infrastructure and don't count in the no
340 // mallocs in RT code.
341 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700342
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700343 auto message = std::make_shared<SimulatedMessage>(channel);
344 message->context.size = data->size();
345 message->context.data = data->data();
346 message->data = std::move(data);
347
348 return message;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700349}
350
351SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
352 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700353 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700354}
355
356SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700357 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700358}
359
360class SimulatedSender : public RawSender {
361 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800362 SimulatedSender(SimulatedChannel *simulated_channel,
363 SimulatedEventLoop *event_loop);
364 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365
366 void *data() override {
367 if (!message_) {
Austin Schuh9b1d6282022-06-10 17:03:21 -0700368 // This API is safe to use in a RT context on a RT system. So annotate it
369 // accordingly.
370 ScopedNotRealtime nrt;
371
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700372 auto [span, mutable_span] =
373 MakeSharedSpan(simulated_channel_->max_size());
374 message_ = SimulatedMessage::Make(simulated_channel_, span);
375 message_->mutable_data = mutable_span;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700377 CHECK(message_->is_mutable());
378 return message_->mutable_data.data();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700379 }
380
381 size_t size() override { return simulated_channel_->max_size(); }
382
milind1f1dca32021-07-03 13:50:07 -0700383 Error DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
384 realtime_clock::time_point realtime_remote_time,
385 uint32_t remote_queue_index,
386 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700387
milind1f1dca32021-07-03 13:50:07 -0700388 Error DoSend(const void *msg, size_t size,
389 monotonic_clock::time_point monotonic_remote_time,
390 realtime_clock::time_point realtime_remote_time,
391 uint32_t remote_queue_index,
392 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393
milind1f1dca32021-07-03 13:50:07 -0700394 Error DoSend(const SharedSpan data,
395 aos::monotonic_clock::time_point monotonic_remote_time,
396 aos::realtime_clock::time_point realtime_remote_time,
397 uint32_t remote_queue_index,
398 const UUID &source_boot_uuid) override;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700399
Brian Silverman4f4e0612020-08-12 19:54:41 -0700400 int buffer_index() override {
401 // First, ensure message_ is allocated.
402 data();
403 return message_->context.buffer_index;
404 }
405
Alex Perrycb7da4b2019-08-28 19:35:56 -0700406 private:
407 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700408 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409
410 std::shared_ptr<SimulatedMessage> message_;
411};
412} // namespace
413
414class SimulatedFetcher : public RawFetcher {
415 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800416 explicit SimulatedFetcher(EventLoop *event_loop,
417 SimulatedChannel *simulated_channel)
418 : RawFetcher(event_loop, simulated_channel->channel()),
419 simulated_channel_(simulated_channel) {}
420 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700421
Austin Schuh39788ff2019-12-01 18:22:57 -0800422 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800423 // The allocations in here are due to infrastructure and don't count in the
424 // no mallocs in RT code.
425 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800426 if (msgs_.size() == 0) {
427 return std::make_pair(false, monotonic_clock::min_time);
428 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700429
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700430 CHECK(!fell_behind_) << ": Got behind on "
431 << configuration::StrippedChannelToString(
432 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700433
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434 SetMsg(msgs_.front());
435 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800436 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700437 }
438
Austin Schuh39788ff2019-12-01 18:22:57 -0800439 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800440 // The allocations in here are due to infrastructure and don't count in the
441 // no mallocs in RT code.
442 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800444 // TODO(austin): Can we just do this logic unconditionally? It is a lot
445 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800446 if (!msg_ && simulated_channel_->latest_message()) {
447 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800448 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700449 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800450 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 }
452 }
453
454 // We've had a message enqueued, so we don't need to go looking for the
455 // latest message from before we started.
456 SetMsg(msgs_.back());
457 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700458 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800459 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460 }
461
462 private:
463 friend class SimulatedChannel;
464
465 // Updates the state inside RawFetcher to point to the data in msg_.
466 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800467 msg_ = std::move(msg);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700469 if (channel()->read_method() != ReadMethod::PIN) {
470 context_.buffer_index = -1;
471 }
Austin Schuhad154822019-12-27 15:45:13 -0800472 if (context_.remote_queue_index == 0xffffffffu) {
473 context_.remote_queue_index = context_.queue_index;
474 }
Austin Schuh58646e22021-08-23 23:51:46 -0700475 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800476 context_.monotonic_remote_time = context_.monotonic_event_time;
477 }
Austin Schuh58646e22021-08-23 23:51:46 -0700478 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800479 context_.realtime_remote_time = context_.realtime_event_time;
480 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481 }
482
483 // Internal method for Simulation to add a message to the buffer.
484 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800485 msgs_.emplace_back(std::move(buffer));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700486 if (fell_behind_ ||
487 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
488 fell_behind_ = true;
489 // Might as well empty out all the intermediate messages now.
490 while (msgs_.size() > 1) {
491 msgs_.pop_front();
492 }
493 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 }
495
Austin Schuhac0771c2020-01-07 18:36:30 -0800496 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700497 std::shared_ptr<SimulatedMessage> msg_;
498
499 // Messages queued up but not in use.
500 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700501
502 // Whether we're currently "behind", which means a FetchNext call will fail.
503 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700504};
505
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800506class SimulatedTimerHandler : public TimerHandler,
507 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700508 public:
509 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800510 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800511 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800512 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700513
514 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800515 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700516
Austin Schuhf4b09c72021-12-08 12:04:37 -0800517 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700518
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800519 void Handle() noexcept override;
520
Austin Schuh7d87b672019-12-01 20:23:49 -0800521 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700522
Alex Perrycb7da4b2019-08-28 19:35:56 -0700523 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800524 SimulatedEventLoop *simulated_event_loop_;
525 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700526 EventScheduler *scheduler_;
527 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800528
Alex Perrycb7da4b2019-08-28 19:35:56 -0700529 monotonic_clock::time_point base_;
530 monotonic_clock::duration repeat_offset_;
531};
532
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800533class SimulatedPhasedLoopHandler : public PhasedLoopHandler,
534 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535 public:
536 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800537 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538 ::std::function<void(int)> fn,
539 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800540 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800541 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542
Austin Schuhf4b09c72021-12-08 12:04:37 -0800543 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544
Austin Schuh7d87b672019-12-01 20:23:49 -0800545 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800547 void Handle() noexcept override;
548
Alex Perrycb7da4b2019-08-28 19:35:56 -0700549 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800550 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800551 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552
Austin Schuh39788ff2019-12-01 18:22:57 -0800553 EventScheduler *scheduler_;
554 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555};
556
557class SimulatedEventLoop : public EventLoop {
558 public:
559 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700560 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700561 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
562 *channels,
563 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700564 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
James Kuszmaul890c2492022-04-06 14:59:31 -0700565 pid_t tid, EventLoopOptions options)
Austin Schuh83c7f702021-01-19 22:36:29 -0800566 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800568 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700569 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700570 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800571 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700572 tid_(tid),
James Kuszmaul890c2492022-04-06 14:59:31 -0700573 startup_tracker_(std::make_shared<StartupTracker>()),
574 options_(options) {
Austin Schuh58646e22021-08-23 23:51:46 -0700575 startup_tracker_->loop = this;
576 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
577 if (startup_tracker->loop) {
578 startup_tracker->loop->Setup();
579 startup_tracker->has_setup = true;
580 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700581 });
582
583 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700584 }
Austin Schuh58646e22021-08-23 23:51:46 -0700585
Alex Perrycb7da4b2019-08-28 19:35:56 -0700586 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800587 // Trigger any remaining senders or fetchers to be cleared before destroying
588 // the event loop so the book keeping matches.
589 timing_report_sender_.reset();
590
591 // Force everything with a registered fd with epoll to be destroyed now.
592 timers_.clear();
593 phased_loops_.clear();
594 watchers_.clear();
595
Austin Schuh58646e22021-08-23 23:51:46 -0700596 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700597 if (*it == this) {
598 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700599 break;
600 }
601 }
Austin Schuh58646e22021-08-23 23:51:46 -0700602 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
603 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
604 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700605 }
606
Austin Schuh057d29f2021-08-21 23:05:15 -0700607 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700608 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
609 << monotonic_now() << " " << name_ << " set_is_running(" << running
610 << ")";
611 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700612
613 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700614 if (running) {
615 has_run_ = true;
616 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700617 }
618
Austin Schuh8fb315a2020-11-19 22:33:58 -0800619 bool has_run() const { return has_run_; }
620
Austin Schuh7d87b672019-12-01 20:23:49 -0800621 std::chrono::nanoseconds send_delay() const { return send_delay_; }
622 void set_send_delay(std::chrono::nanoseconds send_delay) {
623 send_delay_ = send_delay;
624 }
625
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800626 monotonic_clock::time_point monotonic_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800627 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628 }
629
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800630 realtime_clock::time_point realtime_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800631 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700632 }
633
Austin Schuh58646e22021-08-23 23:51:46 -0700634 distributed_clock::time_point distributed_now() {
635 return scheduler_->distributed_now();
636 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700637
Austin Schuh58646e22021-08-23 23:51:46 -0700638 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
639
640 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700641
642 void MakeRawWatcher(
643 const Channel *channel,
644 ::std::function<void(const Context &context, const void *message)>
645 watcher) override;
646
647 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800648 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800649 return NewTimer(::std::unique_ptr<TimerHandler>(
650 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700651 }
652
653 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
654 const monotonic_clock::duration interval,
655 const monotonic_clock::duration offset =
656 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800657 return NewPhasedLoop(
658 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
659 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700660 }
661
662 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800663 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700664 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800665 logging::ScopedLogRestorer prev_logger;
666 if (log_impl_) {
667 prev_logger.Swap(log_impl_);
668 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700669 ScopedMarkRealtimeRestorer rt(priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700670 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700671 on_run();
672 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700673 }
674
Austin Schuh217a9782019-12-21 23:02:50 -0800675 const Node *node() const override { return node_; }
676
James Kuszmaul3ae42262019-11-08 12:33:41 -0800677 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700678 name_ = std::string(name);
679 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800680 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700681
682 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
683
Austin Schuh39788ff2019-12-01 18:22:57 -0800684 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700685 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800686 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700687 }
688
Austin Schuh39788ff2019-12-01 18:22:57 -0800689 int priority() const override { return priority_; }
690
Brian Silverman6a54ff32020-04-28 16:41:39 -0700691 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
692 CHECK(!is_running()) << ": Cannot set affinity while running.";
693 }
694
Tyler Chatow67ddb032020-01-12 14:30:04 -0800695 void Setup() {
696 MaybeScheduleTimingReports();
697 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800698 log_sender_.Initialize(&name_,
699 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700700 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800701 }
702 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800703
Brian Silverman4f4e0612020-08-12 19:54:41 -0700704 int NumberBuffers(const Channel *channel) override;
705
Austin Schuh83c7f702021-01-19 22:36:29 -0800706 const UUID &boot_uuid() const override {
707 return node_event_loop_factory_->boot_uuid();
708 }
709
James Kuszmaul890c2492022-04-06 14:59:31 -0700710 const EventLoopOptions &options() const { return options_; }
711
Alex Perrycb7da4b2019-08-28 19:35:56 -0700712 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800713 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800714 friend class SimulatedPhasedLoopHandler;
715 friend class SimulatedWatcher;
716
Austin Schuh58646e22021-08-23 23:51:46 -0700717 // We have a condition where we register a startup handler, but then get shut
718 // down before it runs. This results in a segfault if we are lucky, and
719 // corruption otherwise. To handle that, allocate a small object which points
720 // back to us and can be freed when the function is freed. That object can
721 // then be updated when we get destroyed so setup is not called.
722 struct StartupTracker {
723 SimulatedEventLoop *loop = nullptr;
724 bool has_setup = false;
725 };
726
Austin Schuh7d87b672019-12-01 20:23:49 -0800727 void HandleEvent() {
728 while (true) {
729 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
730 break;
731 }
732
733 EventLoopEvent *event = PopEvent();
734 event->HandleEvent();
735 }
736 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800737
Austin Schuh39788ff2019-12-01 18:22:57 -0800738 pid_t GetTid() override { return tid_; }
739
Alex Perrycb7da4b2019-08-28 19:35:56 -0700740 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800741 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700742 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700743 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700744
745 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800746
747 int priority_ = 0;
748
Austin Schuh7d87b672019-12-01 20:23:49 -0800749 std::chrono::nanoseconds send_delay_;
750
Austin Schuh217a9782019-12-21 23:02:50 -0800751 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800752 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800753
754 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700755 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800756
757 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700758
759 std::shared_ptr<StartupTracker> startup_tracker_;
James Kuszmaul890c2492022-04-06 14:59:31 -0700760
761 EventLoopOptions options_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700762};
763
Austin Schuh7d87b672019-12-01 20:23:49 -0800764void SimulatedEventLoopFactory::set_send_delay(
765 std::chrono::nanoseconds send_delay) {
766 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700767 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700768 if (node) {
769 for (SimulatedEventLoop *loop : node->event_loops_) {
770 loop->set_send_delay(send_delay_);
771 }
772 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800773 }
774}
775
James Kuszmaulb67409b2022-06-20 16:25:03 -0700776void SimulatedEventLoopFactory::SetRealtimeReplayRate(double replay_rate) {
777 scheduler_scheduler_.SetReplayRate(replay_rate);
778}
779
Alex Perrycb7da4b2019-08-28 19:35:56 -0700780void SimulatedEventLoop::MakeRawWatcher(
781 const Channel *channel,
782 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800783 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800784
Austin Schuh057d29f2021-08-21 23:05:15 -0700785 std::unique_ptr<SimulatedWatcher> shm_watcher =
786 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
787 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800788
789 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700790
Austin Schuh39788ff2019-12-01 18:22:57 -0800791 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700792 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
793 << " " << name() << " MakeRawWatcher(\""
794 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800795
796 // Order of operations gets kinda wonky if we let people make watchers after
797 // running once. If someone has a valid use case, we can reconsider.
798 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700799}
800
801std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
802 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800803 TakeSender(channel);
804
Austin Schuh58646e22021-08-23 23:51:46 -0700805 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
806 << " " << name() << " MakeRawSender(\""
807 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700808 return GetSimulatedChannel(channel)->MakeRawSender(this);
809}
810
811std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
812 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800813 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800814
Austin Schuhca4828c2019-12-28 14:21:35 -0800815 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
816 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
817 << "\", \"type\": \"" << channel->type()->string_view()
818 << "\" } is not able to be fetched on this node. Check your "
819 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800820 }
821
Austin Schuh58646e22021-08-23 23:51:46 -0700822 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
823 << " " << name() << " MakeRawFetcher(\""
824 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800825 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700826}
827
828SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
829 const Channel *channel) {
830 auto it = channels_->find(SimpleChannel(channel));
831 if (it == channels_->end()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700832 it = channels_
833 ->emplace(SimpleChannel(channel),
834 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
835 channel,
836 std::chrono::nanoseconds(
837 configuration()->channel_storage_duration()),
838 scheduler_)))
839 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700840 }
841 return it->second.get();
842}
843
Brian Silverman4f4e0612020-08-12 19:54:41 -0700844int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
845 return GetSimulatedChannel(channel)->number_buffers();
846}
847
Austin Schuh7d87b672019-12-01 20:23:49 -0800848SimulatedWatcher::SimulatedWatcher(
849 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800850 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800851 std::function<void(const Context &context, const void *message)> fn)
852 : WatcherState(simulated_event_loop, channel, std::move(fn)),
853 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700854 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800855 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700856 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700857 token_(scheduler_->InvalidToken()) {
858 VLOG(1) << simulated_event_loop_->distributed_now() << " "
859 << NodeName(simulated_event_loop_->node())
860 << simulated_event_loop_->monotonic_now() << " "
861 << simulated_event_loop_->name() << " Watching "
862 << configuration::StrippedChannelToString(channel_);
863}
Austin Schuh7d87b672019-12-01 20:23:49 -0800864
865SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700866 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700867 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700868 << simulated_event_loop_->monotonic_now() << " "
869 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700870 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800871 simulated_event_loop_->RemoveEvent(&event_);
872 if (token_ != scheduler_->InvalidToken()) {
873 scheduler_->Deschedule(token_);
874 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700875 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800876}
877
Austin Schuh8fb315a2020-11-19 22:33:58 -0800878bool SimulatedWatcher::has_run() const {
879 return simulated_event_loop_->has_run();
880}
881
Austin Schuh7d87b672019-12-01 20:23:49 -0800882void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800883 monotonic_clock::time_point event_time =
884 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800885
886 // Messages are queued in order. If we are the first, add ourselves.
887 // Otherwise, don't.
888 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800889 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800890 simulated_event_loop_->AddEvent(&event_);
891
892 DoSchedule(event_time);
893 }
894
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800895 msgs_.emplace_back(std::move(message));
Austin Schuh7d87b672019-12-01 20:23:49 -0800896}
897
Austin Schuhf4b09c72021-12-08 12:04:37 -0800898void SimulatedWatcher::HandleEvent() noexcept {
Austin Schuh7d87b672019-12-01 20:23:49 -0800899 const monotonic_clock::time_point monotonic_now =
900 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700901 VLOG(1) << simulated_event_loop_->distributed_now() << " "
902 << NodeName(simulated_event_loop_->node())
903 << simulated_event_loop_->monotonic_now() << " "
904 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700905 << configuration::StrippedChannelToString(channel_);
906 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
907
Tyler Chatow67ddb032020-01-12 14:30:04 -0800908 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700909 if (simulated_event_loop_->log_impl_) {
910 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800911 }
Austin Schuhad154822019-12-27 15:45:13 -0800912 Context context = msgs_.front()->context;
913
Brian Silverman4f4e0612020-08-12 19:54:41 -0700914 if (channel_->read_method() != ReadMethod::PIN) {
915 context.buffer_index = -1;
916 }
Austin Schuhad154822019-12-27 15:45:13 -0800917 if (context.remote_queue_index == 0xffffffffu) {
918 context.remote_queue_index = context.queue_index;
919 }
Austin Schuh58646e22021-08-23 23:51:46 -0700920 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800921 context.monotonic_remote_time = context.monotonic_event_time;
922 }
Austin Schuh58646e22021-08-23 23:51:46 -0700923 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800924 context.realtime_remote_time = context.realtime_event_time;
925 }
926
Austin Schuhcc6070c2020-10-10 20:25:56 -0700927 {
928 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
929 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
930 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800931
932 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700933 if (token_ != scheduler_->InvalidToken()) {
934 scheduler_->Deschedule(token_);
935 token_ = scheduler_->InvalidToken();
936 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800937 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800938 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800939 simulated_event_loop_->AddEvent(&event_);
940
941 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800942 }
943}
944
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800945void SimulatedWatcher::Handle() noexcept {
946 DCHECK(token_ != scheduler_->InvalidToken());
947 token_ = scheduler_->InvalidToken();
948 simulated_event_loop_->HandleEvent();
949}
950
Austin Schuh7d87b672019-12-01 20:23:49 -0800951void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700952 CHECK(token_ == scheduler_->InvalidToken())
953 << ": May not schedule multiple times";
954 token_ = scheduler_->Schedule(
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800955 event_time + simulated_event_loop_->send_delay(), this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800956}
957
958void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700959 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800960 watcher->SetSimulatedChannel(this);
961 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700962}
963
964::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800965 SimulatedEventLoop *event_loop) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700966 CHECK(allow_new_senders_)
967 << ": Attempted to create a new sender on exclusive channel "
968 << configuration::StrippedChannelToString(channel_);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700969 std::optional<ExclusiveSenders> per_channel_option;
970 for (const std::pair<const aos::Channel *, ExclusiveSenders> &per_channel :
971 event_loop->options().per_channel_exclusivity) {
972 if (per_channel.first->name()->string_view() ==
973 channel_->name()->string_view() &&
974 per_channel.first->type()->string_view() ==
975 channel_->type()->string_view()) {
976 CHECK(!per_channel_option.has_value())
977 << ": Channel " << configuration::StrippedChannelToString(channel_)
978 << " listed twice in per-channel list.";
979 per_channel_option = per_channel.second;
980 }
981 }
982 if (!per_channel_option.has_value()) {
983 // This could just as easily be implemented by setting
984 // per_channel_option to the global setting when we initialize it, but
985 // then we'd lose track of whether a given channel appears twice in
986 // the list.
987 per_channel_option = event_loop->options().exclusive_senders;
988 }
989 if (per_channel_option.value() == ExclusiveSenders::kYes) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700990 CHECK_EQ(0, sender_count_)
991 << ": Attempted to add an exclusive sender on a channel with existing "
992 "senders: "
993 << configuration::StrippedChannelToString(channel_);
994 allow_new_senders_ = false;
995 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700996 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
997}
998
Austin Schuh39788ff2019-12-01 18:22:57 -0800999::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
1000 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -07001001 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -08001002 ::std::unique_ptr<SimulatedFetcher> fetcher(
1003 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -07001004 fetchers_.push_back(fetcher.get());
1005 return ::std::move(fetcher);
1006}
1007
milind1f1dca32021-07-03 13:50:07 -07001008std::optional<uint32_t> SimulatedChannel::Send(
Austin Schuh60e77942022-05-16 17:48:24 -07001009 std::shared_ptr<SimulatedMessage> message,
1010 CheckSentTooFast check_sent_too_fast) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001011 const auto now = scheduler_->monotonic_now();
1012 // Remove times that are greater than or equal to a channel_storage_duration_
1013 // ago
1014 while (!last_times_.empty() &&
1015 (now - last_times_.front() >= channel_storage_duration_)) {
1016 last_times_.pop();
1017 }
1018
1019 // Check that we are not sending messages too fast
James Kuszmaul890c2492022-04-06 14:59:31 -07001020 if (check_sent_too_fast == CheckSentTooFast::kYes &&
1021 static_cast<int>(last_times_.size()) >= queue_size()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001022 return std::nullopt;
1023 }
1024
1025 const std::optional<uint32_t> queue_index = {next_queue_index_.index()};
1026 last_times_.push(now);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001027
milind1f1dca32021-07-03 13:50:07 -07001028 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001029 // Points to the actual data depending on the size set in context. Data may
1030 // allocate more than the actual size of the message, so offset from the back
1031 // of that to get the actual start of the data.
1032 message->context.data =
1033 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -07001034
1035 DCHECK(channel()->has_schema())
1036 << ": Missing schema for channel "
1037 << configuration::StrippedChannelToString(channel());
1038 DCHECK(flatbuffers::Verify(
1039 *channel()->schema(), *channel()->schema()->root_table(),
1040 static_cast<const uint8_t *>(message->context.data),
1041 message->context.size))
1042 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
1043 << channel()->type()->c_str();
1044
Alex Perrycb7da4b2019-08-28 19:35:56 -07001045 next_queue_index_ = next_queue_index_.Increment();
1046
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001047 latest_message_ = std::move(message);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001048 for (SimulatedWatcher *watcher : watchers_) {
1049 if (watcher->has_run()) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001050 watcher->Schedule(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001051 }
1052 }
1053 for (auto &fetcher : fetchers_) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001054 fetcher->Enqueue(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001055 }
Austin Schuhad154822019-12-27 15:45:13 -08001056 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001057}
1058
1059void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
1060 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
1061}
1062
Austin Schuh8fb315a2020-11-19 22:33:58 -08001063SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
1064 SimulatedEventLoop *event_loop)
1065 : RawSender(event_loop, simulated_channel->channel()),
1066 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -07001067 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -08001068 simulated_channel_->CountSenderCreated();
1069}
1070
1071SimulatedSender::~SimulatedSender() {
1072 simulated_channel_->CountSenderDestroyed();
1073}
1074
milind1f1dca32021-07-03 13:50:07 -07001075RawSender::Error SimulatedSender::DoSend(
1076 size_t length, monotonic_clock::time_point monotonic_remote_time,
1077 realtime_clock::time_point realtime_remote_time,
1078 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001079 // The allocations in here are due to infrastructure and don't count in the
1080 // no mallocs in RT code.
1081 ScopedNotRealtime nrt;
1082
Austin Schuh58646e22021-08-23 23:51:46 -07001083 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1084 << NodeName(simulated_event_loop_->node())
1085 << simulated_event_loop_->monotonic_now() << " "
1086 << simulated_event_loop_->name() << " Send "
1087 << configuration::StrippedChannelToString(channel());
1088
Austin Schuh8fb315a2020-11-19 22:33:58 -08001089 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -07001090 message_->context.monotonic_event_time =
1091 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001092 message_->context.monotonic_remote_time = monotonic_remote_time;
1093 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001094 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001095 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001096 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001097 CHECK_LE(length, message_->context.size);
1098 message_->context.size = length;
1099
Austin Schuh60e77942022-05-16 17:48:24 -07001100 const std::optional<uint32_t> optional_queue_index = simulated_channel_->Send(
1101 message_, simulated_event_loop_->options().check_sent_too_fast);
milind1f1dca32021-07-03 13:50:07 -07001102
1103 // Check that we are not sending messages too fast
1104 if (!optional_queue_index) {
1105 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1106 << NodeName(simulated_event_loop_->node())
1107 << simulated_event_loop_->monotonic_now() << " "
1108 << simulated_event_loop_->name()
1109 << "\nMessages were sent too fast:\n"
1110 << "For channel: "
1111 << configuration::CleanedChannelToString(
1112 simulated_channel_->channel())
1113 << '\n'
1114 << "Tried to send more than " << simulated_channel_->queue_size()
1115 << " (queue size) messages in the last "
1116 << std::chrono::duration<double>(
1117 simulated_channel_->channel_storage_duration())
1118 .count()
1119 << " seconds (channel storage duration)"
1120 << "\n\n";
1121 return Error::kMessagesSentTooFast;
1122 }
1123
1124 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001125 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1126 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001127
1128 // Drop the reference to the message so that we allocate a new message for
1129 // next time. Otherwise we will continue to reuse the same memory for all
1130 // messages and corrupt it.
1131 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001132 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001133}
1134
milind1f1dca32021-07-03 13:50:07 -07001135RawSender::Error SimulatedSender::DoSend(
1136 const void *msg, size_t size,
1137 monotonic_clock::time_point monotonic_remote_time,
1138 realtime_clock::time_point realtime_remote_time,
1139 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001140 CHECK_LE(size, this->size())
1141 << ": Attempting to send too big a message on "
1142 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001143
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001144 // Allocates an aligned buffer in which to copy unaligned msg.
1145 auto [span, mutable_span] = MakeSharedSpan(size);
1146 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001147
1148 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001149 // queue_index will be populated in simulated_channel_.
1150 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001151
1152 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001153 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001154}
1155
milind1f1dca32021-07-03 13:50:07 -07001156RawSender::Error SimulatedSender::DoSend(
1157 const RawSender::SharedSpan data,
1158 monotonic_clock::time_point monotonic_remote_time,
1159 realtime_clock::time_point realtime_remote_time,
1160 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001161 CHECK_LE(data->size(), this->size())
1162 << ": Attempting to send too big a message on "
1163 << configuration::CleanedChannelToString(simulated_channel_->channel());
1164
1165 // Constructs a message sharing the already allocated and aligned message
1166 // data.
1167 message_ = SimulatedMessage::Make(simulated_channel_, data);
1168
1169 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1170 remote_queue_index, source_boot_uuid);
1171}
1172
Austin Schuh39788ff2019-12-01 18:22:57 -08001173SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001174 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1175 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001176 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001177 simulated_event_loop_(simulated_event_loop),
1178 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001179 scheduler_(scheduler),
1180 token_(scheduler_->InvalidToken()) {}
1181
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001182void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
1183 monotonic_clock::duration repeat_offset) {
James Kuszmaul86e86c32022-07-21 17:39:47 -07001184 CHECK_GE(base, monotonic_clock::epoch());
Austin Schuh62288252020-11-18 23:26:04 -08001185 // The allocations in here are due to infrastructure and don't count in the no
1186 // mallocs in RT code.
1187 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001188 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001189 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001190 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001191 base_ = base;
1192 repeat_offset_ = repeat_offset;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001193 token_ = scheduler_->Schedule(std::max(base, monotonic_now), this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001194 event_.set_event_time(base_);
1195 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001196}
1197
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001198void SimulatedTimerHandler::Handle() noexcept {
1199 DCHECK(token_ != scheduler_->InvalidToken());
1200 token_ = scheduler_->InvalidToken();
1201 simulated_event_loop_->HandleEvent();
1202}
1203
Austin Schuhf4b09c72021-12-08 12:04:37 -08001204void SimulatedTimerHandler::HandleEvent() noexcept {
Austin Schuh58646e22021-08-23 23:51:46 -07001205 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001206 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001207 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1208 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1209 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001210 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001211 if (simulated_event_loop_->log_impl_) {
1212 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001213 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001214 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001215 {
1216 ScopedNotRealtime nrt;
1217 scheduler_->Deschedule(token_);
1218 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001219 token_ = scheduler_->InvalidToken();
1220 }
Austin Schuh58646e22021-08-23 23:51:46 -07001221 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001222 // Reschedule.
1223 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001224 token_ = scheduler_->Schedule(base_, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001225 event_.set_event_time(base_);
1226 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001227 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001228
Austin Schuhcc6070c2020-10-10 20:25:56 -07001229 {
1230 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1231 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
1232 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001233}
1234
Austin Schuh7d87b672019-12-01 20:23:49 -08001235void SimulatedTimerHandler::Disable() {
1236 simulated_event_loop_->RemoveEvent(&event_);
1237 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001238 {
1239 ScopedNotRealtime nrt;
1240 scheduler_->Deschedule(token_);
1241 }
Austin Schuh7d87b672019-12-01 20:23:49 -08001242 token_ = scheduler_->InvalidToken();
1243 }
1244}
1245
Austin Schuh39788ff2019-12-01 18:22:57 -08001246SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001247 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1248 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001249 const monotonic_clock::duration offset)
1250 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1251 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001252 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001253 scheduler_(scheduler),
1254 token_(scheduler_->InvalidToken()) {}
1255
Austin Schuh7d87b672019-12-01 20:23:49 -08001256SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1257 if (token_ != scheduler_->InvalidToken()) {
1258 scheduler_->Deschedule(token_);
1259 token_ = scheduler_->InvalidToken();
1260 }
1261 simulated_event_loop_->RemoveEvent(&event_);
1262}
1263
Austin Schuhf4b09c72021-12-08 12:04:37 -08001264void SimulatedPhasedLoopHandler::HandleEvent() noexcept {
Austin Schuh39788ff2019-12-01 18:22:57 -08001265 monotonic_clock::time_point monotonic_now =
1266 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001267 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1268 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001269 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001270 if (simulated_event_loop_->log_impl_) {
1271 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001272 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001273
1274 {
1275 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1276 Call([monotonic_now]() { return monotonic_now; },
1277 [this](monotonic_clock::time_point sleep_time) {
1278 Schedule(sleep_time);
1279 });
1280 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001281}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001282
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001283void SimulatedPhasedLoopHandler::Handle() noexcept {
1284 DCHECK(token_ != scheduler_->InvalidToken());
1285 token_ = scheduler_->InvalidToken();
1286 simulated_event_loop_->HandleEvent();
1287}
1288
Austin Schuh7d87b672019-12-01 20:23:49 -08001289void SimulatedPhasedLoopHandler::Schedule(
1290 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001291 // The allocations in here are due to infrastructure and don't count in the no
1292 // mallocs in RT code.
1293 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001294 if (token_ != scheduler_->InvalidToken()) {
1295 scheduler_->Deschedule(token_);
1296 token_ = scheduler_->InvalidToken();
1297 }
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001298 token_ = scheduler_->Schedule(sleep_time, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001299 event_.set_event_time(sleep_time);
1300 simulated_event_loop_->AddEvent(&event_);
1301}
1302
Alex Perrycb7da4b2019-08-28 19:35:56 -07001303SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1304 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001305 : configuration_(CHECK_NOTNULL(configuration)),
1306 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001307 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001308 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001309 node_factories_.emplace_back(
1310 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001311 }
Austin Schuh898f4972020-01-11 17:21:25 -08001312
1313 if (configuration::MultiNode(configuration)) {
1314 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1315 }
Austin Schuh15649d62019-12-28 16:36:38 -08001316}
1317
Brian Silvermane1fe2512022-08-14 23:18:50 -07001318SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {
1319 CHECK_EQ(0, exit_handle_count_)
1320 << ": All ExitHandles must be destroyed before the factory";
1321}
Alex Perrycb7da4b2019-08-28 19:35:56 -07001322
Austin Schuhac0771c2020-01-07 18:36:30 -08001323NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001324 std::string_view node) {
1325 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1326}
1327
1328NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001329 const Node *node) {
1330 auto result = std::find_if(
1331 node_factories_.begin(), node_factories_.end(),
1332 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1333 return node_factory->node() == node;
1334 });
1335
1336 CHECK(result != node_factories_.end())
1337 << ": Failed to find node " << FlatbufferToJson(node);
1338
1339 return result->get();
1340}
1341
Austin Schuh87dd3832021-01-01 23:07:31 -08001342void SimulatedEventLoopFactory::SetTimeConverter(
1343 TimeConverter *time_converter) {
1344 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1345 factory->SetTimeConverter(time_converter);
1346 }
Austin Schuh58646e22021-08-23 23:51:46 -07001347 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001348}
1349
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001350::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001351 std::string_view name, const Node *node) {
1352 if (node == nullptr) {
1353 CHECK(!configuration::MultiNode(configuration()))
1354 << ": Can't make a single node event loop in a multi-node world.";
1355 } else {
1356 CHECK(configuration::MultiNode(configuration()))
1357 << ": Can't make a multi-node event loop in a single-node world.";
1358 }
1359 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1360}
1361
Austin Schuh057d29f2021-08-21 23:05:15 -07001362NodeEventLoopFactory::NodeEventLoopFactory(
1363 EventSchedulerScheduler *scheduler_scheduler,
1364 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001365 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1366 factory_(factory),
1367 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001368 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001369 scheduler_.set_started([this]() {
1370 started_ = true;
1371 for (SimulatedEventLoop *event_loop : event_loops_) {
1372 event_loop->SetIsRunning(true);
1373 }
1374 });
Austin Schuhe33c08d2022-02-03 18:15:21 -08001375 scheduler_.set_stopped([this]() {
1376 for (SimulatedEventLoop *event_loop : event_loops_) {
1377 event_loop->SetIsRunning(false);
1378 }
1379 });
Austin Schuh58646e22021-08-23 23:51:46 -07001380 scheduler_.set_on_shutdown([this]() {
1381 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1382 << monotonic_now() << " Shutting down node.";
1383 Shutdown();
1384 ScheduleStartup();
1385 });
1386 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001387}
1388
1389NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001390 if (started_) {
1391 for (std::function<void()> &fn : on_shutdown_) {
1392 fn();
1393 }
1394
1395 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1396 << monotonic_now() << " Shutting down applications.";
1397 applications_.clear();
1398 started_ = false;
1399 }
1400
1401 if (event_loops_.size() != 0u) {
1402 for (SimulatedEventLoop *event_loop : event_loops_) {
1403 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1404 << monotonic_now() << " Event loop '" << event_loop->name()
1405 << "' failed to shut down";
1406 }
1407 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001408 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1409}
1410
Austin Schuh58646e22021-08-23 23:51:46 -07001411void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001412 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001413 << ": Can only register OnStartup handlers when not running.";
1414 on_startup_.emplace_back(std::move(fn));
1415 if (started_) {
1416 size_t on_startup_index = on_startup_.size() - 1;
1417 scheduler_.ScheduleOnStartup(
1418 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1419 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001420}
1421
Austin Schuh58646e22021-08-23 23:51:46 -07001422void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1423 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001424}
Austin Schuh057d29f2021-08-21 23:05:15 -07001425
Austin Schuh58646e22021-08-23 23:51:46 -07001426void NodeEventLoopFactory::ScheduleStartup() {
1427 scheduler_.ScheduleOnStartup([this]() {
1428 UUID next_uuid = scheduler_.boot_uuid();
1429 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001430 CHECK_EQ(boot_uuid_, UUID::Zero())
1431 << ": Boot UUID changed without restarting. Did TimeConverter "
1432 "change the boot UUID without signaling a restart, or did you "
1433 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001434 boot_uuid_ = next_uuid;
1435 }
1436 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1437 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1438 Startup();
1439 });
1440}
1441
1442void NodeEventLoopFactory::Startup() {
1443 CHECK(!started_);
1444 for (size_t i = 0; i < on_startup_.size(); ++i) {
1445 on_startup_[i]();
1446 }
1447}
1448
1449void NodeEventLoopFactory::Shutdown() {
1450 for (SimulatedEventLoop *event_loop : event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001451 CHECK(!event_loop->is_running());
Austin Schuh58646e22021-08-23 23:51:46 -07001452 }
1453
1454 CHECK(started_);
1455 started_ = false;
1456 for (std::function<void()> &fn : on_shutdown_) {
1457 fn();
1458 }
1459
1460 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1461 << monotonic_now() << " Shutting down applications.";
1462 applications_.clear();
1463
1464 if (event_loops_.size() != 0u) {
1465 for (SimulatedEventLoop *event_loop : event_loops_) {
1466 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1467 << monotonic_now() << " Event loop '" << event_loop->name()
1468 << "' failed to shut down";
1469 }
1470 }
1471 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1472 boot_uuid_ = UUID::Zero();
1473
1474 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001475}
1476
Alex Perrycb7da4b2019-08-28 19:35:56 -07001477void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001478 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001479 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001480 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1481 if (node) {
1482 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001483 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001484 }
1485 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001486 }
1487}
1488
1489void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001490 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001491 scheduler_scheduler_.Run();
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
Austin Schuh87dd3832021-01-01 23:07:31 -08001501void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001502
Brian Silvermane1fe2512022-08-14 23:18:50 -07001503std::unique_ptr<ExitHandle> SimulatedEventLoopFactory::MakeExitHandle() {
1504 return std::make_unique<SimulatedFactoryExitHandle>(this);
1505}
1506
Austin Schuh6f3babe2020-01-26 20:34:50 -08001507void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001508 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001509 bridge_->DisableForwarding(channel);
1510}
1511
Austin Schuh4c3b9702020-08-30 11:34:55 -07001512void SimulatedEventLoopFactory::DisableStatistics() {
1513 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
James Kuszmaul94ca5132022-07-19 09:11:08 -07001514 bridge_->DisableStatistics(
1515 message_bridge::SimulatedMessageBridge::DestroySenders::kNo);
1516}
1517
1518void SimulatedEventLoopFactory::PermanentlyDisableStatistics() {
1519 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1520 bridge_->DisableStatistics(
1521 message_bridge::SimulatedMessageBridge::DestroySenders::kYes);
Austin Schuh4c3b9702020-08-30 11:34:55 -07001522}
1523
Austin Schuh48205e62021-11-12 14:13:18 -08001524void SimulatedEventLoopFactory::EnableStatistics() {
1525 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1526 bridge_->EnableStatistics();
1527}
1528
Austin Schuh2928ebe2021-02-07 22:10:27 -08001529void SimulatedEventLoopFactory::SkipTimingReport() {
1530 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001531
1532 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1533 if (node) {
1534 node->SkipTimingReport();
1535 }
1536 }
1537}
1538
1539void NodeEventLoopFactory::SkipTimingReport() {
1540 for (SimulatedEventLoop *event_loop : event_loops_) {
1541 event_loop->SkipTimingReport();
1542 }
1543 skip_timing_report_ = true;
1544}
1545
1546void NodeEventLoopFactory::EnableStatistics() {
1547 CHECK(factory_->bridge_)
1548 << ": Can't enable statistics without a message bridge.";
1549 factory_->bridge_->EnableStatistics(node_);
1550}
1551
1552void NodeEventLoopFactory::DisableStatistics() {
1553 CHECK(factory_->bridge_)
1554 << ": Can't disable statistics without a message bridge.";
1555 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001556}
1557
Austin Schuh58646e22021-08-23 23:51:46 -07001558::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
James Kuszmaul890c2492022-04-06 14:59:31 -07001559 std::string_view name, EventLoopOptions options) {
Austin Schuh58646e22021-08-23 23:51:46 -07001560 CHECK(!scheduler_.is_running() || !started_)
1561 << ": Can't create an event loop while running";
1562
1563 pid_t tid = tid_;
1564 ++tid_;
1565 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1566 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
James Kuszmaul890c2492022-04-06 14:59:31 -07001567 node_, tid, options));
Austin Schuh58646e22021-08-23 23:51:46 -07001568 result->set_name(name);
1569 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001570 if (skip_timing_report_) {
1571 result->SkipTimingReport();
1572 }
Austin Schuh58646e22021-08-23 23:51:46 -07001573
1574 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1575 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
1576 return std::move(result);
1577}
1578
Austin Schuhe33c08d2022-02-03 18:15:21 -08001579void SimulatedEventLoopFactory::AllowApplicationCreationDuring(
1580 std::function<void()> fn) {
1581 scheduler_scheduler_.TemporarilyStopAndRun(std::move(fn));
1582}
1583
Austin Schuh58646e22021-08-23 23:51:46 -07001584void NodeEventLoopFactory::Disconnect(const Node *other) {
1585 factory_->bridge_->Disconnect(node_, other);
1586}
1587
1588void NodeEventLoopFactory::Connect(const Node *other) {
1589 factory_->bridge_->Connect(node_, other);
1590}
1591
Alex Perrycb7da4b2019-08-28 19:35:56 -07001592} // namespace aos