blob: 7e469f5d7b53b6cb764bf312a9a499cd4b856c2e [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"
Philipp Schrader790cb542023-07-05 21:06:52 -070011
Brian Silverman661eb8d2020-08-12 19:41:01 -070012#include "aos/events/aos_logging.h"
Austin Schuh898f4972020-01-11 17:21:25 -080013#include "aos/events/simulated_network_bridge.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080014#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070015#include "aos/json_to_flatbuffer.h"
Austin Schuhcc6070c2020-10-10 20:25:56 -070016#include "aos/realtime.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070017#include "aos/util/phased_loop.h"
18
Austin Schuh9b1d6282022-06-10 17:03:21 -070019// TODO(austin): If someone runs a SimulatedEventLoop on a RT thread with
20// die_on_malloc set, it won't die. Really, we need to go RT, or fall back to
21// the base thread's original RT state to be actually accurate.
22
Alex Perrycb7da4b2019-08-28 19:35:56 -070023namespace aos {
24
Brian Silverman661eb8d2020-08-12 19:41:01 -070025class SimulatedEventLoop;
26class SimulatedFetcher;
27class SimulatedChannel;
28
James Kuszmaul890c2492022-04-06 14:59:31 -070029using CheckSentTooFast = NodeEventLoopFactory::CheckSentTooFast;
30using ExclusiveSenders = NodeEventLoopFactory::ExclusiveSenders;
31using EventLoopOptions = NodeEventLoopFactory::EventLoopOptions;
32
Brian Silverman661eb8d2020-08-12 19:41:01 -070033namespace {
34
Austin Schuh057d29f2021-08-21 23:05:15 -070035std::string NodeName(const Node *node) {
36 if (node == nullptr) {
37 return "";
38 }
39
40 return absl::StrCat(node->name()->string_view(), " ");
41}
42
Austin Schuhcc6070c2020-10-10 20:25:56 -070043class ScopedMarkRealtimeRestorer {
44 public:
45 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
46 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
47
48 private:
49 const bool rt_;
50 const bool prior_;
51};
52
Alex Perrycb7da4b2019-08-28 19:35:56 -070053// Container for both a message, and the context for it for simulation. This
54// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070055struct SimulatedMessage final {
56 SimulatedMessage(const SimulatedMessage &) = delete;
57 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070058 ~SimulatedMessage();
Brian Silverman661eb8d2020-08-12 19:41:01 -070059
60 // Creates a SimulatedMessage with size bytes of storage.
61 // This is a shared_ptr so we don't have to implement refcounting or copying.
Austin Schuhe0ab4de2023-05-03 08:05:08 -070062 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel,
63 const SharedSpan data);
Brian Silverman661eb8d2020-08-12 19:41:01 -070064
Alex Perrycb7da4b2019-08-28 19:35:56 -070065 // Context for the data.
66 Context context;
67
Brian Silverman661eb8d2020-08-12 19:41:01 -070068 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070069
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070070 // Owning span to this message's data. Depending on the sender may either
71 // represent the data of just the flatbuffer, or max channel size.
Austin Schuhe0ab4de2023-05-03 08:05:08 -070072 SharedSpan data;
Alex Perrycb7da4b2019-08-28 19:35:56 -070073
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070074 // Mutable view of above data. If empty, this message is not mutable.
75 absl::Span<uint8_t> mutable_data;
Brian Silverman661eb8d2020-08-12 19:41:01 -070076
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070077 // Determines whether this message is mutable. Used for Send where the user
78 // fills out a message stored internally then gives us the size of data used.
79 bool is_mutable() const { return data->size() == mutable_data.size(); }
80
81 // Note: this should be private but make_shared requires it to be public. Use
82 // Make() above to construct.
Brian Silverman661eb8d2020-08-12 19:41:01 -070083 SimulatedMessage(SimulatedChannel *channel_in);
Alex Perrycb7da4b2019-08-28 19:35:56 -070084};
85
Brian Silverman661eb8d2020-08-12 19:41:01 -070086} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080087
Brian Silverman661eb8d2020-08-12 19:41:01 -070088// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
89// for some reason...
Austin Schuhef8f1ae2021-12-11 12:35:05 -080090class SimulatedWatcher : public WatcherState, public EventScheduler::Event {
Austin Schuh39788ff2019-12-01 18:22:57 -080091 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080092 SimulatedWatcher(
93 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
94 const Channel *channel,
95 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080096
Austin Schuh7d87b672019-12-01 20:23:49 -080097 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080098
Austin Schuh8fb315a2020-11-19 22:33:58 -080099 bool has_run() const;
100
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800101 void Handle() noexcept override;
102
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 void Startup(EventLoop * /*event_loop*/) override {}
104
Austin Schuh7d87b672019-12-01 20:23:49 -0800105 void Schedule(std::shared_ptr<SimulatedMessage> message);
106
Austin Schuhf4b09c72021-12-08 12:04:37 -0800107 void HandleEvent() noexcept;
Austin Schuh39788ff2019-12-01 18:22:57 -0800108
109 void SetSimulatedChannel(SimulatedChannel *channel) {
110 simulated_channel_ = channel;
111 }
112
113 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800114 void DoSchedule(monotonic_clock::time_point event_time);
115
116 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
117
Brian Silverman4f4e0612020-08-12 19:54:41 -0700118 SimulatedEventLoop *const simulated_event_loop_;
119 const Channel *const channel_;
120 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800121 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800122 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800123 SimulatedChannel *simulated_channel_ = nullptr;
124};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700125
Brian Silvermane1fe2512022-08-14 23:18:50 -0700126class SimulatedFactoryExitHandle : public ExitHandle {
127 public:
128 SimulatedFactoryExitHandle(SimulatedEventLoopFactory *factory)
129 : factory_(factory) {
130 ++factory_->exit_handle_count_;
131 }
132 ~SimulatedFactoryExitHandle() override {
133 CHECK_GT(factory_->exit_handle_count_, 0);
134 --factory_->exit_handle_count_;
135 }
136
137 void Exit() override { factory_->Exit(); }
138
139 private:
140 SimulatedEventLoopFactory *const factory_;
141};
142
Alex Perrycb7da4b2019-08-28 19:35:56 -0700143class SimulatedChannel {
144 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800145 explicit SimulatedChannel(const Channel *channel,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700146 std::chrono::nanoseconds channel_storage_duration,
147 const EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -0800148 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700149 channel_storage_duration_(channel_storage_duration),
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700150 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())),
151 scheduler_(scheduler) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700152 // Gut check that things fit. Configuration validation should have caught
153 // this before we get here.
154 CHECK_LT(static_cast<size_t>(number_buffers()),
155 std::numeric_limits<
156 decltype(available_buffer_indices_)::value_type>::max())
157 << configuration::CleanedChannelToString(channel);
Brian Silvermanbc596c62021-10-15 14:04:54 -0700158 available_buffer_indices_.resize(number_buffers());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700159 for (int i = 0; i < number_buffers(); ++i) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700160 available_buffer_indices_[i] = i;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700161 }
162 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163
Brian Silverman661eb8d2020-08-12 19:41:01 -0700164 ~SimulatedChannel() {
165 latest_message_.reset();
166 CHECK_EQ(static_cast<size_t>(number_buffers()),
167 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800168 CHECK_EQ(0u, fetchers_.size())
169 << configuration::StrippedChannelToString(channel());
170 CHECK_EQ(0u, watchers_.size())
171 << configuration::StrippedChannelToString(channel());
172 CHECK_EQ(0, sender_count_)
173 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700174 }
175
176 // The number of messages we pretend to have in the queue.
177 int queue_size() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700178 return configuration::QueueSize(channel()->frequency(),
179 channel_storage_duration_);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700180 }
181
milind1f1dca32021-07-03 13:50:07 -0700182 std::chrono::nanoseconds channel_storage_duration() const {
183 return channel_storage_duration_;
184 }
185
Brian Silverman661eb8d2020-08-12 19:41:01 -0700186 // The number of extra buffers (beyond the queue) we pretend to have.
187 int number_scratch_buffers() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700188 return configuration::QueueScratchBufferSize(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700189 }
190
191 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
192
193 int GetBufferIndex() {
194 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
195 const int result = available_buffer_indices_.back();
196 available_buffer_indices_.pop_back();
197 return result;
198 }
199
200 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700201 // This extra checking has a large performance hit with sanitizers that
202 // track memory accesses, so just skip it.
203#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700204 DCHECK(std::find(available_buffer_indices_.begin(),
205 available_buffer_indices_.end(),
206 i) == available_buffer_indices_.end())
207 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800208#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700209 available_buffer_indices_.push_back(i);
210 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700211
212 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800213 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700214
215 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217
218 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800219 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800220
Austin Schuh7d87b672019-12-01 20:23:49 -0800221 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800222 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
223 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700224
Austin Schuhad154822019-12-27 15:45:13 -0800225 // Sends the message to all the connected receivers and fetchers. Returns the
milind1f1dca32021-07-03 13:50:07 -0700226 // sent queue index, or std::nullopt if messages were sent too fast.
James Kuszmaul890c2492022-04-06 14:59:31 -0700227 std::optional<uint32_t> Send(std::shared_ptr<SimulatedMessage> message,
228 CheckSentTooFast check_sent_too_fast);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700229
230 // Unregisters a fetcher.
231 void UnregisterFetcher(SimulatedFetcher *fetcher);
232
233 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
234
Austin Schuh39788ff2019-12-01 18:22:57 -0800235 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700236
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800237 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800238 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700239 }
240
Austin Schuh39788ff2019-12-01 18:22:57 -0800241 const Channel *channel() const { return channel_; }
242
Austin Schuhe516ab02020-05-06 21:37:04 -0700243 void CountSenderCreated() {
244 if (sender_count_ >= channel()->num_senders()) {
245 LOG(FATAL) << "Failed to create sender on "
246 << configuration::CleanedChannelToString(channel())
247 << ", too many senders.";
248 }
Austin Schuhfb37c612022-08-11 15:24:51 -0700249 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700250 ++sender_count_;
251 }
Brian Silverman77162972020-08-12 19:52:40 -0700252
Austin Schuhe516ab02020-05-06 21:37:04 -0700253 void CountSenderDestroyed() {
254 --sender_count_;
255 CHECK_GE(sender_count_, 0);
James Kuszmaul890c2492022-04-06 14:59:31 -0700256 if (sender_count_ == 0) {
257 allow_new_senders_ = true;
258 }
Austin Schuhe516ab02020-05-06 21:37:04 -0700259 }
260
Alex Perrycb7da4b2019-08-28 19:35:56 -0700261 private:
Brian Silverman77162972020-08-12 19:52:40 -0700262 void CheckBufferCount() {
263 int reader_count = 0;
264 if (channel()->read_method() == ReadMethod::PIN) {
265 reader_count = watchers_.size() + fetchers_.size();
266 }
267 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
268 }
269
270 void CheckReaderCount() {
271 if (channel()->read_method() != ReadMethod::PIN) {
272 return;
273 }
274 CheckBufferCount();
275 const int reader_count = watchers_.size() + fetchers_.size();
276 if (reader_count >= channel()->num_readers()) {
277 LOG(FATAL) << "Failed to create reader on "
278 << configuration::CleanedChannelToString(channel())
279 << ", too many readers.";
280 }
281 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700282
283 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700284 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285
286 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800287 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700288
289 // List of all fetchers.
290 ::std::vector<SimulatedFetcher *> fetchers_;
291 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700292
293 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700294
295 int sender_count_ = 0;
James Kuszmaul890c2492022-04-06 14:59:31 -0700296 // Used to track when an exclusive sender has been created (e.g., for log
297 // replay) and we want to prevent new senders from being accidentally created.
298 bool allow_new_senders_ = true;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700299
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700300 std::vector<ipc_lib::QueueIndex::PackedIndexType> available_buffer_indices_;
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700301
302 const EventScheduler *scheduler_;
303
304 // Queue of all the message send times in the last channel_storage_duration_
305 std::queue<monotonic_clock::time_point> last_times_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700306};
307
308namespace {
309
Brian Silverman661eb8d2020-08-12 19:41:01 -0700310std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
Austin Schuhe0ab4de2023-05-03 08:05:08 -0700311 SimulatedChannel *channel, SharedSpan data) {
Austin Schuh62288252020-11-18 23:26:04 -0800312 // The allocations in here are due to infrastructure and don't count in the no
313 // mallocs in RT code.
314 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700316 auto message = std::make_shared<SimulatedMessage>(channel);
317 message->context.size = data->size();
318 message->context.data = data->data();
319 message->data = std::move(data);
320
321 return message;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700322}
323
324SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
325 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700326 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700327}
328
329SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700330 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331}
332
333class SimulatedSender : public RawSender {
334 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800335 SimulatedSender(SimulatedChannel *simulated_channel,
336 SimulatedEventLoop *event_loop);
337 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700338
339 void *data() override {
340 if (!message_) {
Austin Schuh9b1d6282022-06-10 17:03:21 -0700341 // This API is safe to use in a RT context on a RT system. So annotate it
342 // accordingly.
343 ScopedNotRealtime nrt;
344
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700345 auto [span, mutable_span] =
346 MakeSharedSpan(simulated_channel_->max_size());
347 message_ = SimulatedMessage::Make(simulated_channel_, span);
348 message_->mutable_data = mutable_span;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700349 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700350 CHECK(message_->is_mutable());
351 return message_->mutable_data.data();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700352 }
353
354 size_t size() override { return simulated_channel_->max_size(); }
355
milind1f1dca32021-07-03 13:50:07 -0700356 Error DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
357 realtime_clock::time_point realtime_remote_time,
358 uint32_t remote_queue_index,
359 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360
milind1f1dca32021-07-03 13:50:07 -0700361 Error DoSend(const void *msg, size_t size,
362 monotonic_clock::time_point monotonic_remote_time,
363 realtime_clock::time_point realtime_remote_time,
364 uint32_t remote_queue_index,
365 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366
milind1f1dca32021-07-03 13:50:07 -0700367 Error DoSend(const SharedSpan data,
368 aos::monotonic_clock::time_point monotonic_remote_time,
369 aos::realtime_clock::time_point realtime_remote_time,
370 uint32_t remote_queue_index,
371 const UUID &source_boot_uuid) override;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700372
Brian Silverman4f4e0612020-08-12 19:54:41 -0700373 int buffer_index() override {
374 // First, ensure message_ is allocated.
375 data();
376 return message_->context.buffer_index;
377 }
378
Alex Perrycb7da4b2019-08-28 19:35:56 -0700379 private:
380 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700381 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700382
383 std::shared_ptr<SimulatedMessage> message_;
384};
385} // namespace
386
387class SimulatedFetcher : public RawFetcher {
388 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800389 explicit SimulatedFetcher(EventLoop *event_loop,
390 SimulatedChannel *simulated_channel)
391 : RawFetcher(event_loop, simulated_channel->channel()),
392 simulated_channel_(simulated_channel) {}
393 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394
Austin Schuh39788ff2019-12-01 18:22:57 -0800395 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800396 // The allocations in here are due to infrastructure and don't count in the
397 // no mallocs in RT code.
398 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800399 if (msgs_.size() == 0) {
400 return std::make_pair(false, monotonic_clock::min_time);
401 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700403 CHECK(!fell_behind_) << ": Got behind on "
404 << configuration::StrippedChannelToString(
405 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700406
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407 SetMsg(msgs_.front());
408 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800409 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700410 }
411
Austin Schuh39788ff2019-12-01 18:22:57 -0800412 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800413 // The allocations in here are due to infrastructure and don't count in the
414 // no mallocs in RT code.
415 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800417 // TODO(austin): Can we just do this logic unconditionally? It is a lot
418 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800419 if (!msg_ && simulated_channel_->latest_message()) {
420 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800421 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700422 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800423 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700424 }
425 }
426
427 // We've had a message enqueued, so we don't need to go looking for the
428 // latest message from before we started.
429 SetMsg(msgs_.back());
430 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700431 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800432 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433 }
434
435 private:
436 friend class SimulatedChannel;
437
438 // Updates the state inside RawFetcher to point to the data in msg_.
439 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800440 msg_ = std::move(msg);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700441 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700442 if (channel()->read_method() != ReadMethod::PIN) {
443 context_.buffer_index = -1;
444 }
Austin Schuhad154822019-12-27 15:45:13 -0800445 if (context_.remote_queue_index == 0xffffffffu) {
446 context_.remote_queue_index = context_.queue_index;
447 }
Austin Schuh58646e22021-08-23 23:51:46 -0700448 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800449 context_.monotonic_remote_time = context_.monotonic_event_time;
450 }
Austin Schuh58646e22021-08-23 23:51:46 -0700451 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800452 context_.realtime_remote_time = context_.realtime_event_time;
453 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454 }
455
456 // Internal method for Simulation to add a message to the buffer.
457 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800458 msgs_.emplace_back(std::move(buffer));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700459 if (fell_behind_ ||
460 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
461 fell_behind_ = true;
462 // Might as well empty out all the intermediate messages now.
463 while (msgs_.size() > 1) {
464 msgs_.pop_front();
465 }
466 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467 }
468
Austin Schuhac0771c2020-01-07 18:36:30 -0800469 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470 std::shared_ptr<SimulatedMessage> msg_;
471
472 // Messages queued up but not in use.
473 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700474
475 // Whether we're currently "behind", which means a FetchNext call will fail.
476 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477};
478
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800479class SimulatedTimerHandler : public TimerHandler,
480 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481 public:
482 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800483 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800484 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800485 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700486
Philipp Schradera6712522023-07-05 20:25:11 -0700487 void Schedule(monotonic_clock::time_point base,
488 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489
Austin Schuhf4b09c72021-12-08 12:04:37 -0800490 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700491
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800492 void Handle() noexcept override;
493
Austin Schuh7d87b672019-12-01 20:23:49 -0800494 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700495
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700496 bool IsDisabled() override;
497
Alex Perrycb7da4b2019-08-28 19:35:56 -0700498 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800499 SimulatedEventLoop *simulated_event_loop_;
500 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700501 EventScheduler *scheduler_;
502 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800503
Alex Perrycb7da4b2019-08-28 19:35:56 -0700504 monotonic_clock::time_point base_;
505 monotonic_clock::duration repeat_offset_;
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700506 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507};
508
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800509class SimulatedPhasedLoopHandler : public PhasedLoopHandler,
510 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511 public:
512 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800513 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514 ::std::function<void(int)> fn,
515 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800516 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800517 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700518
Austin Schuhf4b09c72021-12-08 12:04:37 -0800519 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700520
Austin Schuh7d87b672019-12-01 20:23:49 -0800521 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700522
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800523 void Handle() noexcept override;
524
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800526 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800527 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700528
Austin Schuh39788ff2019-12-01 18:22:57 -0800529 EventScheduler *scheduler_;
530 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531};
532
533class SimulatedEventLoop : public EventLoop {
534 public:
535 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700536 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
538 *channels,
539 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700540 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
James Kuszmaul890c2492022-04-06 14:59:31 -0700541 pid_t tid, EventLoopOptions options)
Austin Schuh83c7f702021-01-19 22:36:29 -0800542 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700543 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800544 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700546 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800547 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700548 tid_(tid),
James Kuszmaul890c2492022-04-06 14:59:31 -0700549 startup_tracker_(std::make_shared<StartupTracker>()),
550 options_(options) {
Austin Schuh0debde12022-08-17 16:25:17 -0700551 ClearContext();
Austin Schuh58646e22021-08-23 23:51:46 -0700552 startup_tracker_->loop = this;
553 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
554 if (startup_tracker->loop) {
555 startup_tracker->loop->Setup();
556 startup_tracker->has_setup = true;
557 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700558 });
559
560 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700561 }
Austin Schuh58646e22021-08-23 23:51:46 -0700562
Alex Perrycb7da4b2019-08-28 19:35:56 -0700563 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800564 // Trigger any remaining senders or fetchers to be cleared before destroying
565 // the event loop so the book keeping matches.
566 timing_report_sender_.reset();
567
568 // Force everything with a registered fd with epoll to be destroyed now.
569 timers_.clear();
570 phased_loops_.clear();
571 watchers_.clear();
572
Austin Schuh58646e22021-08-23 23:51:46 -0700573 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700574 if (*it == this) {
575 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700576 break;
577 }
578 }
Austin Schuh58646e22021-08-23 23:51:46 -0700579 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
580 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
581 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700582 }
583
Austin Schuh057d29f2021-08-21 23:05:15 -0700584 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700585 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
586 << monotonic_now() << " " << name_ << " set_is_running(" << running
587 << ")";
588 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700589
590 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700591 if (running) {
592 has_run_ = true;
593 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700594 }
595
Austin Schuh8fb315a2020-11-19 22:33:58 -0800596 bool has_run() const { return has_run_; }
597
Austin Schuh7d87b672019-12-01 20:23:49 -0800598 std::chrono::nanoseconds send_delay() const { return send_delay_; }
599 void set_send_delay(std::chrono::nanoseconds send_delay) {
600 send_delay_ = send_delay;
601 }
602
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800603 monotonic_clock::time_point monotonic_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800604 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700605 }
606
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800607 realtime_clock::time_point realtime_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800608 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700609 }
610
Austin Schuh58646e22021-08-23 23:51:46 -0700611 distributed_clock::time_point distributed_now() {
612 return scheduler_->distributed_now();
613 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700614
Austin Schuh58646e22021-08-23 23:51:46 -0700615 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
616
617 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618
619 void MakeRawWatcher(
620 const Channel *channel,
621 ::std::function<void(const Context &context, const void *message)>
622 watcher) override;
623
624 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800625 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800626 return NewTimer(::std::unique_ptr<TimerHandler>(
627 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628 }
629
630 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
631 const monotonic_clock::duration interval,
632 const monotonic_clock::duration offset =
633 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800634 return NewPhasedLoop(
635 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
636 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700637 }
638
639 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800640 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700641 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800642 logging::ScopedLogRestorer prev_logger;
643 if (log_impl_) {
644 prev_logger.Swap(log_impl_);
645 }
Austin Schuh65493d62022-08-17 15:10:37 -0700646 ScopedMarkRealtimeRestorer rt(runtime_realtime_priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700647 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700648 on_run();
Austin Schuh0debde12022-08-17 16:25:17 -0700649 ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700650 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700651 }
652
Austin Schuh217a9782019-12-21 23:02:50 -0800653 const Node *node() const override { return node_; }
654
James Kuszmaul3ae42262019-11-08 12:33:41 -0800655 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700656 name_ = std::string(name);
657 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800658 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700659
660 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
661
Austin Schuh39788ff2019-12-01 18:22:57 -0800662 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700663 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800664 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700665 }
666
Austin Schuh65493d62022-08-17 15:10:37 -0700667 int runtime_realtime_priority() const override { return priority_; }
668 const cpu_set_t &runtime_affinity() const override { return affinity_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800669
Austin Schuh65493d62022-08-17 15:10:37 -0700670 void SetRuntimeAffinity(const cpu_set_t &affinity) override {
Brian Silverman6a54ff32020-04-28 16:41:39 -0700671 CHECK(!is_running()) << ": Cannot set affinity while running.";
Austin Schuh65493d62022-08-17 15:10:37 -0700672 affinity_ = affinity;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700673 }
674
Tyler Chatow67ddb032020-01-12 14:30:04 -0800675 void Setup() {
676 MaybeScheduleTimingReports();
677 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800678 log_sender_.Initialize(&name_,
679 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700680 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800681 }
682 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800683
Brian Silverman4f4e0612020-08-12 19:54:41 -0700684 int NumberBuffers(const Channel *channel) override;
685
Austin Schuh83c7f702021-01-19 22:36:29 -0800686 const UUID &boot_uuid() const override {
687 return node_event_loop_factory_->boot_uuid();
688 }
689
James Kuszmaul890c2492022-04-06 14:59:31 -0700690 const EventLoopOptions &options() const { return options_; }
691
Alex Perrycb7da4b2019-08-28 19:35:56 -0700692 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800693 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800694 friend class SimulatedPhasedLoopHandler;
695 friend class SimulatedWatcher;
696
Austin Schuh58646e22021-08-23 23:51:46 -0700697 // We have a condition where we register a startup handler, but then get shut
698 // down before it runs. This results in a segfault if we are lucky, and
699 // corruption otherwise. To handle that, allocate a small object which points
700 // back to us and can be freed when the function is freed. That object can
701 // then be updated when we get destroyed so setup is not called.
702 struct StartupTracker {
703 SimulatedEventLoop *loop = nullptr;
704 bool has_setup = false;
705 };
706
Austin Schuh7d87b672019-12-01 20:23:49 -0800707 void HandleEvent() {
708 while (true) {
709 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
710 break;
711 }
712
713 EventLoopEvent *event = PopEvent();
714 event->HandleEvent();
715 }
716 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800717
Austin Schuh39788ff2019-12-01 18:22:57 -0800718 pid_t GetTid() override { return tid_; }
719
Alex Perrycb7da4b2019-08-28 19:35:56 -0700720 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800721 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700722 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700723 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700724
725 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800726
727 int priority_ = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700728 cpu_set_t affinity_ = DefaultAffinity();
Austin Schuh39788ff2019-12-01 18:22:57 -0800729
Austin Schuh7d87b672019-12-01 20:23:49 -0800730 std::chrono::nanoseconds send_delay_;
731
Austin Schuh217a9782019-12-21 23:02:50 -0800732 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800733 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800734
735 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700736 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800737
738 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700739
740 std::shared_ptr<StartupTracker> startup_tracker_;
James Kuszmaul890c2492022-04-06 14:59:31 -0700741
742 EventLoopOptions options_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700743};
744
Austin Schuh7d87b672019-12-01 20:23:49 -0800745void SimulatedEventLoopFactory::set_send_delay(
746 std::chrono::nanoseconds send_delay) {
747 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700748 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700749 if (node) {
750 for (SimulatedEventLoop *loop : node->event_loops_) {
751 loop->set_send_delay(send_delay_);
752 }
753 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800754 }
755}
756
James Kuszmaulb67409b2022-06-20 16:25:03 -0700757void SimulatedEventLoopFactory::SetRealtimeReplayRate(double replay_rate) {
758 scheduler_scheduler_.SetReplayRate(replay_rate);
759}
760
Alex Perrycb7da4b2019-08-28 19:35:56 -0700761void SimulatedEventLoop::MakeRawWatcher(
762 const Channel *channel,
763 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800764 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800765
Austin Schuh057d29f2021-08-21 23:05:15 -0700766 std::unique_ptr<SimulatedWatcher> shm_watcher =
767 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
768 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800769
770 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700771
Austin Schuh39788ff2019-12-01 18:22:57 -0800772 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700773 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
774 << " " << name() << " MakeRawWatcher(\""
775 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800776
777 // Order of operations gets kinda wonky if we let people make watchers after
778 // running once. If someone has a valid use case, we can reconsider.
779 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700780}
781
782std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
783 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800784 TakeSender(channel);
785
Austin Schuh58646e22021-08-23 23:51:46 -0700786 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
787 << " " << name() << " MakeRawSender(\""
788 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700789 return GetSimulatedChannel(channel)->MakeRawSender(this);
790}
791
792std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
793 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800794 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800795
Austin Schuhca4828c2019-12-28 14:21:35 -0800796 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
797 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
798 << "\", \"type\": \"" << channel->type()->string_view()
799 << "\" } is not able to be fetched on this node. Check your "
800 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800801 }
802
Austin Schuh58646e22021-08-23 23:51:46 -0700803 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
804 << " " << name() << " MakeRawFetcher(\""
805 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800806 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700807}
808
809SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
810 const Channel *channel) {
811 auto it = channels_->find(SimpleChannel(channel));
812 if (it == channels_->end()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700813 it = channels_
814 ->emplace(SimpleChannel(channel),
815 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
816 channel,
Austin Schuhfff9c3a2023-06-16 18:48:23 -0700817 configuration::ChannelStorageDuration(
818 configuration(), channel),
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700819 scheduler_)))
820 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700821 }
822 return it->second.get();
823}
824
Brian Silverman4f4e0612020-08-12 19:54:41 -0700825int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
826 return GetSimulatedChannel(channel)->number_buffers();
827}
828
Austin Schuh7d87b672019-12-01 20:23:49 -0800829SimulatedWatcher::SimulatedWatcher(
830 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800831 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800832 std::function<void(const Context &context, const void *message)> fn)
833 : WatcherState(simulated_event_loop, channel, std::move(fn)),
834 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700835 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800836 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700837 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700838 token_(scheduler_->InvalidToken()) {
839 VLOG(1) << simulated_event_loop_->distributed_now() << " "
840 << NodeName(simulated_event_loop_->node())
841 << simulated_event_loop_->monotonic_now() << " "
842 << simulated_event_loop_->name() << " Watching "
843 << configuration::StrippedChannelToString(channel_);
844}
Austin Schuh7d87b672019-12-01 20:23:49 -0800845
846SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700847 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700848 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700849 << simulated_event_loop_->monotonic_now() << " "
850 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700851 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800852 simulated_event_loop_->RemoveEvent(&event_);
853 if (token_ != scheduler_->InvalidToken()) {
854 scheduler_->Deschedule(token_);
855 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700856 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800857}
858
Austin Schuh8fb315a2020-11-19 22:33:58 -0800859bool SimulatedWatcher::has_run() const {
860 return simulated_event_loop_->has_run();
861}
862
Austin Schuh7d87b672019-12-01 20:23:49 -0800863void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800864 monotonic_clock::time_point event_time =
865 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800866
867 // Messages are queued in order. If we are the first, add ourselves.
868 // Otherwise, don't.
869 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800870 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800871 simulated_event_loop_->AddEvent(&event_);
872
873 DoSchedule(event_time);
874 }
875
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800876 msgs_.emplace_back(std::move(message));
Austin Schuh7d87b672019-12-01 20:23:49 -0800877}
878
Austin Schuhf4b09c72021-12-08 12:04:37 -0800879void SimulatedWatcher::HandleEvent() noexcept {
Austin Schuh7d87b672019-12-01 20:23:49 -0800880 const monotonic_clock::time_point monotonic_now =
881 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700882 VLOG(1) << simulated_event_loop_->distributed_now() << " "
883 << NodeName(simulated_event_loop_->node())
884 << simulated_event_loop_->monotonic_now() << " "
885 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700886 << configuration::StrippedChannelToString(channel_);
887 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
888
Tyler Chatow67ddb032020-01-12 14:30:04 -0800889 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700890 if (simulated_event_loop_->log_impl_) {
891 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800892 }
Austin Schuhad154822019-12-27 15:45:13 -0800893 Context context = msgs_.front()->context;
894
Brian Silverman4f4e0612020-08-12 19:54:41 -0700895 if (channel_->read_method() != ReadMethod::PIN) {
896 context.buffer_index = -1;
897 }
Austin Schuhad154822019-12-27 15:45:13 -0800898 if (context.remote_queue_index == 0xffffffffu) {
899 context.remote_queue_index = context.queue_index;
900 }
Austin Schuh58646e22021-08-23 23:51:46 -0700901 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800902 context.monotonic_remote_time = context.monotonic_event_time;
903 }
Austin Schuh58646e22021-08-23 23:51:46 -0700904 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800905 context.realtime_remote_time = context.realtime_event_time;
906 }
907
Austin Schuhcc6070c2020-10-10 20:25:56 -0700908 {
Austin Schuh65493d62022-08-17 15:10:37 -0700909 ScopedMarkRealtimeRestorer rt(
910 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700911 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh0debde12022-08-17 16:25:17 -0700912 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700913 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800914
915 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700916 if (token_ != scheduler_->InvalidToken()) {
917 scheduler_->Deschedule(token_);
918 token_ = scheduler_->InvalidToken();
919 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800920 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800921 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800922 simulated_event_loop_->AddEvent(&event_);
923
924 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800925 }
926}
927
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800928void SimulatedWatcher::Handle() noexcept {
929 DCHECK(token_ != scheduler_->InvalidToken());
930 token_ = scheduler_->InvalidToken();
931 simulated_event_loop_->HandleEvent();
932}
933
Austin Schuh7d87b672019-12-01 20:23:49 -0800934void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700935 CHECK(token_ == scheduler_->InvalidToken())
936 << ": May not schedule multiple times";
937 token_ = scheduler_->Schedule(
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800938 event_time + simulated_event_loop_->send_delay(), this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800939}
940
941void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700942 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800943 watcher->SetSimulatedChannel(this);
944 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700945}
946
947::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800948 SimulatedEventLoop *event_loop) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700949 CHECK(allow_new_senders_)
950 << ": Attempted to create a new sender on exclusive channel "
951 << configuration::StrippedChannelToString(channel_);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700952 std::optional<ExclusiveSenders> per_channel_option;
953 for (const std::pair<const aos::Channel *, ExclusiveSenders> &per_channel :
954 event_loop->options().per_channel_exclusivity) {
955 if (per_channel.first->name()->string_view() ==
956 channel_->name()->string_view() &&
957 per_channel.first->type()->string_view() ==
958 channel_->type()->string_view()) {
959 CHECK(!per_channel_option.has_value())
960 << ": Channel " << configuration::StrippedChannelToString(channel_)
961 << " listed twice in per-channel list.";
962 per_channel_option = per_channel.second;
963 }
964 }
965 if (!per_channel_option.has_value()) {
966 // This could just as easily be implemented by setting
967 // per_channel_option to the global setting when we initialize it, but
968 // then we'd lose track of whether a given channel appears twice in
969 // the list.
970 per_channel_option = event_loop->options().exclusive_senders;
971 }
972 if (per_channel_option.value() == ExclusiveSenders::kYes) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700973 CHECK_EQ(0, sender_count_)
974 << ": Attempted to add an exclusive sender on a channel with existing "
975 "senders: "
976 << configuration::StrippedChannelToString(channel_);
977 allow_new_senders_ = false;
978 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700979 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
980}
981
Austin Schuh39788ff2019-12-01 18:22:57 -0800982::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
983 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700984 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800985 ::std::unique_ptr<SimulatedFetcher> fetcher(
986 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700987 fetchers_.push_back(fetcher.get());
James Kuszmaul9776b392023-01-14 14:08:08 -0800988 return fetcher;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700989}
990
milind1f1dca32021-07-03 13:50:07 -0700991std::optional<uint32_t> SimulatedChannel::Send(
Austin Schuh60e77942022-05-16 17:48:24 -0700992 std::shared_ptr<SimulatedMessage> message,
993 CheckSentTooFast check_sent_too_fast) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700994 const auto now = scheduler_->monotonic_now();
995 // Remove times that are greater than or equal to a channel_storage_duration_
996 // ago
997 while (!last_times_.empty() &&
998 (now - last_times_.front() >= channel_storage_duration_)) {
999 last_times_.pop();
1000 }
1001
1002 // Check that we are not sending messages too fast
James Kuszmaul890c2492022-04-06 14:59:31 -07001003 if (check_sent_too_fast == CheckSentTooFast::kYes &&
1004 static_cast<int>(last_times_.size()) >= queue_size()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001005 return std::nullopt;
1006 }
1007
1008 const std::optional<uint32_t> queue_index = {next_queue_index_.index()};
1009 last_times_.push(now);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001010
milind1f1dca32021-07-03 13:50:07 -07001011 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001012 // Points to the actual data depending on the size set in context. Data may
1013 // allocate more than the actual size of the message, so offset from the back
1014 // of that to get the actual start of the data.
1015 message->context.data =
1016 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -07001017
1018 DCHECK(channel()->has_schema())
1019 << ": Missing schema for channel "
1020 << configuration::StrippedChannelToString(channel());
1021 DCHECK(flatbuffers::Verify(
1022 *channel()->schema(), *channel()->schema()->root_table(),
1023 static_cast<const uint8_t *>(message->context.data),
1024 message->context.size))
1025 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
1026 << channel()->type()->c_str();
1027
Alex Perrycb7da4b2019-08-28 19:35:56 -07001028 next_queue_index_ = next_queue_index_.Increment();
1029
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001030 latest_message_ = std::move(message);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001031 for (SimulatedWatcher *watcher : watchers_) {
1032 if (watcher->has_run()) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001033 watcher->Schedule(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001034 }
1035 }
1036 for (auto &fetcher : fetchers_) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001037 fetcher->Enqueue(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001038 }
Austin Schuhad154822019-12-27 15:45:13 -08001039 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001040}
1041
1042void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
1043 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
1044}
1045
Austin Schuh8fb315a2020-11-19 22:33:58 -08001046SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
1047 SimulatedEventLoop *event_loop)
1048 : RawSender(event_loop, simulated_channel->channel()),
1049 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -07001050 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -08001051 simulated_channel_->CountSenderCreated();
1052}
1053
1054SimulatedSender::~SimulatedSender() {
1055 simulated_channel_->CountSenderDestroyed();
1056}
1057
milind1f1dca32021-07-03 13:50:07 -07001058RawSender::Error SimulatedSender::DoSend(
1059 size_t length, monotonic_clock::time_point monotonic_remote_time,
1060 realtime_clock::time_point realtime_remote_time,
1061 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001062 // The allocations in here are due to infrastructure and don't count in the
1063 // no mallocs in RT code.
1064 ScopedNotRealtime nrt;
1065
Austin Schuh58646e22021-08-23 23:51:46 -07001066 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1067 << NodeName(simulated_event_loop_->node())
1068 << simulated_event_loop_->monotonic_now() << " "
1069 << simulated_event_loop_->name() << " Send "
1070 << configuration::StrippedChannelToString(channel());
1071
Austin Schuh8fb315a2020-11-19 22:33:58 -08001072 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -07001073 message_->context.monotonic_event_time =
1074 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001075 message_->context.monotonic_remote_time = monotonic_remote_time;
1076 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001077 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001078 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001079 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001080 CHECK_LE(length, message_->context.size);
1081 message_->context.size = length;
1082
Austin Schuh60e77942022-05-16 17:48:24 -07001083 const std::optional<uint32_t> optional_queue_index = simulated_channel_->Send(
1084 message_, simulated_event_loop_->options().check_sent_too_fast);
milind1f1dca32021-07-03 13:50:07 -07001085
1086 // Check that we are not sending messages too fast
1087 if (!optional_queue_index) {
1088 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1089 << NodeName(simulated_event_loop_->node())
1090 << simulated_event_loop_->monotonic_now() << " "
1091 << simulated_event_loop_->name()
1092 << "\nMessages were sent too fast:\n"
1093 << "For channel: "
1094 << configuration::CleanedChannelToString(
1095 simulated_channel_->channel())
1096 << '\n'
1097 << "Tried to send more than " << simulated_channel_->queue_size()
1098 << " (queue size) messages in the last "
1099 << std::chrono::duration<double>(
1100 simulated_channel_->channel_storage_duration())
1101 .count()
1102 << " seconds (channel storage duration)"
1103 << "\n\n";
1104 return Error::kMessagesSentTooFast;
1105 }
1106
1107 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001108 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1109 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001110
1111 // Drop the reference to the message so that we allocate a new message for
1112 // next time. Otherwise we will continue to reuse the same memory for all
1113 // messages and corrupt it.
1114 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001115 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001116}
1117
milind1f1dca32021-07-03 13:50:07 -07001118RawSender::Error SimulatedSender::DoSend(
1119 const void *msg, size_t size,
1120 monotonic_clock::time_point monotonic_remote_time,
1121 realtime_clock::time_point realtime_remote_time,
1122 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001123 CHECK_LE(size, this->size())
1124 << ": Attempting to send too big a message on "
1125 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001126
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001127 // Allocates an aligned buffer in which to copy unaligned msg.
1128 auto [span, mutable_span] = MakeSharedSpan(size);
1129 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001130
1131 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001132 // queue_index will be populated in simulated_channel_.
1133 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001134
1135 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001136 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001137}
1138
milind1f1dca32021-07-03 13:50:07 -07001139RawSender::Error SimulatedSender::DoSend(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001140 const SharedSpan data, monotonic_clock::time_point monotonic_remote_time,
milind1f1dca32021-07-03 13:50:07 -07001141 realtime_clock::time_point realtime_remote_time,
1142 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001143 CHECK_LE(data->size(), this->size())
1144 << ": Attempting to send too big a message on "
1145 << configuration::CleanedChannelToString(simulated_channel_->channel());
1146
1147 // Constructs a message sharing the already allocated and aligned message
1148 // data.
1149 message_ = SimulatedMessage::Make(simulated_channel_, data);
1150
1151 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1152 remote_queue_index, source_boot_uuid);
1153}
1154
Austin Schuh39788ff2019-12-01 18:22:57 -08001155SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001156 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1157 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001158 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001159 simulated_event_loop_(simulated_event_loop),
1160 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001161 scheduler_(scheduler),
1162 token_(scheduler_->InvalidToken()) {}
1163
Philipp Schradera6712522023-07-05 20:25:11 -07001164void SimulatedTimerHandler::Schedule(monotonic_clock::time_point base,
1165 monotonic_clock::duration repeat_offset) {
James Kuszmaul86e86c32022-07-21 17:39:47 -07001166 CHECK_GE(base, monotonic_clock::epoch());
Austin Schuh62288252020-11-18 23:26:04 -08001167 // The allocations in here are due to infrastructure and don't count in the no
1168 // mallocs in RT code.
1169 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001170 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001171 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001172 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001173 base_ = base;
1174 repeat_offset_ = repeat_offset;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001175 token_ = scheduler_->Schedule(std::max(base, monotonic_now), this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001176 event_.set_event_time(base_);
1177 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001178 disabled_ = false;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001179}
1180
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001181void SimulatedTimerHandler::Handle() noexcept {
1182 DCHECK(token_ != scheduler_->InvalidToken());
1183 token_ = scheduler_->InvalidToken();
1184 simulated_event_loop_->HandleEvent();
1185}
1186
Austin Schuhf4b09c72021-12-08 12:04:37 -08001187void SimulatedTimerHandler::HandleEvent() noexcept {
Austin Schuh58646e22021-08-23 23:51:46 -07001188 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001189 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001190 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1191 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1192 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001193 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001194 if (simulated_event_loop_->log_impl_) {
1195 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001196 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001197 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001198 {
1199 ScopedNotRealtime nrt;
1200 scheduler_->Deschedule(token_);
1201 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001202 token_ = scheduler_->InvalidToken();
1203 }
Austin Schuh58646e22021-08-23 23:51:46 -07001204 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001205 // Reschedule.
1206 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001207 token_ = scheduler_->Schedule(base_, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001208 event_.set_event_time(base_);
1209 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001210 disabled_ = false;
1211 } else {
1212 disabled_ = true;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001213 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001214 {
Austin Schuh65493d62022-08-17 15:10:37 -07001215 ScopedMarkRealtimeRestorer rt(
1216 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -07001217 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuh0debde12022-08-17 16:25:17 -07001218 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001219 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001220}
1221
Austin Schuh7d87b672019-12-01 20:23:49 -08001222void SimulatedTimerHandler::Disable() {
1223 simulated_event_loop_->RemoveEvent(&event_);
1224 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001225 {
1226 ScopedNotRealtime nrt;
1227 scheduler_->Deschedule(token_);
1228 }
Austin Schuh7d87b672019-12-01 20:23:49 -08001229 token_ = scheduler_->InvalidToken();
1230 }
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001231 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -08001232}
1233
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001234bool SimulatedTimerHandler::IsDisabled() { return disabled_; }
1235
Austin Schuh39788ff2019-12-01 18:22:57 -08001236SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001237 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1238 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001239 const monotonic_clock::duration offset)
1240 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1241 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001242 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001243 scheduler_(scheduler),
1244 token_(scheduler_->InvalidToken()) {}
1245
Austin Schuh7d87b672019-12-01 20:23:49 -08001246SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1247 if (token_ != scheduler_->InvalidToken()) {
1248 scheduler_->Deschedule(token_);
1249 token_ = scheduler_->InvalidToken();
1250 }
1251 simulated_event_loop_->RemoveEvent(&event_);
1252}
1253
Austin Schuhf4b09c72021-12-08 12:04:37 -08001254void SimulatedPhasedLoopHandler::HandleEvent() noexcept {
Austin Schuh39788ff2019-12-01 18:22:57 -08001255 monotonic_clock::time_point monotonic_now =
1256 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001257 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1258 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001259 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001260 if (simulated_event_loop_->log_impl_) {
1261 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001262 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001263
1264 {
Austin Schuh65493d62022-08-17 15:10:37 -07001265 ScopedMarkRealtimeRestorer rt(
1266 simulated_event_loop_->runtime_realtime_priority() > 0);
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001267 Call([monotonic_now]() { return monotonic_now; });
Austin Schuh0debde12022-08-17 16:25:17 -07001268 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001269 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001270}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001271
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001272void SimulatedPhasedLoopHandler::Handle() noexcept {
1273 DCHECK(token_ != scheduler_->InvalidToken());
1274 token_ = scheduler_->InvalidToken();
1275 simulated_event_loop_->HandleEvent();
1276}
1277
Austin Schuh7d87b672019-12-01 20:23:49 -08001278void SimulatedPhasedLoopHandler::Schedule(
1279 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001280 // The allocations in here are due to infrastructure and don't count in the no
1281 // mallocs in RT code.
1282 ScopedNotRealtime nrt;
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001283 simulated_event_loop_->RemoveEvent(&event_);
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001284 if (token_ != scheduler_->InvalidToken()) {
1285 scheduler_->Deschedule(token_);
1286 token_ = scheduler_->InvalidToken();
1287 }
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001288 token_ = scheduler_->Schedule(sleep_time, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001289 event_.set_event_time(sleep_time);
1290 simulated_event_loop_->AddEvent(&event_);
1291}
1292
Alex Perrycb7da4b2019-08-28 19:35:56 -07001293SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1294 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001295 : configuration_(CHECK_NOTNULL(configuration)),
1296 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001297 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001298 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001299 node_factories_.emplace_back(
1300 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001301 }
Austin Schuh898f4972020-01-11 17:21:25 -08001302
1303 if (configuration::MultiNode(configuration)) {
1304 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1305 }
Austin Schuh15649d62019-12-28 16:36:38 -08001306}
1307
Brian Silvermane1fe2512022-08-14 23:18:50 -07001308SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {
1309 CHECK_EQ(0, exit_handle_count_)
1310 << ": All ExitHandles must be destroyed before the factory";
1311}
Alex Perrycb7da4b2019-08-28 19:35:56 -07001312
Austin Schuhac0771c2020-01-07 18:36:30 -08001313NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001314 std::string_view node) {
1315 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1316}
1317
1318NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001319 const Node *node) {
1320 auto result = std::find_if(
1321 node_factories_.begin(), node_factories_.end(),
1322 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1323 return node_factory->node() == node;
1324 });
1325
1326 CHECK(result != node_factories_.end())
1327 << ": Failed to find node " << FlatbufferToJson(node);
1328
1329 return result->get();
1330}
1331
Austin Schuh87dd3832021-01-01 23:07:31 -08001332void SimulatedEventLoopFactory::SetTimeConverter(
1333 TimeConverter *time_converter) {
1334 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1335 factory->SetTimeConverter(time_converter);
1336 }
Austin Schuh58646e22021-08-23 23:51:46 -07001337 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001338}
1339
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001340::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001341 std::string_view name, const Node *node) {
1342 if (node == nullptr) {
1343 CHECK(!configuration::MultiNode(configuration()))
1344 << ": Can't make a single node event loop in a multi-node world.";
1345 } else {
1346 CHECK(configuration::MultiNode(configuration()))
1347 << ": Can't make a multi-node event loop in a single-node world.";
1348 }
1349 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1350}
1351
Austin Schuh057d29f2021-08-21 23:05:15 -07001352NodeEventLoopFactory::NodeEventLoopFactory(
1353 EventSchedulerScheduler *scheduler_scheduler,
1354 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001355 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1356 factory_(factory),
1357 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001358 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001359 scheduler_.set_started([this]() {
1360 started_ = true;
1361 for (SimulatedEventLoop *event_loop : event_loops_) {
1362 event_loop->SetIsRunning(true);
1363 }
1364 });
Austin Schuhe33c08d2022-02-03 18:15:21 -08001365 scheduler_.set_stopped([this]() {
1366 for (SimulatedEventLoop *event_loop : event_loops_) {
1367 event_loop->SetIsRunning(false);
1368 }
1369 });
Austin Schuh58646e22021-08-23 23:51:46 -07001370 scheduler_.set_on_shutdown([this]() {
1371 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1372 << monotonic_now() << " Shutting down node.";
1373 Shutdown();
1374 ScheduleStartup();
1375 });
1376 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001377}
1378
1379NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001380 if (started_) {
1381 for (std::function<void()> &fn : on_shutdown_) {
1382 fn();
1383 }
1384
1385 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1386 << monotonic_now() << " Shutting down applications.";
1387 applications_.clear();
1388 started_ = false;
1389 }
1390
1391 if (event_loops_.size() != 0u) {
1392 for (SimulatedEventLoop *event_loop : event_loops_) {
1393 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1394 << monotonic_now() << " Event loop '" << event_loop->name()
1395 << "' failed to shut down";
1396 }
1397 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001398 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1399}
1400
Austin Schuh58646e22021-08-23 23:51:46 -07001401void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001402 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001403 << ": Can only register OnStartup handlers when not running.";
1404 on_startup_.emplace_back(std::move(fn));
1405 if (started_) {
1406 size_t on_startup_index = on_startup_.size() - 1;
1407 scheduler_.ScheduleOnStartup(
1408 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1409 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001410}
1411
Austin Schuh58646e22021-08-23 23:51:46 -07001412void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1413 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001414}
Austin Schuh057d29f2021-08-21 23:05:15 -07001415
Austin Schuh58646e22021-08-23 23:51:46 -07001416void NodeEventLoopFactory::ScheduleStartup() {
1417 scheduler_.ScheduleOnStartup([this]() {
1418 UUID next_uuid = scheduler_.boot_uuid();
1419 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001420 CHECK_EQ(boot_uuid_, UUID::Zero())
1421 << ": Boot UUID changed without restarting. Did TimeConverter "
1422 "change the boot UUID without signaling a restart, or did you "
1423 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001424 boot_uuid_ = next_uuid;
1425 }
1426 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1427 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1428 Startup();
1429 });
1430}
1431
1432void NodeEventLoopFactory::Startup() {
1433 CHECK(!started_);
1434 for (size_t i = 0; i < on_startup_.size(); ++i) {
1435 on_startup_[i]();
1436 }
1437}
1438
1439void NodeEventLoopFactory::Shutdown() {
1440 for (SimulatedEventLoop *event_loop : event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001441 CHECK(!event_loop->is_running());
Austin Schuh58646e22021-08-23 23:51:46 -07001442 }
1443
1444 CHECK(started_);
1445 started_ = false;
1446 for (std::function<void()> &fn : on_shutdown_) {
1447 fn();
1448 }
1449
1450 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1451 << monotonic_now() << " Shutting down applications.";
1452 applications_.clear();
1453
1454 if (event_loops_.size() != 0u) {
1455 for (SimulatedEventLoop *event_loop : event_loops_) {
1456 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1457 << monotonic_now() << " Event loop '" << event_loop->name()
1458 << "' failed to shut down";
1459 }
1460 }
1461 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1462 boot_uuid_ = UUID::Zero();
1463
1464 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001465}
1466
Alex Perrycb7da4b2019-08-28 19:35:56 -07001467void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001468 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001469 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001470 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1471 if (node) {
1472 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001473 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001474 }
1475 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001476 }
1477}
1478
1479void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001480 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001481 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001482 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1483 if (node) {
1484 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001485 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001486 }
1487 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001488 }
1489}
1490
Austin Schuh87dd3832021-01-01 23:07:31 -08001491void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001492
Brian Silvermane1fe2512022-08-14 23:18:50 -07001493std::unique_ptr<ExitHandle> SimulatedEventLoopFactory::MakeExitHandle() {
1494 return std::make_unique<SimulatedFactoryExitHandle>(this);
1495}
1496
Austin Schuh6f3babe2020-01-26 20:34:50 -08001497void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001498 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001499 bridge_->DisableForwarding(channel);
1500}
1501
Austin Schuh4c3b9702020-08-30 11:34:55 -07001502void SimulatedEventLoopFactory::DisableStatistics() {
1503 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
James Kuszmaul94ca5132022-07-19 09:11:08 -07001504 bridge_->DisableStatistics(
1505 message_bridge::SimulatedMessageBridge::DestroySenders::kNo);
1506}
1507
1508void SimulatedEventLoopFactory::PermanentlyDisableStatistics() {
1509 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1510 bridge_->DisableStatistics(
1511 message_bridge::SimulatedMessageBridge::DestroySenders::kYes);
Austin Schuh4c3b9702020-08-30 11:34:55 -07001512}
1513
Austin Schuh48205e62021-11-12 14:13:18 -08001514void SimulatedEventLoopFactory::EnableStatistics() {
1515 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1516 bridge_->EnableStatistics();
1517}
1518
Austin Schuh2928ebe2021-02-07 22:10:27 -08001519void SimulatedEventLoopFactory::SkipTimingReport() {
1520 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001521
1522 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1523 if (node) {
1524 node->SkipTimingReport();
1525 }
1526 }
1527}
1528
1529void NodeEventLoopFactory::SkipTimingReport() {
1530 for (SimulatedEventLoop *event_loop : event_loops_) {
1531 event_loop->SkipTimingReport();
1532 }
1533 skip_timing_report_ = true;
1534}
1535
1536void NodeEventLoopFactory::EnableStatistics() {
1537 CHECK(factory_->bridge_)
1538 << ": Can't enable statistics without a message bridge.";
1539 factory_->bridge_->EnableStatistics(node_);
1540}
1541
1542void NodeEventLoopFactory::DisableStatistics() {
1543 CHECK(factory_->bridge_)
1544 << ": Can't disable statistics without a message bridge.";
1545 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001546}
1547
Austin Schuh58646e22021-08-23 23:51:46 -07001548::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
James Kuszmaul890c2492022-04-06 14:59:31 -07001549 std::string_view name, EventLoopOptions options) {
Austin Schuh58646e22021-08-23 23:51:46 -07001550 CHECK(!scheduler_.is_running() || !started_)
1551 << ": Can't create an event loop while running";
1552
1553 pid_t tid = tid_;
1554 ++tid_;
1555 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1556 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
James Kuszmaul890c2492022-04-06 14:59:31 -07001557 node_, tid, options));
Austin Schuh58646e22021-08-23 23:51:46 -07001558 result->set_name(name);
1559 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001560 if (skip_timing_report_) {
1561 result->SkipTimingReport();
1562 }
Austin Schuh58646e22021-08-23 23:51:46 -07001563
1564 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1565 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
James Kuszmaul9776b392023-01-14 14:08:08 -08001566 return result;
Austin Schuh58646e22021-08-23 23:51:46 -07001567}
1568
Austin Schuhe33c08d2022-02-03 18:15:21 -08001569void SimulatedEventLoopFactory::AllowApplicationCreationDuring(
1570 std::function<void()> fn) {
1571 scheduler_scheduler_.TemporarilyStopAndRun(std::move(fn));
1572}
1573
Austin Schuh58646e22021-08-23 23:51:46 -07001574void NodeEventLoopFactory::Disconnect(const Node *other) {
1575 factory_->bridge_->Disconnect(node_, other);
1576}
1577
1578void NodeEventLoopFactory::Connect(const Node *other) {
1579 factory_->bridge_->Connect(node_, other);
1580}
1581
Alex Perrycb7da4b2019-08-28 19:35:56 -07001582} // namespace aos