blob: c021a84071b4b0ccdeae48e9c44e18243bb0e066 [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
Alex Perrycb7da4b2019-08-28 19:35:56 -070052// Container for both a message, and the context for it for simulation. This
53// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070054struct SimulatedMessage final {
55 SimulatedMessage(const SimulatedMessage &) = delete;
56 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070057 ~SimulatedMessage();
Brian Silverman661eb8d2020-08-12 19:41:01 -070058
59 // Creates a SimulatedMessage with size bytes of storage.
60 // This is a shared_ptr so we don't have to implement refcounting or copying.
Austin Schuhe0ab4de2023-05-03 08:05:08 -070061 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel,
62 const SharedSpan data);
Brian Silverman661eb8d2020-08-12 19:41:01 -070063
Alex Perrycb7da4b2019-08-28 19:35:56 -070064 // Context for the data.
65 Context context;
66
Brian Silverman661eb8d2020-08-12 19:41:01 -070067 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070068
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070069 // Owning span to this message's data. Depending on the sender may either
70 // represent the data of just the flatbuffer, or max channel size.
Austin Schuhe0ab4de2023-05-03 08:05:08 -070071 SharedSpan data;
Alex Perrycb7da4b2019-08-28 19:35:56 -070072
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070073 // Mutable view of above data. If empty, this message is not mutable.
74 absl::Span<uint8_t> mutable_data;
Brian Silverman661eb8d2020-08-12 19:41:01 -070075
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070076 // Determines whether this message is mutable. Used for Send where the user
77 // fills out a message stored internally then gives us the size of data used.
78 bool is_mutable() const { return data->size() == mutable_data.size(); }
79
80 // Note: this should be private but make_shared requires it to be public. Use
81 // Make() above to construct.
Brian Silverman661eb8d2020-08-12 19:41:01 -070082 SimulatedMessage(SimulatedChannel *channel_in);
Alex Perrycb7da4b2019-08-28 19:35:56 -070083};
84
Brian Silverman661eb8d2020-08-12 19:41:01 -070085} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080086
Brian Silverman661eb8d2020-08-12 19:41:01 -070087// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
88// for some reason...
Austin Schuhef8f1ae2021-12-11 12:35:05 -080089class SimulatedWatcher : public WatcherState, public EventScheduler::Event {
Austin Schuh39788ff2019-12-01 18:22:57 -080090 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080091 SimulatedWatcher(
92 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
93 const Channel *channel,
94 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080095
Austin Schuh7d87b672019-12-01 20:23:49 -080096 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080097
Austin Schuh8fb315a2020-11-19 22:33:58 -080098 bool has_run() const;
99
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800100 void Handle() noexcept override;
101
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 void Startup(EventLoop * /*event_loop*/) override {}
103
Austin Schuh7d87b672019-12-01 20:23:49 -0800104 void Schedule(std::shared_ptr<SimulatedMessage> message);
105
Austin Schuhf4b09c72021-12-08 12:04:37 -0800106 void HandleEvent() noexcept;
Austin Schuh39788ff2019-12-01 18:22:57 -0800107
108 void SetSimulatedChannel(SimulatedChannel *channel) {
109 simulated_channel_ = channel;
110 }
111
112 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800113 void DoSchedule(monotonic_clock::time_point event_time);
114
115 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
116
Brian Silverman4f4e0612020-08-12 19:54:41 -0700117 SimulatedEventLoop *const simulated_event_loop_;
118 const Channel *const channel_;
119 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800120 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800121 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800122 SimulatedChannel *simulated_channel_ = nullptr;
123};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700124
Brian Silvermane1fe2512022-08-14 23:18:50 -0700125class SimulatedFactoryExitHandle : public ExitHandle {
126 public:
127 SimulatedFactoryExitHandle(SimulatedEventLoopFactory *factory)
128 : factory_(factory) {
129 ++factory_->exit_handle_count_;
130 }
131 ~SimulatedFactoryExitHandle() override {
132 CHECK_GT(factory_->exit_handle_count_, 0);
133 --factory_->exit_handle_count_;
134 }
135
136 void Exit() override { factory_->Exit(); }
137
138 private:
139 SimulatedEventLoopFactory *const factory_;
140};
141
Alex Perrycb7da4b2019-08-28 19:35:56 -0700142class SimulatedChannel {
143 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800144 explicit SimulatedChannel(const Channel *channel,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700145 std::chrono::nanoseconds channel_storage_duration,
146 const EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -0800147 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700148 channel_storage_duration_(channel_storage_duration),
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700149 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())),
150 scheduler_(scheduler) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700151 available_buffer_indices_.resize(number_buffers());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700152 for (int i = 0; i < number_buffers(); ++i) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700153 available_buffer_indices_[i] = i;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700154 }
155 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700156
Brian Silverman661eb8d2020-08-12 19:41:01 -0700157 ~SimulatedChannel() {
158 latest_message_.reset();
159 CHECK_EQ(static_cast<size_t>(number_buffers()),
160 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800161 CHECK_EQ(0u, fetchers_.size())
162 << configuration::StrippedChannelToString(channel());
163 CHECK_EQ(0u, watchers_.size())
164 << configuration::StrippedChannelToString(channel());
165 CHECK_EQ(0, sender_count_)
166 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700167 }
168
169 // The number of messages we pretend to have in the queue.
170 int queue_size() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700171 return configuration::QueueSize(channel()->frequency(),
172 channel_storage_duration_);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700173 }
174
milind1f1dca32021-07-03 13:50:07 -0700175 std::chrono::nanoseconds channel_storage_duration() const {
176 return channel_storage_duration_;
177 }
178
Brian Silverman661eb8d2020-08-12 19:41:01 -0700179 // The number of extra buffers (beyond the queue) we pretend to have.
180 int number_scratch_buffers() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700181 return configuration::QueueScratchBufferSize(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700182 }
183
184 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
185
186 int GetBufferIndex() {
187 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
188 const int result = available_buffer_indices_.back();
189 available_buffer_indices_.pop_back();
190 return result;
191 }
192
193 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700194 // This extra checking has a large performance hit with sanitizers that
195 // track memory accesses, so just skip it.
196#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700197 DCHECK(std::find(available_buffer_indices_.begin(),
198 available_buffer_indices_.end(),
199 i) == available_buffer_indices_.end())
200 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800201#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700202 available_buffer_indices_.push_back(i);
203 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700204
205 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800206 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700207
208 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800209 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210
211 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800212 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800213
Austin Schuh7d87b672019-12-01 20:23:49 -0800214 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800215 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
216 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217
Austin Schuhad154822019-12-27 15:45:13 -0800218 // Sends the message to all the connected receivers and fetchers. Returns the
milind1f1dca32021-07-03 13:50:07 -0700219 // sent queue index, or std::nullopt if messages were sent too fast.
James Kuszmaul890c2492022-04-06 14:59:31 -0700220 std::optional<uint32_t> Send(std::shared_ptr<SimulatedMessage> message,
221 CheckSentTooFast check_sent_too_fast);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700222
223 // Unregisters a fetcher.
224 void UnregisterFetcher(SimulatedFetcher *fetcher);
225
226 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
227
Austin Schuh39788ff2019-12-01 18:22:57 -0800228 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700229
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800230 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800231 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700232 }
233
Austin Schuh39788ff2019-12-01 18:22:57 -0800234 const Channel *channel() const { return channel_; }
235
Austin Schuhe516ab02020-05-06 21:37:04 -0700236 void CountSenderCreated() {
237 if (sender_count_ >= channel()->num_senders()) {
238 LOG(FATAL) << "Failed to create sender on "
239 << configuration::CleanedChannelToString(channel())
240 << ", too many senders.";
241 }
Austin Schuhfb37c612022-08-11 15:24:51 -0700242 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700243 ++sender_count_;
244 }
Brian Silverman77162972020-08-12 19:52:40 -0700245
Austin Schuhe516ab02020-05-06 21:37:04 -0700246 void CountSenderDestroyed() {
247 --sender_count_;
248 CHECK_GE(sender_count_, 0);
James Kuszmaul890c2492022-04-06 14:59:31 -0700249 if (sender_count_ == 0) {
250 allow_new_senders_ = true;
251 }
Austin Schuhe516ab02020-05-06 21:37:04 -0700252 }
253
Alex Perrycb7da4b2019-08-28 19:35:56 -0700254 private:
Brian Silverman77162972020-08-12 19:52:40 -0700255 void CheckBufferCount() {
256 int reader_count = 0;
257 if (channel()->read_method() == ReadMethod::PIN) {
258 reader_count = watchers_.size() + fetchers_.size();
259 }
260 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
261 }
262
263 void CheckReaderCount() {
264 if (channel()->read_method() != ReadMethod::PIN) {
265 return;
266 }
267 CheckBufferCount();
268 const int reader_count = watchers_.size() + fetchers_.size();
269 if (reader_count >= channel()->num_readers()) {
270 LOG(FATAL) << "Failed to create reader on "
271 << configuration::CleanedChannelToString(channel())
272 << ", too many readers.";
273 }
274 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700275
276 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700277 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700278
279 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800280 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281
282 // List of all fetchers.
283 ::std::vector<SimulatedFetcher *> fetchers_;
284 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285
286 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700287
288 int sender_count_ = 0;
James Kuszmaul890c2492022-04-06 14:59:31 -0700289 // Used to track when an exclusive sender has been created (e.g., for log
290 // replay) and we want to prevent new senders from being accidentally created.
291 bool allow_new_senders_ = true;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700292
293 std::vector<uint16_t> available_buffer_indices_;
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700294
295 const EventScheduler *scheduler_;
296
297 // Queue of all the message send times in the last channel_storage_duration_
298 std::queue<monotonic_clock::time_point> last_times_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700299};
300
301namespace {
302
Brian Silverman661eb8d2020-08-12 19:41:01 -0700303std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
Austin Schuhe0ab4de2023-05-03 08:05:08 -0700304 SimulatedChannel *channel, SharedSpan data) {
Austin Schuh62288252020-11-18 23:26:04 -0800305 // The allocations in here are due to infrastructure and don't count in the no
306 // mallocs in RT code.
307 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700308
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700309 auto message = std::make_shared<SimulatedMessage>(channel);
310 message->context.size = data->size();
311 message->context.data = data->data();
312 message->data = std::move(data);
313
314 return message;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700315}
316
317SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
318 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700319 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700320}
321
322SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700323 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700324}
325
326class SimulatedSender : public RawSender {
327 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800328 SimulatedSender(SimulatedChannel *simulated_channel,
329 SimulatedEventLoop *event_loop);
330 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331
332 void *data() override {
333 if (!message_) {
Austin Schuh9b1d6282022-06-10 17:03:21 -0700334 // This API is safe to use in a RT context on a RT system. So annotate it
335 // accordingly.
336 ScopedNotRealtime nrt;
337
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700338 auto [span, mutable_span] =
339 MakeSharedSpan(simulated_channel_->max_size());
340 message_ = SimulatedMessage::Make(simulated_channel_, span);
341 message_->mutable_data = mutable_span;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700342 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700343 CHECK(message_->is_mutable());
344 return message_->mutable_data.data();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 }
346
347 size_t size() override { return simulated_channel_->max_size(); }
348
milind1f1dca32021-07-03 13:50:07 -0700349 Error DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
350 realtime_clock::time_point realtime_remote_time,
351 uint32_t remote_queue_index,
352 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700353
milind1f1dca32021-07-03 13:50:07 -0700354 Error DoSend(const void *msg, size_t size,
355 monotonic_clock::time_point monotonic_remote_time,
356 realtime_clock::time_point realtime_remote_time,
357 uint32_t remote_queue_index,
358 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700359
milind1f1dca32021-07-03 13:50:07 -0700360 Error DoSend(const SharedSpan data,
361 aos::monotonic_clock::time_point monotonic_remote_time,
362 aos::realtime_clock::time_point realtime_remote_time,
363 uint32_t remote_queue_index,
364 const UUID &source_boot_uuid) override;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700365
Brian Silverman4f4e0612020-08-12 19:54:41 -0700366 int buffer_index() override {
367 // First, ensure message_ is allocated.
368 data();
369 return message_->context.buffer_index;
370 }
371
Alex Perrycb7da4b2019-08-28 19:35:56 -0700372 private:
373 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700374 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375
376 std::shared_ptr<SimulatedMessage> message_;
377};
378} // namespace
379
380class SimulatedFetcher : public RawFetcher {
381 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800382 explicit SimulatedFetcher(EventLoop *event_loop,
383 SimulatedChannel *simulated_channel)
384 : RawFetcher(event_loop, simulated_channel->channel()),
385 simulated_channel_(simulated_channel) {}
386 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700387
Austin Schuh39788ff2019-12-01 18:22:57 -0800388 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800389 // The allocations in here are due to infrastructure and don't count in the
390 // no mallocs in RT code.
391 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800392 if (msgs_.size() == 0) {
393 return std::make_pair(false, monotonic_clock::min_time);
394 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700396 CHECK(!fell_behind_) << ": Got behind on "
397 << configuration::StrippedChannelToString(
398 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700399
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400 SetMsg(msgs_.front());
401 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800402 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403 }
404
Austin Schuh39788ff2019-12-01 18:22:57 -0800405 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800406 // The allocations in here are due to infrastructure and don't count in the
407 // no mallocs in RT code.
408 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800410 // TODO(austin): Can we just do this logic unconditionally? It is a lot
411 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800412 if (!msg_ && simulated_channel_->latest_message()) {
413 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800414 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700415 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800416 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417 }
418 }
419
420 // We've had a message enqueued, so we don't need to go looking for the
421 // latest message from before we started.
422 SetMsg(msgs_.back());
423 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700424 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800425 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426 }
427
428 private:
429 friend class SimulatedChannel;
430
431 // Updates the state inside RawFetcher to point to the data in msg_.
432 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800433 msg_ = std::move(msg);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700435 if (channel()->read_method() != ReadMethod::PIN) {
436 context_.buffer_index = -1;
437 }
Austin Schuhad154822019-12-27 15:45:13 -0800438 if (context_.remote_queue_index == 0xffffffffu) {
439 context_.remote_queue_index = context_.queue_index;
440 }
Austin Schuh58646e22021-08-23 23:51:46 -0700441 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800442 context_.monotonic_remote_time = context_.monotonic_event_time;
443 }
Austin Schuh58646e22021-08-23 23:51:46 -0700444 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800445 context_.realtime_remote_time = context_.realtime_event_time;
446 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700447 }
448
449 // Internal method for Simulation to add a message to the buffer.
450 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800451 msgs_.emplace_back(std::move(buffer));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700452 if (fell_behind_ ||
453 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
454 fell_behind_ = true;
455 // Might as well empty out all the intermediate messages now.
456 while (msgs_.size() > 1) {
457 msgs_.pop_front();
458 }
459 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460 }
461
Austin Schuhac0771c2020-01-07 18:36:30 -0800462 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700463 std::shared_ptr<SimulatedMessage> msg_;
464
465 // Messages queued up but not in use.
466 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700467
468 // Whether we're currently "behind", which means a FetchNext call will fail.
469 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470};
471
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800472class SimulatedTimerHandler : public TimerHandler,
473 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474 public:
475 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800476 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800477 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800478 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479
480 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800481 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700482
Austin Schuhf4b09c72021-12-08 12:04:37 -0800483 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700484
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800485 void Handle() noexcept override;
486
Austin Schuh7d87b672019-12-01 20:23:49 -0800487 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700488
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700489 bool IsDisabled() override;
490
Alex Perrycb7da4b2019-08-28 19:35:56 -0700491 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800492 SimulatedEventLoop *simulated_event_loop_;
493 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 EventScheduler *scheduler_;
495 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800496
Alex Perrycb7da4b2019-08-28 19:35:56 -0700497 monotonic_clock::time_point base_;
498 monotonic_clock::duration repeat_offset_;
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700499 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500};
501
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800502class SimulatedPhasedLoopHandler : public PhasedLoopHandler,
503 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700504 public:
505 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800506 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507 ::std::function<void(int)> fn,
508 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800509 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800510 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511
Austin Schuhf4b09c72021-12-08 12:04:37 -0800512 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700513
Austin Schuh7d87b672019-12-01 20:23:49 -0800514 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800516 void Handle() noexcept override;
517
Alex Perrycb7da4b2019-08-28 19:35:56 -0700518 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800519 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800520 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700521
Austin Schuh39788ff2019-12-01 18:22:57 -0800522 EventScheduler *scheduler_;
523 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700524};
525
526class SimulatedEventLoop : public EventLoop {
527 public:
528 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700529 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700530 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
531 *channels,
532 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700533 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
James Kuszmaul890c2492022-04-06 14:59:31 -0700534 pid_t tid, EventLoopOptions options)
Austin Schuh83c7f702021-01-19 22:36:29 -0800535 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700536 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800537 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700539 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800540 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700541 tid_(tid),
James Kuszmaul890c2492022-04-06 14:59:31 -0700542 startup_tracker_(std::make_shared<StartupTracker>()),
543 options_(options) {
Austin Schuh0debde12022-08-17 16:25:17 -0700544 ClearContext();
Austin Schuh58646e22021-08-23 23:51:46 -0700545 startup_tracker_->loop = this;
546 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
547 if (startup_tracker->loop) {
548 startup_tracker->loop->Setup();
549 startup_tracker->has_setup = true;
550 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700551 });
552
553 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700554 }
Austin Schuh58646e22021-08-23 23:51:46 -0700555
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800557 // Trigger any remaining senders or fetchers to be cleared before destroying
558 // the event loop so the book keeping matches.
559 timing_report_sender_.reset();
560
561 // Force everything with a registered fd with epoll to be destroyed now.
562 timers_.clear();
563 phased_loops_.clear();
564 watchers_.clear();
565
Austin Schuh58646e22021-08-23 23:51:46 -0700566 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700567 if (*it == this) {
568 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700569 break;
570 }
571 }
Austin Schuh58646e22021-08-23 23:51:46 -0700572 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
573 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
574 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700575 }
576
Austin Schuh057d29f2021-08-21 23:05:15 -0700577 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700578 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
579 << monotonic_now() << " " << name_ << " set_is_running(" << running
580 << ")";
581 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700582
583 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700584 if (running) {
585 has_run_ = true;
586 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700587 }
588
Austin Schuh8fb315a2020-11-19 22:33:58 -0800589 bool has_run() const { return has_run_; }
590
Austin Schuh7d87b672019-12-01 20:23:49 -0800591 std::chrono::nanoseconds send_delay() const { return send_delay_; }
592 void set_send_delay(std::chrono::nanoseconds send_delay) {
593 send_delay_ = send_delay;
594 }
595
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800596 monotonic_clock::time_point monotonic_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800597 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598 }
599
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800600 realtime_clock::time_point realtime_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800601 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700602 }
603
Austin Schuh58646e22021-08-23 23:51:46 -0700604 distributed_clock::time_point distributed_now() {
605 return scheduler_->distributed_now();
606 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700607
Austin Schuh58646e22021-08-23 23:51:46 -0700608 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
609
610 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700611
612 void MakeRawWatcher(
613 const Channel *channel,
614 ::std::function<void(const Context &context, const void *message)>
615 watcher) override;
616
617 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800618 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800619 return NewTimer(::std::unique_ptr<TimerHandler>(
620 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700621 }
622
623 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
624 const monotonic_clock::duration interval,
625 const monotonic_clock::duration offset =
626 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800627 return NewPhasedLoop(
628 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
629 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630 }
631
632 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800633 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700634 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800635 logging::ScopedLogRestorer prev_logger;
636 if (log_impl_) {
637 prev_logger.Swap(log_impl_);
638 }
Austin Schuh65493d62022-08-17 15:10:37 -0700639 ScopedMarkRealtimeRestorer rt(runtime_realtime_priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700640 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700641 on_run();
Austin Schuh0debde12022-08-17 16:25:17 -0700642 ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700643 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700644 }
645
Austin Schuh217a9782019-12-21 23:02:50 -0800646 const Node *node() const override { return node_; }
647
James Kuszmaul3ae42262019-11-08 12:33:41 -0800648 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700649 name_ = std::string(name);
650 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800651 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700652
653 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
654
Austin Schuh39788ff2019-12-01 18:22:57 -0800655 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700656 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800657 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700658 }
659
Austin Schuh65493d62022-08-17 15:10:37 -0700660 int runtime_realtime_priority() const override { return priority_; }
661 const cpu_set_t &runtime_affinity() const override { return affinity_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800662
Austin Schuh65493d62022-08-17 15:10:37 -0700663 void SetRuntimeAffinity(const cpu_set_t &affinity) override {
Brian Silverman6a54ff32020-04-28 16:41:39 -0700664 CHECK(!is_running()) << ": Cannot set affinity while running.";
Austin Schuh65493d62022-08-17 15:10:37 -0700665 affinity_ = affinity;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700666 }
667
Tyler Chatow67ddb032020-01-12 14:30:04 -0800668 void Setup() {
669 MaybeScheduleTimingReports();
670 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800671 log_sender_.Initialize(&name_,
672 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700673 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800674 }
675 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800676
Brian Silverman4f4e0612020-08-12 19:54:41 -0700677 int NumberBuffers(const Channel *channel) override;
678
Austin Schuh83c7f702021-01-19 22:36:29 -0800679 const UUID &boot_uuid() const override {
680 return node_event_loop_factory_->boot_uuid();
681 }
682
James Kuszmaul890c2492022-04-06 14:59:31 -0700683 const EventLoopOptions &options() const { return options_; }
684
Alex Perrycb7da4b2019-08-28 19:35:56 -0700685 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800686 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800687 friend class SimulatedPhasedLoopHandler;
688 friend class SimulatedWatcher;
689
Austin Schuh58646e22021-08-23 23:51:46 -0700690 // We have a condition where we register a startup handler, but then get shut
691 // down before it runs. This results in a segfault if we are lucky, and
692 // corruption otherwise. To handle that, allocate a small object which points
693 // back to us and can be freed when the function is freed. That object can
694 // then be updated when we get destroyed so setup is not called.
695 struct StartupTracker {
696 SimulatedEventLoop *loop = nullptr;
697 bool has_setup = false;
698 };
699
Austin Schuh7d87b672019-12-01 20:23:49 -0800700 void HandleEvent() {
701 while (true) {
702 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
703 break;
704 }
705
706 EventLoopEvent *event = PopEvent();
707 event->HandleEvent();
708 }
709 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800710
Austin Schuh39788ff2019-12-01 18:22:57 -0800711 pid_t GetTid() override { return tid_; }
712
Alex Perrycb7da4b2019-08-28 19:35:56 -0700713 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800714 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700715 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700716 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700717
718 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800719
720 int priority_ = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700721 cpu_set_t affinity_ = DefaultAffinity();
Austin Schuh39788ff2019-12-01 18:22:57 -0800722
Austin Schuh7d87b672019-12-01 20:23:49 -0800723 std::chrono::nanoseconds send_delay_;
724
Austin Schuh217a9782019-12-21 23:02:50 -0800725 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800726 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800727
728 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700729 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800730
731 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700732
733 std::shared_ptr<StartupTracker> startup_tracker_;
James Kuszmaul890c2492022-04-06 14:59:31 -0700734
735 EventLoopOptions options_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700736};
737
Austin Schuh7d87b672019-12-01 20:23:49 -0800738void SimulatedEventLoopFactory::set_send_delay(
739 std::chrono::nanoseconds send_delay) {
740 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700741 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700742 if (node) {
743 for (SimulatedEventLoop *loop : node->event_loops_) {
744 loop->set_send_delay(send_delay_);
745 }
746 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800747 }
748}
749
James Kuszmaulb67409b2022-06-20 16:25:03 -0700750void SimulatedEventLoopFactory::SetRealtimeReplayRate(double replay_rate) {
751 scheduler_scheduler_.SetReplayRate(replay_rate);
752}
753
Alex Perrycb7da4b2019-08-28 19:35:56 -0700754void SimulatedEventLoop::MakeRawWatcher(
755 const Channel *channel,
756 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800757 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800758
Austin Schuh057d29f2021-08-21 23:05:15 -0700759 std::unique_ptr<SimulatedWatcher> shm_watcher =
760 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
761 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800762
763 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700764
Austin Schuh39788ff2019-12-01 18:22:57 -0800765 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700766 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
767 << " " << name() << " MakeRawWatcher(\""
768 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800769
770 // Order of operations gets kinda wonky if we let people make watchers after
771 // running once. If someone has a valid use case, we can reconsider.
772 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700773}
774
775std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
776 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800777 TakeSender(channel);
778
Austin Schuh58646e22021-08-23 23:51:46 -0700779 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
780 << " " << name() << " MakeRawSender(\""
781 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700782 return GetSimulatedChannel(channel)->MakeRawSender(this);
783}
784
785std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
786 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800787 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800788
Austin Schuhca4828c2019-12-28 14:21:35 -0800789 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
790 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
791 << "\", \"type\": \"" << channel->type()->string_view()
792 << "\" } is not able to be fetched on this node. Check your "
793 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800794 }
795
Austin Schuh58646e22021-08-23 23:51:46 -0700796 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
797 << " " << name() << " MakeRawFetcher(\""
798 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800799 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700800}
801
802SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
803 const Channel *channel) {
804 auto it = channels_->find(SimpleChannel(channel));
805 if (it == channels_->end()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700806 it = channels_
807 ->emplace(SimpleChannel(channel),
808 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
809 channel,
810 std::chrono::nanoseconds(
811 configuration()->channel_storage_duration()),
812 scheduler_)))
813 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700814 }
815 return it->second.get();
816}
817
Brian Silverman4f4e0612020-08-12 19:54:41 -0700818int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
819 return GetSimulatedChannel(channel)->number_buffers();
820}
821
Austin Schuh7d87b672019-12-01 20:23:49 -0800822SimulatedWatcher::SimulatedWatcher(
823 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800824 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800825 std::function<void(const Context &context, const void *message)> fn)
826 : WatcherState(simulated_event_loop, channel, std::move(fn)),
827 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700828 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800829 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700830 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700831 token_(scheduler_->InvalidToken()) {
832 VLOG(1) << simulated_event_loop_->distributed_now() << " "
833 << NodeName(simulated_event_loop_->node())
834 << simulated_event_loop_->monotonic_now() << " "
835 << simulated_event_loop_->name() << " Watching "
836 << configuration::StrippedChannelToString(channel_);
837}
Austin Schuh7d87b672019-12-01 20:23:49 -0800838
839SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700840 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700841 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700842 << simulated_event_loop_->monotonic_now() << " "
843 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700844 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800845 simulated_event_loop_->RemoveEvent(&event_);
846 if (token_ != scheduler_->InvalidToken()) {
847 scheduler_->Deschedule(token_);
848 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700849 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800850}
851
Austin Schuh8fb315a2020-11-19 22:33:58 -0800852bool SimulatedWatcher::has_run() const {
853 return simulated_event_loop_->has_run();
854}
855
Austin Schuh7d87b672019-12-01 20:23:49 -0800856void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800857 monotonic_clock::time_point event_time =
858 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800859
860 // Messages are queued in order. If we are the first, add ourselves.
861 // Otherwise, don't.
862 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800863 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800864 simulated_event_loop_->AddEvent(&event_);
865
866 DoSchedule(event_time);
867 }
868
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800869 msgs_.emplace_back(std::move(message));
Austin Schuh7d87b672019-12-01 20:23:49 -0800870}
871
Austin Schuhf4b09c72021-12-08 12:04:37 -0800872void SimulatedWatcher::HandleEvent() noexcept {
Austin Schuh7d87b672019-12-01 20:23:49 -0800873 const monotonic_clock::time_point monotonic_now =
874 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700875 VLOG(1) << simulated_event_loop_->distributed_now() << " "
876 << NodeName(simulated_event_loop_->node())
877 << simulated_event_loop_->monotonic_now() << " "
878 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700879 << configuration::StrippedChannelToString(channel_);
880 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
881
Tyler Chatow67ddb032020-01-12 14:30:04 -0800882 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700883 if (simulated_event_loop_->log_impl_) {
884 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800885 }
Austin Schuhad154822019-12-27 15:45:13 -0800886 Context context = msgs_.front()->context;
887
Brian Silverman4f4e0612020-08-12 19:54:41 -0700888 if (channel_->read_method() != ReadMethod::PIN) {
889 context.buffer_index = -1;
890 }
Austin Schuhad154822019-12-27 15:45:13 -0800891 if (context.remote_queue_index == 0xffffffffu) {
892 context.remote_queue_index = context.queue_index;
893 }
Austin Schuh58646e22021-08-23 23:51:46 -0700894 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800895 context.monotonic_remote_time = context.monotonic_event_time;
896 }
Austin Schuh58646e22021-08-23 23:51:46 -0700897 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800898 context.realtime_remote_time = context.realtime_event_time;
899 }
900
Austin Schuhcc6070c2020-10-10 20:25:56 -0700901 {
Austin Schuh65493d62022-08-17 15:10:37 -0700902 ScopedMarkRealtimeRestorer rt(
903 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700904 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh0debde12022-08-17 16:25:17 -0700905 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700906 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800907
908 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700909 if (token_ != scheduler_->InvalidToken()) {
910 scheduler_->Deschedule(token_);
911 token_ = scheduler_->InvalidToken();
912 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800913 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800914 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800915 simulated_event_loop_->AddEvent(&event_);
916
917 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800918 }
919}
920
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800921void SimulatedWatcher::Handle() noexcept {
922 DCHECK(token_ != scheduler_->InvalidToken());
923 token_ = scheduler_->InvalidToken();
924 simulated_event_loop_->HandleEvent();
925}
926
Austin Schuh7d87b672019-12-01 20:23:49 -0800927void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700928 CHECK(token_ == scheduler_->InvalidToken())
929 << ": May not schedule multiple times";
930 token_ = scheduler_->Schedule(
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800931 event_time + simulated_event_loop_->send_delay(), this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800932}
933
934void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700935 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800936 watcher->SetSimulatedChannel(this);
937 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700938}
939
940::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800941 SimulatedEventLoop *event_loop) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700942 CHECK(allow_new_senders_)
943 << ": Attempted to create a new sender on exclusive channel "
944 << configuration::StrippedChannelToString(channel_);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700945 std::optional<ExclusiveSenders> per_channel_option;
946 for (const std::pair<const aos::Channel *, ExclusiveSenders> &per_channel :
947 event_loop->options().per_channel_exclusivity) {
948 if (per_channel.first->name()->string_view() ==
949 channel_->name()->string_view() &&
950 per_channel.first->type()->string_view() ==
951 channel_->type()->string_view()) {
952 CHECK(!per_channel_option.has_value())
953 << ": Channel " << configuration::StrippedChannelToString(channel_)
954 << " listed twice in per-channel list.";
955 per_channel_option = per_channel.second;
956 }
957 }
958 if (!per_channel_option.has_value()) {
959 // This could just as easily be implemented by setting
960 // per_channel_option to the global setting when we initialize it, but
961 // then we'd lose track of whether a given channel appears twice in
962 // the list.
963 per_channel_option = event_loop->options().exclusive_senders;
964 }
965 if (per_channel_option.value() == ExclusiveSenders::kYes) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700966 CHECK_EQ(0, sender_count_)
967 << ": Attempted to add an exclusive sender on a channel with existing "
968 "senders: "
969 << configuration::StrippedChannelToString(channel_);
970 allow_new_senders_ = false;
971 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700972 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
973}
974
Austin Schuh39788ff2019-12-01 18:22:57 -0800975::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
976 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700977 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800978 ::std::unique_ptr<SimulatedFetcher> fetcher(
979 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700980 fetchers_.push_back(fetcher.get());
James Kuszmaul9776b392023-01-14 14:08:08 -0800981 return fetcher;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700982}
983
milind1f1dca32021-07-03 13:50:07 -0700984std::optional<uint32_t> SimulatedChannel::Send(
Austin Schuh60e77942022-05-16 17:48:24 -0700985 std::shared_ptr<SimulatedMessage> message,
986 CheckSentTooFast check_sent_too_fast) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700987 const auto now = scheduler_->monotonic_now();
988 // Remove times that are greater than or equal to a channel_storage_duration_
989 // ago
990 while (!last_times_.empty() &&
991 (now - last_times_.front() >= channel_storage_duration_)) {
992 last_times_.pop();
993 }
994
995 // Check that we are not sending messages too fast
James Kuszmaul890c2492022-04-06 14:59:31 -0700996 if (check_sent_too_fast == CheckSentTooFast::kYes &&
997 static_cast<int>(last_times_.size()) >= queue_size()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700998 return std::nullopt;
999 }
1000
1001 const std::optional<uint32_t> queue_index = {next_queue_index_.index()};
1002 last_times_.push(now);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001003
milind1f1dca32021-07-03 13:50:07 -07001004 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001005 // Points to the actual data depending on the size set in context. Data may
1006 // allocate more than the actual size of the message, so offset from the back
1007 // of that to get the actual start of the data.
1008 message->context.data =
1009 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -07001010
1011 DCHECK(channel()->has_schema())
1012 << ": Missing schema for channel "
1013 << configuration::StrippedChannelToString(channel());
1014 DCHECK(flatbuffers::Verify(
1015 *channel()->schema(), *channel()->schema()->root_table(),
1016 static_cast<const uint8_t *>(message->context.data),
1017 message->context.size))
1018 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
1019 << channel()->type()->c_str();
1020
Alex Perrycb7da4b2019-08-28 19:35:56 -07001021 next_queue_index_ = next_queue_index_.Increment();
1022
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001023 latest_message_ = std::move(message);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001024 for (SimulatedWatcher *watcher : watchers_) {
1025 if (watcher->has_run()) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001026 watcher->Schedule(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001027 }
1028 }
1029 for (auto &fetcher : fetchers_) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001030 fetcher->Enqueue(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001031 }
Austin Schuhad154822019-12-27 15:45:13 -08001032 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001033}
1034
1035void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
1036 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
1037}
1038
Austin Schuh8fb315a2020-11-19 22:33:58 -08001039SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
1040 SimulatedEventLoop *event_loop)
1041 : RawSender(event_loop, simulated_channel->channel()),
1042 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -07001043 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -08001044 simulated_channel_->CountSenderCreated();
1045}
1046
1047SimulatedSender::~SimulatedSender() {
1048 simulated_channel_->CountSenderDestroyed();
1049}
1050
milind1f1dca32021-07-03 13:50:07 -07001051RawSender::Error SimulatedSender::DoSend(
1052 size_t length, monotonic_clock::time_point monotonic_remote_time,
1053 realtime_clock::time_point realtime_remote_time,
1054 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001055 // The allocations in here are due to infrastructure and don't count in the
1056 // no mallocs in RT code.
1057 ScopedNotRealtime nrt;
1058
Austin Schuh58646e22021-08-23 23:51:46 -07001059 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1060 << NodeName(simulated_event_loop_->node())
1061 << simulated_event_loop_->monotonic_now() << " "
1062 << simulated_event_loop_->name() << " Send "
1063 << configuration::StrippedChannelToString(channel());
1064
Austin Schuh8fb315a2020-11-19 22:33:58 -08001065 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -07001066 message_->context.monotonic_event_time =
1067 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001068 message_->context.monotonic_remote_time = monotonic_remote_time;
1069 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001070 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001071 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001072 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001073 CHECK_LE(length, message_->context.size);
1074 message_->context.size = length;
1075
Austin Schuh60e77942022-05-16 17:48:24 -07001076 const std::optional<uint32_t> optional_queue_index = simulated_channel_->Send(
1077 message_, simulated_event_loop_->options().check_sent_too_fast);
milind1f1dca32021-07-03 13:50:07 -07001078
1079 // Check that we are not sending messages too fast
1080 if (!optional_queue_index) {
1081 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1082 << NodeName(simulated_event_loop_->node())
1083 << simulated_event_loop_->monotonic_now() << " "
1084 << simulated_event_loop_->name()
1085 << "\nMessages were sent too fast:\n"
1086 << "For channel: "
1087 << configuration::CleanedChannelToString(
1088 simulated_channel_->channel())
1089 << '\n'
1090 << "Tried to send more than " << simulated_channel_->queue_size()
1091 << " (queue size) messages in the last "
1092 << std::chrono::duration<double>(
1093 simulated_channel_->channel_storage_duration())
1094 .count()
1095 << " seconds (channel storage duration)"
1096 << "\n\n";
1097 return Error::kMessagesSentTooFast;
1098 }
1099
1100 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001101 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1102 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001103
1104 // Drop the reference to the message so that we allocate a new message for
1105 // next time. Otherwise we will continue to reuse the same memory for all
1106 // messages and corrupt it.
1107 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001108 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001109}
1110
milind1f1dca32021-07-03 13:50:07 -07001111RawSender::Error SimulatedSender::DoSend(
1112 const void *msg, size_t size,
1113 monotonic_clock::time_point monotonic_remote_time,
1114 realtime_clock::time_point realtime_remote_time,
1115 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001116 CHECK_LE(size, this->size())
1117 << ": Attempting to send too big a message on "
1118 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001119
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001120 // Allocates an aligned buffer in which to copy unaligned msg.
1121 auto [span, mutable_span] = MakeSharedSpan(size);
1122 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001123
1124 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001125 // queue_index will be populated in simulated_channel_.
1126 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001127
1128 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001129 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001130}
1131
milind1f1dca32021-07-03 13:50:07 -07001132RawSender::Error SimulatedSender::DoSend(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001133 const SharedSpan data, monotonic_clock::time_point monotonic_remote_time,
milind1f1dca32021-07-03 13:50:07 -07001134 realtime_clock::time_point realtime_remote_time,
1135 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001136 CHECK_LE(data->size(), this->size())
1137 << ": Attempting to send too big a message on "
1138 << configuration::CleanedChannelToString(simulated_channel_->channel());
1139
1140 // Constructs a message sharing the already allocated and aligned message
1141 // data.
1142 message_ = SimulatedMessage::Make(simulated_channel_, data);
1143
1144 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1145 remote_queue_index, source_boot_uuid);
1146}
1147
Austin Schuh39788ff2019-12-01 18:22:57 -08001148SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001149 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1150 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001151 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001152 simulated_event_loop_(simulated_event_loop),
1153 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001154 scheduler_(scheduler),
1155 token_(scheduler_->InvalidToken()) {}
1156
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001157void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
1158 monotonic_clock::duration repeat_offset) {
James Kuszmaul86e86c32022-07-21 17:39:47 -07001159 CHECK_GE(base, monotonic_clock::epoch());
Austin Schuh62288252020-11-18 23:26:04 -08001160 // The allocations in here are due to infrastructure and don't count in the no
1161 // mallocs in RT code.
1162 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001163 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001164 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001165 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001166 base_ = base;
1167 repeat_offset_ = repeat_offset;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001168 token_ = scheduler_->Schedule(std::max(base, monotonic_now), this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001169 event_.set_event_time(base_);
1170 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001171 disabled_ = false;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001172}
1173
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001174void SimulatedTimerHandler::Handle() noexcept {
1175 DCHECK(token_ != scheduler_->InvalidToken());
1176 token_ = scheduler_->InvalidToken();
1177 simulated_event_loop_->HandleEvent();
1178}
1179
Austin Schuhf4b09c72021-12-08 12:04:37 -08001180void SimulatedTimerHandler::HandleEvent() noexcept {
Austin Schuh58646e22021-08-23 23:51:46 -07001181 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001182 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001183 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1184 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1185 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001186 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001187 if (simulated_event_loop_->log_impl_) {
1188 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001189 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001190 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001191 {
1192 ScopedNotRealtime nrt;
1193 scheduler_->Deschedule(token_);
1194 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001195 token_ = scheduler_->InvalidToken();
1196 }
Austin Schuh58646e22021-08-23 23:51:46 -07001197 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001198 // Reschedule.
1199 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001200 token_ = scheduler_->Schedule(base_, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001201 event_.set_event_time(base_);
1202 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001203 disabled_ = false;
1204 } else {
1205 disabled_ = true;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001206 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001207 {
Austin Schuh65493d62022-08-17 15:10:37 -07001208 ScopedMarkRealtimeRestorer rt(
1209 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -07001210 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuh0debde12022-08-17 16:25:17 -07001211 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001212 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001213}
1214
Austin Schuh7d87b672019-12-01 20:23:49 -08001215void SimulatedTimerHandler::Disable() {
1216 simulated_event_loop_->RemoveEvent(&event_);
1217 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001218 {
1219 ScopedNotRealtime nrt;
1220 scheduler_->Deschedule(token_);
1221 }
Austin Schuh7d87b672019-12-01 20:23:49 -08001222 token_ = scheduler_->InvalidToken();
1223 }
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001224 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -08001225}
1226
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001227bool SimulatedTimerHandler::IsDisabled() { return disabled_; }
1228
Austin Schuh39788ff2019-12-01 18:22:57 -08001229SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001230 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1231 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001232 const monotonic_clock::duration offset)
1233 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1234 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001235 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001236 scheduler_(scheduler),
1237 token_(scheduler_->InvalidToken()) {}
1238
Austin Schuh7d87b672019-12-01 20:23:49 -08001239SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1240 if (token_ != scheduler_->InvalidToken()) {
1241 scheduler_->Deschedule(token_);
1242 token_ = scheduler_->InvalidToken();
1243 }
1244 simulated_event_loop_->RemoveEvent(&event_);
1245}
1246
Austin Schuhf4b09c72021-12-08 12:04:37 -08001247void SimulatedPhasedLoopHandler::HandleEvent() noexcept {
Austin Schuh39788ff2019-12-01 18:22:57 -08001248 monotonic_clock::time_point monotonic_now =
1249 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001250 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1251 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001252 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001253 if (simulated_event_loop_->log_impl_) {
1254 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001255 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001256
1257 {
Austin Schuh65493d62022-08-17 15:10:37 -07001258 ScopedMarkRealtimeRestorer rt(
1259 simulated_event_loop_->runtime_realtime_priority() > 0);
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001260 Call([monotonic_now]() { return monotonic_now; });
Austin Schuh0debde12022-08-17 16:25:17 -07001261 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001262 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001263}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001264
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001265void SimulatedPhasedLoopHandler::Handle() noexcept {
1266 DCHECK(token_ != scheduler_->InvalidToken());
1267 token_ = scheduler_->InvalidToken();
1268 simulated_event_loop_->HandleEvent();
1269}
1270
Austin Schuh7d87b672019-12-01 20:23:49 -08001271void SimulatedPhasedLoopHandler::Schedule(
1272 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001273 // The allocations in here are due to infrastructure and don't count in the no
1274 // mallocs in RT code.
1275 ScopedNotRealtime nrt;
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001276 simulated_event_loop_->RemoveEvent(&event_);
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001277 if (token_ != scheduler_->InvalidToken()) {
1278 scheduler_->Deschedule(token_);
1279 token_ = scheduler_->InvalidToken();
1280 }
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001281 token_ = scheduler_->Schedule(sleep_time, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001282 event_.set_event_time(sleep_time);
1283 simulated_event_loop_->AddEvent(&event_);
1284}
1285
Alex Perrycb7da4b2019-08-28 19:35:56 -07001286SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1287 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001288 : configuration_(CHECK_NOTNULL(configuration)),
1289 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001290 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001291 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001292 node_factories_.emplace_back(
1293 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001294 }
Austin Schuh898f4972020-01-11 17:21:25 -08001295
1296 if (configuration::MultiNode(configuration)) {
1297 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1298 }
Austin Schuh15649d62019-12-28 16:36:38 -08001299}
1300
Brian Silvermane1fe2512022-08-14 23:18:50 -07001301SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {
1302 CHECK_EQ(0, exit_handle_count_)
1303 << ": All ExitHandles must be destroyed before the factory";
1304}
Alex Perrycb7da4b2019-08-28 19:35:56 -07001305
Austin Schuhac0771c2020-01-07 18:36:30 -08001306NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001307 std::string_view node) {
1308 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1309}
1310
1311NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001312 const Node *node) {
1313 auto result = std::find_if(
1314 node_factories_.begin(), node_factories_.end(),
1315 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1316 return node_factory->node() == node;
1317 });
1318
1319 CHECK(result != node_factories_.end())
1320 << ": Failed to find node " << FlatbufferToJson(node);
1321
1322 return result->get();
1323}
1324
Austin Schuh87dd3832021-01-01 23:07:31 -08001325void SimulatedEventLoopFactory::SetTimeConverter(
1326 TimeConverter *time_converter) {
1327 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1328 factory->SetTimeConverter(time_converter);
1329 }
Austin Schuh58646e22021-08-23 23:51:46 -07001330 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001331}
1332
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001333::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001334 std::string_view name, const Node *node) {
1335 if (node == nullptr) {
1336 CHECK(!configuration::MultiNode(configuration()))
1337 << ": Can't make a single node event loop in a multi-node world.";
1338 } else {
1339 CHECK(configuration::MultiNode(configuration()))
1340 << ": Can't make a multi-node event loop in a single-node world.";
1341 }
1342 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1343}
1344
Austin Schuh057d29f2021-08-21 23:05:15 -07001345NodeEventLoopFactory::NodeEventLoopFactory(
1346 EventSchedulerScheduler *scheduler_scheduler,
1347 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001348 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1349 factory_(factory),
1350 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001351 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001352 scheduler_.set_started([this]() {
1353 started_ = true;
1354 for (SimulatedEventLoop *event_loop : event_loops_) {
1355 event_loop->SetIsRunning(true);
1356 }
1357 });
Austin Schuhe33c08d2022-02-03 18:15:21 -08001358 scheduler_.set_stopped([this]() {
1359 for (SimulatedEventLoop *event_loop : event_loops_) {
1360 event_loop->SetIsRunning(false);
1361 }
1362 });
Austin Schuh58646e22021-08-23 23:51:46 -07001363 scheduler_.set_on_shutdown([this]() {
1364 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1365 << monotonic_now() << " Shutting down node.";
1366 Shutdown();
1367 ScheduleStartup();
1368 });
1369 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001370}
1371
1372NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001373 if (started_) {
1374 for (std::function<void()> &fn : on_shutdown_) {
1375 fn();
1376 }
1377
1378 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1379 << monotonic_now() << " Shutting down applications.";
1380 applications_.clear();
1381 started_ = false;
1382 }
1383
1384 if (event_loops_.size() != 0u) {
1385 for (SimulatedEventLoop *event_loop : event_loops_) {
1386 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1387 << monotonic_now() << " Event loop '" << event_loop->name()
1388 << "' failed to shut down";
1389 }
1390 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001391 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1392}
1393
Austin Schuh58646e22021-08-23 23:51:46 -07001394void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001395 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001396 << ": Can only register OnStartup handlers when not running.";
1397 on_startup_.emplace_back(std::move(fn));
1398 if (started_) {
1399 size_t on_startup_index = on_startup_.size() - 1;
1400 scheduler_.ScheduleOnStartup(
1401 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1402 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001403}
1404
Austin Schuh58646e22021-08-23 23:51:46 -07001405void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1406 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001407}
Austin Schuh057d29f2021-08-21 23:05:15 -07001408
Austin Schuh58646e22021-08-23 23:51:46 -07001409void NodeEventLoopFactory::ScheduleStartup() {
1410 scheduler_.ScheduleOnStartup([this]() {
1411 UUID next_uuid = scheduler_.boot_uuid();
1412 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001413 CHECK_EQ(boot_uuid_, UUID::Zero())
1414 << ": Boot UUID changed without restarting. Did TimeConverter "
1415 "change the boot UUID without signaling a restart, or did you "
1416 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001417 boot_uuid_ = next_uuid;
1418 }
1419 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1420 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1421 Startup();
1422 });
1423}
1424
1425void NodeEventLoopFactory::Startup() {
1426 CHECK(!started_);
1427 for (size_t i = 0; i < on_startup_.size(); ++i) {
1428 on_startup_[i]();
1429 }
1430}
1431
1432void NodeEventLoopFactory::Shutdown() {
1433 for (SimulatedEventLoop *event_loop : event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001434 CHECK(!event_loop->is_running());
Austin Schuh58646e22021-08-23 23:51:46 -07001435 }
1436
1437 CHECK(started_);
1438 started_ = false;
1439 for (std::function<void()> &fn : on_shutdown_) {
1440 fn();
1441 }
1442
1443 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1444 << monotonic_now() << " Shutting down applications.";
1445 applications_.clear();
1446
1447 if (event_loops_.size() != 0u) {
1448 for (SimulatedEventLoop *event_loop : event_loops_) {
1449 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1450 << monotonic_now() << " Event loop '" << event_loop->name()
1451 << "' failed to shut down";
1452 }
1453 }
1454 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1455 boot_uuid_ = UUID::Zero();
1456
1457 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001458}
1459
Alex Perrycb7da4b2019-08-28 19:35:56 -07001460void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001461 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001462 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001463 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1464 if (node) {
1465 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001466 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001467 }
1468 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001469 }
1470}
1471
1472void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001473 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001474 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001475 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1476 if (node) {
1477 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001478 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001479 }
1480 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001481 }
1482}
1483
Austin Schuh87dd3832021-01-01 23:07:31 -08001484void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001485
Brian Silvermane1fe2512022-08-14 23:18:50 -07001486std::unique_ptr<ExitHandle> SimulatedEventLoopFactory::MakeExitHandle() {
1487 return std::make_unique<SimulatedFactoryExitHandle>(this);
1488}
1489
Austin Schuh6f3babe2020-01-26 20:34:50 -08001490void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001491 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001492 bridge_->DisableForwarding(channel);
1493}
1494
Austin Schuh4c3b9702020-08-30 11:34:55 -07001495void SimulatedEventLoopFactory::DisableStatistics() {
1496 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
James Kuszmaul94ca5132022-07-19 09:11:08 -07001497 bridge_->DisableStatistics(
1498 message_bridge::SimulatedMessageBridge::DestroySenders::kNo);
1499}
1500
1501void SimulatedEventLoopFactory::PermanentlyDisableStatistics() {
1502 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1503 bridge_->DisableStatistics(
1504 message_bridge::SimulatedMessageBridge::DestroySenders::kYes);
Austin Schuh4c3b9702020-08-30 11:34:55 -07001505}
1506
Austin Schuh48205e62021-11-12 14:13:18 -08001507void SimulatedEventLoopFactory::EnableStatistics() {
1508 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1509 bridge_->EnableStatistics();
1510}
1511
Austin Schuh2928ebe2021-02-07 22:10:27 -08001512void SimulatedEventLoopFactory::SkipTimingReport() {
1513 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001514
1515 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1516 if (node) {
1517 node->SkipTimingReport();
1518 }
1519 }
1520}
1521
1522void NodeEventLoopFactory::SkipTimingReport() {
1523 for (SimulatedEventLoop *event_loop : event_loops_) {
1524 event_loop->SkipTimingReport();
1525 }
1526 skip_timing_report_ = true;
1527}
1528
1529void NodeEventLoopFactory::EnableStatistics() {
1530 CHECK(factory_->bridge_)
1531 << ": Can't enable statistics without a message bridge.";
1532 factory_->bridge_->EnableStatistics(node_);
1533}
1534
1535void NodeEventLoopFactory::DisableStatistics() {
1536 CHECK(factory_->bridge_)
1537 << ": Can't disable statistics without a message bridge.";
1538 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001539}
1540
Austin Schuh58646e22021-08-23 23:51:46 -07001541::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
James Kuszmaul890c2492022-04-06 14:59:31 -07001542 std::string_view name, EventLoopOptions options) {
Austin Schuh58646e22021-08-23 23:51:46 -07001543 CHECK(!scheduler_.is_running() || !started_)
1544 << ": Can't create an event loop while running";
1545
1546 pid_t tid = tid_;
1547 ++tid_;
1548 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1549 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
James Kuszmaul890c2492022-04-06 14:59:31 -07001550 node_, tid, options));
Austin Schuh58646e22021-08-23 23:51:46 -07001551 result->set_name(name);
1552 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001553 if (skip_timing_report_) {
1554 result->SkipTimingReport();
1555 }
Austin Schuh58646e22021-08-23 23:51:46 -07001556
1557 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1558 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
James Kuszmaul9776b392023-01-14 14:08:08 -08001559 return result;
Austin Schuh58646e22021-08-23 23:51:46 -07001560}
1561
Austin Schuhe33c08d2022-02-03 18:15:21 -08001562void SimulatedEventLoopFactory::AllowApplicationCreationDuring(
1563 std::function<void()> fn) {
1564 scheduler_scheduler_.TemporarilyStopAndRun(std::move(fn));
1565}
1566
Austin Schuh58646e22021-08-23 23:51:46 -07001567void NodeEventLoopFactory::Disconnect(const Node *other) {
1568 factory_->bridge_->Disconnect(node_, other);
1569}
1570
1571void NodeEventLoopFactory::Connect(const Node *other) {
1572 factory_->bridge_->Connect(node_, other);
1573}
1574
Alex Perrycb7da4b2019-08-28 19:35:56 -07001575} // namespace aos