blob: 7b843806dfb7253eb39c5b1a0f6457e2974a7529 [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 Schuh98ed26f2023-07-19 14:12:28 -0700396 return DoFetchNextIf(std::function<bool(const Context &context)>());
397 }
398
399 std::pair<bool, monotonic_clock::time_point> DoFetchNextIf(
400 std::function<bool(const Context &context)> fn) override {
Austin Schuh62288252020-11-18 23:26:04 -0800401 // The allocations in here are due to infrastructure and don't count in the
402 // no mallocs in RT code.
403 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800404 if (msgs_.size() == 0) {
405 return std::make_pair(false, monotonic_clock::min_time);
406 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700408 CHECK(!fell_behind_) << ": Got behind on "
409 << configuration::StrippedChannelToString(
410 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700411
Austin Schuh98ed26f2023-07-19 14:12:28 -0700412 if (fn) {
413 Context context = msgs_.front()->context;
414 context.data = nullptr;
415 context.buffer_index = -1;
416
417 if (!fn(context)) {
418 return std::make_pair(false, monotonic_clock::min_time);
419 }
420 }
421
422 SetMsg(std::move(msgs_.front()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700423 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800424 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700425 }
426
Austin Schuh39788ff2019-12-01 18:22:57 -0800427 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh98ed26f2023-07-19 14:12:28 -0700428 return DoFetchIf(std::function<bool(const Context &context)>());
429 }
430
431 std::pair<bool, monotonic_clock::time_point> DoFetchIf(
432 std::function<bool(const Context &context)> fn) override {
Austin Schuh62288252020-11-18 23:26:04 -0800433 // The allocations in here are due to infrastructure and don't count in the
434 // no mallocs in RT code.
435 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700436 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800437 // TODO(austin): Can we just do this logic unconditionally? It is a lot
438 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800439 if (!msg_ && simulated_channel_->latest_message()) {
Austin Schuh98ed26f2023-07-19 14:12:28 -0700440 std::shared_ptr<SimulatedMessage> latest_message =
441 simulated_channel_->latest_message();
442
443 if (fn) {
444 Context context = latest_message->context;
445 context.data = nullptr;
446 context.buffer_index = -1;
447
448 if (!fn(context)) {
449 return std::make_pair(false, monotonic_clock::min_time);
450 }
451 }
452 SetMsg(std::move(latest_message));
Austin Schuha5e14192020-01-06 18:02:41 -0800453 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800455 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700456 }
457 }
458
Austin Schuh98ed26f2023-07-19 14:12:28 -0700459 if (fn) {
460 Context context = msgs_.back()->context;
461 context.data = nullptr;
462 context.buffer_index = -1;
463
464 if (!fn(context)) {
465 return std::make_pair(false, monotonic_clock::min_time);
466 }
467 }
468
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 // We've had a message enqueued, so we don't need to go looking for the
470 // latest message from before we started.
471 SetMsg(msgs_.back());
472 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700473 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800474 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700475 }
476
477 private:
478 friend class SimulatedChannel;
479
480 // Updates the state inside RawFetcher to point to the data in msg_.
481 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800482 msg_ = std::move(msg);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700484 if (channel()->read_method() != ReadMethod::PIN) {
485 context_.buffer_index = -1;
486 }
Austin Schuhad154822019-12-27 15:45:13 -0800487 if (context_.remote_queue_index == 0xffffffffu) {
488 context_.remote_queue_index = context_.queue_index;
489 }
Austin Schuh58646e22021-08-23 23:51:46 -0700490 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800491 context_.monotonic_remote_time = context_.monotonic_event_time;
492 }
Austin Schuh58646e22021-08-23 23:51:46 -0700493 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800494 context_.realtime_remote_time = context_.realtime_event_time;
495 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700496 }
497
498 // Internal method for Simulation to add a message to the buffer.
499 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800500 msgs_.emplace_back(std::move(buffer));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700501 if (fell_behind_ ||
502 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
503 fell_behind_ = true;
504 // Might as well empty out all the intermediate messages now.
505 while (msgs_.size() > 1) {
506 msgs_.pop_front();
507 }
508 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509 }
510
Austin Schuhac0771c2020-01-07 18:36:30 -0800511 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512 std::shared_ptr<SimulatedMessage> msg_;
513
514 // Messages queued up but not in use.
515 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700516
517 // Whether we're currently "behind", which means a FetchNext call will fail.
518 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700519};
520
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800521class SimulatedTimerHandler : public TimerHandler,
522 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700523 public:
524 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800525 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800526 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800527 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700528
Philipp Schradera6712522023-07-05 20:25:11 -0700529 void Schedule(monotonic_clock::time_point base,
530 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531
Austin Schuhf4b09c72021-12-08 12:04:37 -0800532 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800534 void Handle() noexcept override;
535
Austin Schuh7d87b672019-12-01 20:23:49 -0800536 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700538 bool IsDisabled() override;
539
Alex Perrycb7da4b2019-08-28 19:35:56 -0700540 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800541 SimulatedEventLoop *simulated_event_loop_;
542 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700543 EventScheduler *scheduler_;
544 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800545
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546 monotonic_clock::time_point base_;
547 monotonic_clock::duration repeat_offset_;
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700548 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700549};
550
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800551class SimulatedPhasedLoopHandler : public PhasedLoopHandler,
552 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553 public:
554 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800555 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556 ::std::function<void(int)> fn,
557 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800558 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800559 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560
Austin Schuhf4b09c72021-12-08 12:04:37 -0800561 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562
Austin Schuh7d87b672019-12-01 20:23:49 -0800563 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700564
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800565 void Handle() noexcept override;
566
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800568 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800569 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570
Austin Schuh39788ff2019-12-01 18:22:57 -0800571 EventScheduler *scheduler_;
572 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700573};
574
575class SimulatedEventLoop : public EventLoop {
576 public:
577 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700578 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700579 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
580 *channels,
581 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700582 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
James Kuszmaul890c2492022-04-06 14:59:31 -0700583 pid_t tid, EventLoopOptions options)
Austin Schuh83c7f702021-01-19 22:36:29 -0800584 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700585 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800586 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700587 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700588 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800589 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700590 tid_(tid),
James Kuszmaul890c2492022-04-06 14:59:31 -0700591 startup_tracker_(std::make_shared<StartupTracker>()),
592 options_(options) {
Austin Schuh0debde12022-08-17 16:25:17 -0700593 ClearContext();
Austin Schuh58646e22021-08-23 23:51:46 -0700594 startup_tracker_->loop = this;
595 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
596 if (startup_tracker->loop) {
597 startup_tracker->loop->Setup();
598 startup_tracker->has_setup = true;
599 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700600 });
601
602 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700603 }
Austin Schuh58646e22021-08-23 23:51:46 -0700604
Alex Perrycb7da4b2019-08-28 19:35:56 -0700605 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800606 // Trigger any remaining senders or fetchers to be cleared before destroying
607 // the event loop so the book keeping matches.
608 timing_report_sender_.reset();
609
610 // Force everything with a registered fd with epoll to be destroyed now.
611 timers_.clear();
612 phased_loops_.clear();
613 watchers_.clear();
614
Austin Schuh58646e22021-08-23 23:51:46 -0700615 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700616 if (*it == this) {
617 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618 break;
619 }
620 }
Austin Schuh58646e22021-08-23 23:51:46 -0700621 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
622 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
623 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700624 }
625
Austin Schuh057d29f2021-08-21 23:05:15 -0700626 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700627 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
628 << monotonic_now() << " " << name_ << " set_is_running(" << running
629 << ")";
630 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700631
632 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700633 if (running) {
634 has_run_ = true;
635 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700636 }
637
Austin Schuh8fb315a2020-11-19 22:33:58 -0800638 bool has_run() const { return has_run_; }
639
Austin Schuh7d87b672019-12-01 20:23:49 -0800640 std::chrono::nanoseconds send_delay() const { return send_delay_; }
641 void set_send_delay(std::chrono::nanoseconds send_delay) {
642 send_delay_ = send_delay;
643 }
644
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800645 monotonic_clock::time_point monotonic_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800646 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700647 }
648
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800649 realtime_clock::time_point realtime_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800650 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700651 }
652
Austin Schuh58646e22021-08-23 23:51:46 -0700653 distributed_clock::time_point distributed_now() {
654 return scheduler_->distributed_now();
655 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700656
Austin Schuh58646e22021-08-23 23:51:46 -0700657 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
658
659 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700660
661 void MakeRawWatcher(
662 const Channel *channel,
663 ::std::function<void(const Context &context, const void *message)>
664 watcher) override;
665
666 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800667 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800668 return NewTimer(::std::unique_ptr<TimerHandler>(
669 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700670 }
671
672 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
673 const monotonic_clock::duration interval,
674 const monotonic_clock::duration offset =
675 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800676 return NewPhasedLoop(
677 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
678 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700679 }
680
681 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800682 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700683 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800684 logging::ScopedLogRestorer prev_logger;
685 if (log_impl_) {
686 prev_logger.Swap(log_impl_);
687 }
Austin Schuh65493d62022-08-17 15:10:37 -0700688 ScopedMarkRealtimeRestorer rt(runtime_realtime_priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700689 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700690 on_run();
Austin Schuh0debde12022-08-17 16:25:17 -0700691 ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700692 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700693 }
694
Austin Schuh217a9782019-12-21 23:02:50 -0800695 const Node *node() const override { return node_; }
696
James Kuszmaul3ae42262019-11-08 12:33:41 -0800697 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700698 name_ = std::string(name);
699 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800700 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700701
702 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
703
Austin Schuh39788ff2019-12-01 18:22:57 -0800704 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700705 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800706 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700707 }
708
Austin Schuh65493d62022-08-17 15:10:37 -0700709 int runtime_realtime_priority() const override { return priority_; }
710 const cpu_set_t &runtime_affinity() const override { return affinity_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800711
Austin Schuh65493d62022-08-17 15:10:37 -0700712 void SetRuntimeAffinity(const cpu_set_t &affinity) override {
Brian Silverman6a54ff32020-04-28 16:41:39 -0700713 CHECK(!is_running()) << ": Cannot set affinity while running.";
Austin Schuh65493d62022-08-17 15:10:37 -0700714 affinity_ = affinity;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700715 }
716
Tyler Chatow67ddb032020-01-12 14:30:04 -0800717 void Setup() {
718 MaybeScheduleTimingReports();
719 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800720 log_sender_.Initialize(&name_,
721 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700722 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800723 }
724 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800725
Brian Silverman4f4e0612020-08-12 19:54:41 -0700726 int NumberBuffers(const Channel *channel) override;
727
Austin Schuh83c7f702021-01-19 22:36:29 -0800728 const UUID &boot_uuid() const override {
729 return node_event_loop_factory_->boot_uuid();
730 }
731
James Kuszmaul890c2492022-04-06 14:59:31 -0700732 const EventLoopOptions &options() const { return options_; }
733
Alex Perrycb7da4b2019-08-28 19:35:56 -0700734 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800735 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800736 friend class SimulatedPhasedLoopHandler;
737 friend class SimulatedWatcher;
738
Austin Schuh58646e22021-08-23 23:51:46 -0700739 // We have a condition where we register a startup handler, but then get shut
740 // down before it runs. This results in a segfault if we are lucky, and
741 // corruption otherwise. To handle that, allocate a small object which points
742 // back to us and can be freed when the function is freed. That object can
743 // then be updated when we get destroyed so setup is not called.
744 struct StartupTracker {
745 SimulatedEventLoop *loop = nullptr;
746 bool has_setup = false;
747 };
748
Austin Schuh7d87b672019-12-01 20:23:49 -0800749 void HandleEvent() {
750 while (true) {
751 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
752 break;
753 }
754
755 EventLoopEvent *event = PopEvent();
756 event->HandleEvent();
757 }
758 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800759
Austin Schuh39788ff2019-12-01 18:22:57 -0800760 pid_t GetTid() override { return tid_; }
761
Alex Perrycb7da4b2019-08-28 19:35:56 -0700762 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800763 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700764 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700765 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700766
767 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800768
769 int priority_ = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700770 cpu_set_t affinity_ = DefaultAffinity();
Austin Schuh39788ff2019-12-01 18:22:57 -0800771
Austin Schuh7d87b672019-12-01 20:23:49 -0800772 std::chrono::nanoseconds send_delay_;
773
Austin Schuh217a9782019-12-21 23:02:50 -0800774 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800775 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800776
777 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700778 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800779
780 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700781
782 std::shared_ptr<StartupTracker> startup_tracker_;
James Kuszmaul890c2492022-04-06 14:59:31 -0700783
784 EventLoopOptions options_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700785};
786
Austin Schuh7d87b672019-12-01 20:23:49 -0800787void SimulatedEventLoopFactory::set_send_delay(
788 std::chrono::nanoseconds send_delay) {
789 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700790 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700791 if (node) {
792 for (SimulatedEventLoop *loop : node->event_loops_) {
793 loop->set_send_delay(send_delay_);
794 }
795 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800796 }
797}
798
James Kuszmaulb67409b2022-06-20 16:25:03 -0700799void SimulatedEventLoopFactory::SetRealtimeReplayRate(double replay_rate) {
800 scheduler_scheduler_.SetReplayRate(replay_rate);
801}
802
Alex Perrycb7da4b2019-08-28 19:35:56 -0700803void SimulatedEventLoop::MakeRawWatcher(
804 const Channel *channel,
805 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800806 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800807
Austin Schuh057d29f2021-08-21 23:05:15 -0700808 std::unique_ptr<SimulatedWatcher> shm_watcher =
809 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
810 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800811
812 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700813
Austin Schuh39788ff2019-12-01 18:22:57 -0800814 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700815 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
816 << " " << name() << " MakeRawWatcher(\""
817 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800818
819 // Order of operations gets kinda wonky if we let people make watchers after
820 // running once. If someone has a valid use case, we can reconsider.
821 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700822}
823
824std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
825 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800826 TakeSender(channel);
827
Austin Schuh58646e22021-08-23 23:51:46 -0700828 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
829 << " " << name() << " MakeRawSender(\""
830 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700831 return GetSimulatedChannel(channel)->MakeRawSender(this);
832}
833
834std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
835 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800836 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800837
Austin Schuhca4828c2019-12-28 14:21:35 -0800838 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
839 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
840 << "\", \"type\": \"" << channel->type()->string_view()
841 << "\" } is not able to be fetched on this node. Check your "
842 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800843 }
844
Austin Schuh58646e22021-08-23 23:51:46 -0700845 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
846 << " " << name() << " MakeRawFetcher(\""
847 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800848 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700849}
850
851SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
852 const Channel *channel) {
853 auto it = channels_->find(SimpleChannel(channel));
854 if (it == channels_->end()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700855 it = channels_
856 ->emplace(SimpleChannel(channel),
857 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
858 channel,
Austin Schuhfff9c3a2023-06-16 18:48:23 -0700859 configuration::ChannelStorageDuration(
860 configuration(), channel),
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700861 scheduler_)))
862 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700863 }
864 return it->second.get();
865}
866
Brian Silverman4f4e0612020-08-12 19:54:41 -0700867int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
868 return GetSimulatedChannel(channel)->number_buffers();
869}
870
Austin Schuh7d87b672019-12-01 20:23:49 -0800871SimulatedWatcher::SimulatedWatcher(
872 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800873 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800874 std::function<void(const Context &context, const void *message)> fn)
875 : WatcherState(simulated_event_loop, channel, std::move(fn)),
876 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700877 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800878 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700879 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700880 token_(scheduler_->InvalidToken()) {
881 VLOG(1) << simulated_event_loop_->distributed_now() << " "
882 << NodeName(simulated_event_loop_->node())
883 << simulated_event_loop_->monotonic_now() << " "
884 << simulated_event_loop_->name() << " Watching "
885 << configuration::StrippedChannelToString(channel_);
886}
Austin Schuh7d87b672019-12-01 20:23:49 -0800887
888SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700889 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700890 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700891 << simulated_event_loop_->monotonic_now() << " "
892 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700893 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800894 simulated_event_loop_->RemoveEvent(&event_);
895 if (token_ != scheduler_->InvalidToken()) {
896 scheduler_->Deschedule(token_);
897 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700898 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800899}
900
Austin Schuh8fb315a2020-11-19 22:33:58 -0800901bool SimulatedWatcher::has_run() const {
902 return simulated_event_loop_->has_run();
903}
904
Austin Schuh7d87b672019-12-01 20:23:49 -0800905void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800906 monotonic_clock::time_point event_time =
907 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800908
909 // Messages are queued in order. If we are the first, add ourselves.
910 // Otherwise, don't.
911 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800912 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800913 simulated_event_loop_->AddEvent(&event_);
914
915 DoSchedule(event_time);
916 }
917
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800918 msgs_.emplace_back(std::move(message));
Austin Schuh7d87b672019-12-01 20:23:49 -0800919}
920
Austin Schuhf4b09c72021-12-08 12:04:37 -0800921void SimulatedWatcher::HandleEvent() noexcept {
Austin Schuh7d87b672019-12-01 20:23:49 -0800922 const monotonic_clock::time_point monotonic_now =
923 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700924 VLOG(1) << simulated_event_loop_->distributed_now() << " "
925 << NodeName(simulated_event_loop_->node())
926 << simulated_event_loop_->monotonic_now() << " "
927 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700928 << configuration::StrippedChannelToString(channel_);
929 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
930
Tyler Chatow67ddb032020-01-12 14:30:04 -0800931 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700932 if (simulated_event_loop_->log_impl_) {
933 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800934 }
Austin Schuhad154822019-12-27 15:45:13 -0800935 Context context = msgs_.front()->context;
936
Brian Silverman4f4e0612020-08-12 19:54:41 -0700937 if (channel_->read_method() != ReadMethod::PIN) {
938 context.buffer_index = -1;
939 }
Austin Schuhad154822019-12-27 15:45:13 -0800940 if (context.remote_queue_index == 0xffffffffu) {
941 context.remote_queue_index = context.queue_index;
942 }
Austin Schuh58646e22021-08-23 23:51:46 -0700943 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800944 context.monotonic_remote_time = context.monotonic_event_time;
945 }
Austin Schuh58646e22021-08-23 23:51:46 -0700946 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800947 context.realtime_remote_time = context.realtime_event_time;
948 }
949
Austin Schuhcc6070c2020-10-10 20:25:56 -0700950 {
Austin Schuh65493d62022-08-17 15:10:37 -0700951 ScopedMarkRealtimeRestorer rt(
952 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700953 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh0debde12022-08-17 16:25:17 -0700954 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700955 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800956
957 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700958 if (token_ != scheduler_->InvalidToken()) {
959 scheduler_->Deschedule(token_);
960 token_ = scheduler_->InvalidToken();
961 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800962 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800963 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800964 simulated_event_loop_->AddEvent(&event_);
965
966 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800967 }
968}
969
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800970void SimulatedWatcher::Handle() noexcept {
971 DCHECK(token_ != scheduler_->InvalidToken());
972 token_ = scheduler_->InvalidToken();
973 simulated_event_loop_->HandleEvent();
974}
975
Austin Schuh7d87b672019-12-01 20:23:49 -0800976void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700977 CHECK(token_ == scheduler_->InvalidToken())
978 << ": May not schedule multiple times";
979 token_ = scheduler_->Schedule(
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800980 event_time + simulated_event_loop_->send_delay(), this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800981}
982
983void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700984 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800985 watcher->SetSimulatedChannel(this);
986 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700987}
988
989::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800990 SimulatedEventLoop *event_loop) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700991 CHECK(allow_new_senders_)
992 << ": Attempted to create a new sender on exclusive channel "
993 << configuration::StrippedChannelToString(channel_);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700994 std::optional<ExclusiveSenders> per_channel_option;
995 for (const std::pair<const aos::Channel *, ExclusiveSenders> &per_channel :
996 event_loop->options().per_channel_exclusivity) {
997 if (per_channel.first->name()->string_view() ==
998 channel_->name()->string_view() &&
999 per_channel.first->type()->string_view() ==
1000 channel_->type()->string_view()) {
1001 CHECK(!per_channel_option.has_value())
1002 << ": Channel " << configuration::StrippedChannelToString(channel_)
1003 << " listed twice in per-channel list.";
1004 per_channel_option = per_channel.second;
1005 }
1006 }
1007 if (!per_channel_option.has_value()) {
1008 // This could just as easily be implemented by setting
1009 // per_channel_option to the global setting when we initialize it, but
1010 // then we'd lose track of whether a given channel appears twice in
1011 // the list.
1012 per_channel_option = event_loop->options().exclusive_senders;
1013 }
1014 if (per_channel_option.value() == ExclusiveSenders::kYes) {
James Kuszmaul890c2492022-04-06 14:59:31 -07001015 CHECK_EQ(0, sender_count_)
1016 << ": Attempted to add an exclusive sender on a channel with existing "
1017 "senders: "
1018 << configuration::StrippedChannelToString(channel_);
1019 allow_new_senders_ = false;
1020 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001021 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
1022}
1023
Austin Schuh39788ff2019-12-01 18:22:57 -08001024::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
1025 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -07001026 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -08001027 ::std::unique_ptr<SimulatedFetcher> fetcher(
1028 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -07001029 fetchers_.push_back(fetcher.get());
James Kuszmaul9776b392023-01-14 14:08:08 -08001030 return fetcher;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001031}
1032
milind1f1dca32021-07-03 13:50:07 -07001033std::optional<uint32_t> SimulatedChannel::Send(
Austin Schuh60e77942022-05-16 17:48:24 -07001034 std::shared_ptr<SimulatedMessage> message,
1035 CheckSentTooFast check_sent_too_fast) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001036 const auto now = scheduler_->monotonic_now();
1037 // Remove times that are greater than or equal to a channel_storage_duration_
1038 // ago
1039 while (!last_times_.empty() &&
1040 (now - last_times_.front() >= channel_storage_duration_)) {
1041 last_times_.pop();
1042 }
1043
1044 // Check that we are not sending messages too fast
James Kuszmaul890c2492022-04-06 14:59:31 -07001045 if (check_sent_too_fast == CheckSentTooFast::kYes &&
1046 static_cast<int>(last_times_.size()) >= queue_size()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001047 return std::nullopt;
1048 }
1049
1050 const std::optional<uint32_t> queue_index = {next_queue_index_.index()};
1051 last_times_.push(now);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001052
milind1f1dca32021-07-03 13:50:07 -07001053 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001054 // Points to the actual data depending on the size set in context. Data may
1055 // allocate more than the actual size of the message, so offset from the back
1056 // of that to get the actual start of the data.
1057 message->context.data =
1058 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -07001059
1060 DCHECK(channel()->has_schema())
1061 << ": Missing schema for channel "
1062 << configuration::StrippedChannelToString(channel());
1063 DCHECK(flatbuffers::Verify(
1064 *channel()->schema(), *channel()->schema()->root_table(),
1065 static_cast<const uint8_t *>(message->context.data),
1066 message->context.size))
1067 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
1068 << channel()->type()->c_str();
1069
Alex Perrycb7da4b2019-08-28 19:35:56 -07001070 next_queue_index_ = next_queue_index_.Increment();
1071
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001072 latest_message_ = std::move(message);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001073 for (SimulatedWatcher *watcher : watchers_) {
1074 if (watcher->has_run()) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001075 watcher->Schedule(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001076 }
1077 }
1078 for (auto &fetcher : fetchers_) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001079 fetcher->Enqueue(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001080 }
Austin Schuhad154822019-12-27 15:45:13 -08001081 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001082}
1083
1084void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
1085 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
1086}
1087
Austin Schuh8fb315a2020-11-19 22:33:58 -08001088SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
1089 SimulatedEventLoop *event_loop)
1090 : RawSender(event_loop, simulated_channel->channel()),
1091 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -07001092 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -08001093 simulated_channel_->CountSenderCreated();
1094}
1095
1096SimulatedSender::~SimulatedSender() {
1097 simulated_channel_->CountSenderDestroyed();
1098}
1099
milind1f1dca32021-07-03 13:50:07 -07001100RawSender::Error SimulatedSender::DoSend(
1101 size_t length, monotonic_clock::time_point monotonic_remote_time,
1102 realtime_clock::time_point realtime_remote_time,
1103 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001104 // The allocations in here are due to infrastructure and don't count in the
1105 // no mallocs in RT code.
1106 ScopedNotRealtime nrt;
1107
Austin Schuh58646e22021-08-23 23:51:46 -07001108 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1109 << NodeName(simulated_event_loop_->node())
1110 << simulated_event_loop_->monotonic_now() << " "
1111 << simulated_event_loop_->name() << " Send "
1112 << configuration::StrippedChannelToString(channel());
1113
Austin Schuh8fb315a2020-11-19 22:33:58 -08001114 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -07001115 message_->context.monotonic_event_time =
1116 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001117 message_->context.monotonic_remote_time = monotonic_remote_time;
1118 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001119 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001120 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001121 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001122 CHECK_LE(length, message_->context.size);
1123 message_->context.size = length;
1124
Austin Schuh60e77942022-05-16 17:48:24 -07001125 const std::optional<uint32_t> optional_queue_index = simulated_channel_->Send(
1126 message_, simulated_event_loop_->options().check_sent_too_fast);
milind1f1dca32021-07-03 13:50:07 -07001127
1128 // Check that we are not sending messages too fast
1129 if (!optional_queue_index) {
1130 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1131 << NodeName(simulated_event_loop_->node())
1132 << simulated_event_loop_->monotonic_now() << " "
1133 << simulated_event_loop_->name()
1134 << "\nMessages were sent too fast:\n"
1135 << "For channel: "
1136 << configuration::CleanedChannelToString(
1137 simulated_channel_->channel())
1138 << '\n'
1139 << "Tried to send more than " << simulated_channel_->queue_size()
1140 << " (queue size) messages in the last "
1141 << std::chrono::duration<double>(
1142 simulated_channel_->channel_storage_duration())
1143 .count()
1144 << " seconds (channel storage duration)"
1145 << "\n\n";
1146 return Error::kMessagesSentTooFast;
1147 }
1148
1149 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001150 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1151 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001152
1153 // Drop the reference to the message so that we allocate a new message for
1154 // next time. Otherwise we will continue to reuse the same memory for all
1155 // messages and corrupt it.
1156 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001157 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001158}
1159
milind1f1dca32021-07-03 13:50:07 -07001160RawSender::Error SimulatedSender::DoSend(
1161 const void *msg, size_t size,
1162 monotonic_clock::time_point monotonic_remote_time,
1163 realtime_clock::time_point realtime_remote_time,
1164 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001165 CHECK_LE(size, this->size())
1166 << ": Attempting to send too big a message on "
1167 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001168
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001169 // Allocates an aligned buffer in which to copy unaligned msg.
1170 auto [span, mutable_span] = MakeSharedSpan(size);
1171 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001172
1173 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001174 // queue_index will be populated in simulated_channel_.
1175 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001176
1177 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001178 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001179}
1180
milind1f1dca32021-07-03 13:50:07 -07001181RawSender::Error SimulatedSender::DoSend(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001182 const SharedSpan data, monotonic_clock::time_point monotonic_remote_time,
milind1f1dca32021-07-03 13:50:07 -07001183 realtime_clock::time_point realtime_remote_time,
1184 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001185 CHECK_LE(data->size(), this->size())
1186 << ": Attempting to send too big a message on "
1187 << configuration::CleanedChannelToString(simulated_channel_->channel());
1188
1189 // Constructs a message sharing the already allocated and aligned message
1190 // data.
1191 message_ = SimulatedMessage::Make(simulated_channel_, data);
1192
1193 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1194 remote_queue_index, source_boot_uuid);
1195}
1196
Austin Schuh39788ff2019-12-01 18:22:57 -08001197SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001198 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1199 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001200 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001201 simulated_event_loop_(simulated_event_loop),
1202 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001203 scheduler_(scheduler),
1204 token_(scheduler_->InvalidToken()) {}
1205
Philipp Schradera6712522023-07-05 20:25:11 -07001206void SimulatedTimerHandler::Schedule(monotonic_clock::time_point base,
1207 monotonic_clock::duration repeat_offset) {
James Kuszmaul86e86c32022-07-21 17:39:47 -07001208 CHECK_GE(base, monotonic_clock::epoch());
Austin Schuh62288252020-11-18 23:26:04 -08001209 // The allocations in here are due to infrastructure and don't count in the no
1210 // mallocs in RT code.
1211 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001212 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001213 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001214 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001215 base_ = base;
1216 repeat_offset_ = repeat_offset;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001217 token_ = scheduler_->Schedule(std::max(base, monotonic_now), this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001218 event_.set_event_time(base_);
1219 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001220 disabled_ = false;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001221}
1222
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001223void SimulatedTimerHandler::Handle() noexcept {
1224 DCHECK(token_ != scheduler_->InvalidToken());
1225 token_ = scheduler_->InvalidToken();
1226 simulated_event_loop_->HandleEvent();
1227}
1228
Austin Schuhf4b09c72021-12-08 12:04:37 -08001229void SimulatedTimerHandler::HandleEvent() noexcept {
Austin Schuh58646e22021-08-23 23:51:46 -07001230 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001231 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001232 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1233 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1234 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001235 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001236 if (simulated_event_loop_->log_impl_) {
1237 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001238 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001239 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001240 {
1241 ScopedNotRealtime nrt;
1242 scheduler_->Deschedule(token_);
1243 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001244 token_ = scheduler_->InvalidToken();
1245 }
Austin Schuh58646e22021-08-23 23:51:46 -07001246 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001247 // Reschedule.
1248 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001249 token_ = scheduler_->Schedule(base_, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001250 event_.set_event_time(base_);
1251 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001252 disabled_ = false;
1253 } else {
1254 disabled_ = true;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001255 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001256 {
Austin Schuh65493d62022-08-17 15:10:37 -07001257 ScopedMarkRealtimeRestorer rt(
1258 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -07001259 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuh0debde12022-08-17 16:25:17 -07001260 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001261 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001262}
1263
Austin Schuh7d87b672019-12-01 20:23:49 -08001264void SimulatedTimerHandler::Disable() {
1265 simulated_event_loop_->RemoveEvent(&event_);
1266 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001267 {
1268 ScopedNotRealtime nrt;
1269 scheduler_->Deschedule(token_);
1270 }
Austin Schuh7d87b672019-12-01 20:23:49 -08001271 token_ = scheduler_->InvalidToken();
1272 }
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001273 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -08001274}
1275
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001276bool SimulatedTimerHandler::IsDisabled() { return disabled_; }
1277
Austin Schuh39788ff2019-12-01 18:22:57 -08001278SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001279 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1280 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001281 const monotonic_clock::duration offset)
1282 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1283 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001284 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001285 scheduler_(scheduler),
1286 token_(scheduler_->InvalidToken()) {}
1287
Austin Schuh7d87b672019-12-01 20:23:49 -08001288SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1289 if (token_ != scheduler_->InvalidToken()) {
1290 scheduler_->Deschedule(token_);
1291 token_ = scheduler_->InvalidToken();
1292 }
1293 simulated_event_loop_->RemoveEvent(&event_);
1294}
1295
Austin Schuhf4b09c72021-12-08 12:04:37 -08001296void SimulatedPhasedLoopHandler::HandleEvent() noexcept {
Austin Schuh39788ff2019-12-01 18:22:57 -08001297 monotonic_clock::time_point monotonic_now =
1298 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001299 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1300 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001301 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001302 if (simulated_event_loop_->log_impl_) {
1303 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001304 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001305
1306 {
Austin Schuh65493d62022-08-17 15:10:37 -07001307 ScopedMarkRealtimeRestorer rt(
1308 simulated_event_loop_->runtime_realtime_priority() > 0);
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001309 Call([monotonic_now]() { return monotonic_now; });
Austin Schuh0debde12022-08-17 16:25:17 -07001310 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001311 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001312}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001313
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001314void SimulatedPhasedLoopHandler::Handle() noexcept {
1315 DCHECK(token_ != scheduler_->InvalidToken());
1316 token_ = scheduler_->InvalidToken();
1317 simulated_event_loop_->HandleEvent();
1318}
1319
Austin Schuh7d87b672019-12-01 20:23:49 -08001320void SimulatedPhasedLoopHandler::Schedule(
1321 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001322 // The allocations in here are due to infrastructure and don't count in the no
1323 // mallocs in RT code.
1324 ScopedNotRealtime nrt;
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001325 simulated_event_loop_->RemoveEvent(&event_);
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001326 if (token_ != scheduler_->InvalidToken()) {
1327 scheduler_->Deschedule(token_);
1328 token_ = scheduler_->InvalidToken();
1329 }
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001330 token_ = scheduler_->Schedule(sleep_time, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001331 event_.set_event_time(sleep_time);
1332 simulated_event_loop_->AddEvent(&event_);
1333}
1334
Alex Perrycb7da4b2019-08-28 19:35:56 -07001335SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1336 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001337 : configuration_(CHECK_NOTNULL(configuration)),
1338 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001339 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001340 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001341 node_factories_.emplace_back(
1342 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001343 }
Austin Schuh898f4972020-01-11 17:21:25 -08001344
Austin Schuh54ffea42023-08-23 13:27:04 -07001345 if (configuration::NodesCount(configuration) > 1u) {
Austin Schuh898f4972020-01-11 17:21:25 -08001346 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1347 }
Austin Schuh15649d62019-12-28 16:36:38 -08001348}
1349
Brian Silvermane1fe2512022-08-14 23:18:50 -07001350SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {
1351 CHECK_EQ(0, exit_handle_count_)
1352 << ": All ExitHandles must be destroyed before the factory";
1353}
Alex Perrycb7da4b2019-08-28 19:35:56 -07001354
Austin Schuhac0771c2020-01-07 18:36:30 -08001355NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001356 std::string_view node) {
1357 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1358}
1359
1360NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001361 const Node *node) {
1362 auto result = std::find_if(
1363 node_factories_.begin(), node_factories_.end(),
1364 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1365 return node_factory->node() == node;
1366 });
1367
1368 CHECK(result != node_factories_.end())
1369 << ": Failed to find node " << FlatbufferToJson(node);
1370
1371 return result->get();
1372}
1373
Austin Schuh87dd3832021-01-01 23:07:31 -08001374void SimulatedEventLoopFactory::SetTimeConverter(
1375 TimeConverter *time_converter) {
1376 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1377 factory->SetTimeConverter(time_converter);
1378 }
Austin Schuh58646e22021-08-23 23:51:46 -07001379 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001380}
1381
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001382::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001383 std::string_view name, const Node *node) {
1384 if (node == nullptr) {
1385 CHECK(!configuration::MultiNode(configuration()))
1386 << ": Can't make a single node event loop in a multi-node world.";
1387 } else {
1388 CHECK(configuration::MultiNode(configuration()))
1389 << ": Can't make a multi-node event loop in a single-node world.";
1390 }
1391 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1392}
1393
Austin Schuh057d29f2021-08-21 23:05:15 -07001394NodeEventLoopFactory::NodeEventLoopFactory(
1395 EventSchedulerScheduler *scheduler_scheduler,
1396 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001397 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1398 factory_(factory),
1399 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001400 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001401 scheduler_.set_started([this]() {
1402 started_ = true;
1403 for (SimulatedEventLoop *event_loop : event_loops_) {
1404 event_loop->SetIsRunning(true);
1405 }
1406 });
Austin Schuhe33c08d2022-02-03 18:15:21 -08001407 scheduler_.set_stopped([this]() {
1408 for (SimulatedEventLoop *event_loop : event_loops_) {
1409 event_loop->SetIsRunning(false);
1410 }
1411 });
Austin Schuh58646e22021-08-23 23:51:46 -07001412 scheduler_.set_on_shutdown([this]() {
1413 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1414 << monotonic_now() << " Shutting down node.";
1415 Shutdown();
1416 ScheduleStartup();
1417 });
1418 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001419}
1420
1421NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001422 if (started_) {
1423 for (std::function<void()> &fn : on_shutdown_) {
1424 fn();
1425 }
1426
1427 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1428 << monotonic_now() << " Shutting down applications.";
1429 applications_.clear();
1430 started_ = false;
1431 }
1432
1433 if (event_loops_.size() != 0u) {
1434 for (SimulatedEventLoop *event_loop : event_loops_) {
1435 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1436 << monotonic_now() << " Event loop '" << event_loop->name()
1437 << "' failed to shut down";
1438 }
1439 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001440 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1441}
1442
Austin Schuh58646e22021-08-23 23:51:46 -07001443void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001444 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001445 << ": Can only register OnStartup handlers when not running.";
1446 on_startup_.emplace_back(std::move(fn));
1447 if (started_) {
1448 size_t on_startup_index = on_startup_.size() - 1;
1449 scheduler_.ScheduleOnStartup(
1450 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1451 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001452}
1453
Austin Schuh58646e22021-08-23 23:51:46 -07001454void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1455 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001456}
Austin Schuh057d29f2021-08-21 23:05:15 -07001457
Austin Schuh58646e22021-08-23 23:51:46 -07001458void NodeEventLoopFactory::ScheduleStartup() {
1459 scheduler_.ScheduleOnStartup([this]() {
1460 UUID next_uuid = scheduler_.boot_uuid();
1461 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001462 CHECK_EQ(boot_uuid_, UUID::Zero())
1463 << ": Boot UUID changed without restarting. Did TimeConverter "
1464 "change the boot UUID without signaling a restart, or did you "
1465 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001466 boot_uuid_ = next_uuid;
1467 }
1468 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1469 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1470 Startup();
1471 });
1472}
1473
1474void NodeEventLoopFactory::Startup() {
1475 CHECK(!started_);
1476 for (size_t i = 0; i < on_startup_.size(); ++i) {
1477 on_startup_[i]();
1478 }
1479}
1480
1481void NodeEventLoopFactory::Shutdown() {
1482 for (SimulatedEventLoop *event_loop : event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001483 CHECK(!event_loop->is_running());
Austin Schuh58646e22021-08-23 23:51:46 -07001484 }
1485
1486 CHECK(started_);
1487 started_ = false;
1488 for (std::function<void()> &fn : on_shutdown_) {
1489 fn();
1490 }
1491
1492 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1493 << monotonic_now() << " Shutting down applications.";
1494 applications_.clear();
1495
1496 if (event_loops_.size() != 0u) {
1497 for (SimulatedEventLoop *event_loop : event_loops_) {
1498 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1499 << monotonic_now() << " Event loop '" << event_loop->name()
1500 << "' failed to shut down";
1501 }
1502 }
1503 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1504 boot_uuid_ = UUID::Zero();
1505
1506 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001507}
1508
Alex Perrycb7da4b2019-08-28 19:35:56 -07001509void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001510 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001511 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001512 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1513 if (node) {
1514 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001515 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001516 }
1517 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001518 }
1519}
1520
1521void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001522 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001523 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001524 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1525 if (node) {
1526 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001527 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001528 }
1529 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001530 }
1531}
1532
Austin Schuh87dd3832021-01-01 23:07:31 -08001533void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001534
Brian Silvermane1fe2512022-08-14 23:18:50 -07001535std::unique_ptr<ExitHandle> SimulatedEventLoopFactory::MakeExitHandle() {
1536 return std::make_unique<SimulatedFactoryExitHandle>(this);
1537}
1538
Austin Schuh6f3babe2020-01-26 20:34:50 -08001539void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001540 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001541 bridge_->DisableForwarding(channel);
1542}
1543
Austin Schuh4c3b9702020-08-30 11:34:55 -07001544void SimulatedEventLoopFactory::DisableStatistics() {
1545 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
James Kuszmaul94ca5132022-07-19 09:11:08 -07001546 bridge_->DisableStatistics(
1547 message_bridge::SimulatedMessageBridge::DestroySenders::kNo);
1548}
1549
1550void SimulatedEventLoopFactory::PermanentlyDisableStatistics() {
1551 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1552 bridge_->DisableStatistics(
1553 message_bridge::SimulatedMessageBridge::DestroySenders::kYes);
Austin Schuh4c3b9702020-08-30 11:34:55 -07001554}
1555
Austin Schuh48205e62021-11-12 14:13:18 -08001556void SimulatedEventLoopFactory::EnableStatistics() {
1557 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1558 bridge_->EnableStatistics();
1559}
1560
Austin Schuh2928ebe2021-02-07 22:10:27 -08001561void SimulatedEventLoopFactory::SkipTimingReport() {
1562 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001563
1564 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1565 if (node) {
1566 node->SkipTimingReport();
1567 }
1568 }
1569}
1570
1571void NodeEventLoopFactory::SkipTimingReport() {
1572 for (SimulatedEventLoop *event_loop : event_loops_) {
1573 event_loop->SkipTimingReport();
1574 }
1575 skip_timing_report_ = true;
1576}
1577
1578void NodeEventLoopFactory::EnableStatistics() {
1579 CHECK(factory_->bridge_)
1580 << ": Can't enable statistics without a message bridge.";
1581 factory_->bridge_->EnableStatistics(node_);
1582}
1583
1584void NodeEventLoopFactory::DisableStatistics() {
1585 CHECK(factory_->bridge_)
1586 << ": Can't disable statistics without a message bridge.";
1587 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001588}
1589
Austin Schuh58646e22021-08-23 23:51:46 -07001590::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
James Kuszmaul890c2492022-04-06 14:59:31 -07001591 std::string_view name, EventLoopOptions options) {
Austin Schuh58646e22021-08-23 23:51:46 -07001592 CHECK(!scheduler_.is_running() || !started_)
1593 << ": Can't create an event loop while running";
1594
1595 pid_t tid = tid_;
1596 ++tid_;
1597 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1598 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
James Kuszmaul890c2492022-04-06 14:59:31 -07001599 node_, tid, options));
Austin Schuh58646e22021-08-23 23:51:46 -07001600 result->set_name(name);
1601 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001602 if (skip_timing_report_) {
1603 result->SkipTimingReport();
1604 }
Austin Schuh58646e22021-08-23 23:51:46 -07001605
1606 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1607 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
James Kuszmaul9776b392023-01-14 14:08:08 -08001608 return result;
Austin Schuh58646e22021-08-23 23:51:46 -07001609}
1610
Austin Schuhe33c08d2022-02-03 18:15:21 -08001611void SimulatedEventLoopFactory::AllowApplicationCreationDuring(
1612 std::function<void()> fn) {
1613 scheduler_scheduler_.TemporarilyStopAndRun(std::move(fn));
1614}
1615
Austin Schuh58646e22021-08-23 23:51:46 -07001616void NodeEventLoopFactory::Disconnect(const Node *other) {
1617 factory_->bridge_->Disconnect(node_, other);
1618}
1619
1620void NodeEventLoopFactory::Connect(const Node *other) {
1621 factory_->bridge_->Connect(node_, other);
1622}
1623
Alex Perrycb7da4b2019-08-28 19:35:56 -07001624} // namespace aos