blob: 5cb67b40562085ecb6801cae5d4edc0ef28d8ea4 [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
Philipp Schrader81fa3fb2023-09-17 18:58:35 -0700103 void Construct() override {}
104 void Startup() override {}
Austin Schuh39788ff2019-12-01 18:22:57 -0800105
Austin Schuh7d87b672019-12-01 20:23:49 -0800106 void Schedule(std::shared_ptr<SimulatedMessage> message);
107
Austin Schuhf4b09c72021-12-08 12:04:37 -0800108 void HandleEvent() noexcept;
Austin Schuh39788ff2019-12-01 18:22:57 -0800109
110 void SetSimulatedChannel(SimulatedChannel *channel) {
111 simulated_channel_ = channel;
112 }
113
114 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800115 void DoSchedule(monotonic_clock::time_point event_time);
116
117 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
118
Brian Silverman4f4e0612020-08-12 19:54:41 -0700119 SimulatedEventLoop *const simulated_event_loop_;
120 const Channel *const channel_;
121 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800122 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800123 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800124 SimulatedChannel *simulated_channel_ = nullptr;
125};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700126
Brian Silvermane1fe2512022-08-14 23:18:50 -0700127class SimulatedFactoryExitHandle : public ExitHandle {
128 public:
129 SimulatedFactoryExitHandle(SimulatedEventLoopFactory *factory)
130 : factory_(factory) {
131 ++factory_->exit_handle_count_;
132 }
133 ~SimulatedFactoryExitHandle() override {
134 CHECK_GT(factory_->exit_handle_count_, 0);
135 --factory_->exit_handle_count_;
136 }
137
138 void Exit() override { factory_->Exit(); }
139
140 private:
141 SimulatedEventLoopFactory *const factory_;
142};
143
Alex Perrycb7da4b2019-08-28 19:35:56 -0700144class SimulatedChannel {
145 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800146 explicit SimulatedChannel(const Channel *channel,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700147 std::chrono::nanoseconds channel_storage_duration,
148 const EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -0800149 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700150 channel_storage_duration_(channel_storage_duration),
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700151 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())),
152 scheduler_(scheduler) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700153 // Gut check that things fit. Configuration validation should have caught
154 // this before we get here.
155 CHECK_LT(static_cast<size_t>(number_buffers()),
156 std::numeric_limits<
157 decltype(available_buffer_indices_)::value_type>::max())
158 << configuration::CleanedChannelToString(channel);
Brian Silvermanbc596c62021-10-15 14:04:54 -0700159 available_buffer_indices_.resize(number_buffers());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700160 for (int i = 0; i < number_buffers(); ++i) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700161 available_buffer_indices_[i] = i;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700162 }
163 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164
Brian Silverman661eb8d2020-08-12 19:41:01 -0700165 ~SimulatedChannel() {
166 latest_message_.reset();
167 CHECK_EQ(static_cast<size_t>(number_buffers()),
168 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800169 CHECK_EQ(0u, fetchers_.size())
170 << configuration::StrippedChannelToString(channel());
171 CHECK_EQ(0u, watchers_.size())
172 << configuration::StrippedChannelToString(channel());
173 CHECK_EQ(0, sender_count_)
174 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700175 }
176
177 // The number of messages we pretend to have in the queue.
178 int queue_size() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700179 return configuration::QueueSize(channel()->frequency(),
180 channel_storage_duration_);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700181 }
182
milind1f1dca32021-07-03 13:50:07 -0700183 std::chrono::nanoseconds channel_storage_duration() const {
184 return channel_storage_duration_;
185 }
186
Brian Silverman661eb8d2020-08-12 19:41:01 -0700187 // The number of extra buffers (beyond the queue) we pretend to have.
188 int number_scratch_buffers() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700189 return configuration::QueueScratchBufferSize(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700190 }
191
192 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
193
194 int GetBufferIndex() {
195 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
196 const int result = available_buffer_indices_.back();
197 available_buffer_indices_.pop_back();
198 return result;
199 }
200
201 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700202 // This extra checking has a large performance hit with sanitizers that
203 // track memory accesses, so just skip it.
204#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700205 DCHECK(std::find(available_buffer_indices_.begin(),
206 available_buffer_indices_.end(),
207 i) == available_buffer_indices_.end())
208 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800209#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700210 available_buffer_indices_.push_back(i);
211 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700212
213 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800214 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700215
216 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800217 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700218
219 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800220 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800221
Austin Schuh7d87b672019-12-01 20:23:49 -0800222 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800223 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
224 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700225
Austin Schuhad154822019-12-27 15:45:13 -0800226 // Sends the message to all the connected receivers and fetchers. Returns the
milind1f1dca32021-07-03 13:50:07 -0700227 // sent queue index, or std::nullopt if messages were sent too fast.
James Kuszmaul890c2492022-04-06 14:59:31 -0700228 std::optional<uint32_t> Send(std::shared_ptr<SimulatedMessage> message,
229 CheckSentTooFast check_sent_too_fast);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700230
231 // Unregisters a fetcher.
232 void UnregisterFetcher(SimulatedFetcher *fetcher);
233
234 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
235
Austin Schuh39788ff2019-12-01 18:22:57 -0800236 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700237
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800238 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800239 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700240 }
241
Austin Schuh39788ff2019-12-01 18:22:57 -0800242 const Channel *channel() const { return channel_; }
243
Austin Schuhe516ab02020-05-06 21:37:04 -0700244 void CountSenderCreated() {
245 if (sender_count_ >= channel()->num_senders()) {
246 LOG(FATAL) << "Failed to create sender on "
247 << configuration::CleanedChannelToString(channel())
248 << ", too many senders.";
249 }
Austin Schuhfb37c612022-08-11 15:24:51 -0700250 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700251 ++sender_count_;
252 }
Brian Silverman77162972020-08-12 19:52:40 -0700253
Austin Schuhe516ab02020-05-06 21:37:04 -0700254 void CountSenderDestroyed() {
255 --sender_count_;
256 CHECK_GE(sender_count_, 0);
James Kuszmaul890c2492022-04-06 14:59:31 -0700257 if (sender_count_ == 0) {
258 allow_new_senders_ = true;
259 }
Austin Schuhe516ab02020-05-06 21:37:04 -0700260 }
261
Alex Perrycb7da4b2019-08-28 19:35:56 -0700262 private:
Brian Silverman77162972020-08-12 19:52:40 -0700263 void CheckBufferCount() {
264 int reader_count = 0;
265 if (channel()->read_method() == ReadMethod::PIN) {
266 reader_count = watchers_.size() + fetchers_.size();
267 }
268 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
269 }
270
271 void CheckReaderCount() {
272 if (channel()->read_method() != ReadMethod::PIN) {
273 return;
274 }
275 CheckBufferCount();
276 const int reader_count = watchers_.size() + fetchers_.size();
277 if (reader_count >= channel()->num_readers()) {
278 LOG(FATAL) << "Failed to create reader on "
279 << configuration::CleanedChannelToString(channel())
280 << ", too many readers.";
281 }
282 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700283
284 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700285 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700286
287 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800288 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700289
290 // List of all fetchers.
291 ::std::vector<SimulatedFetcher *> fetchers_;
292 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700293
294 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700295
296 int sender_count_ = 0;
James Kuszmaul890c2492022-04-06 14:59:31 -0700297 // Used to track when an exclusive sender has been created (e.g., for log
298 // replay) and we want to prevent new senders from being accidentally created.
299 bool allow_new_senders_ = true;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700300
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700301 std::vector<ipc_lib::QueueIndex::PackedIndexType> available_buffer_indices_;
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700302
303 const EventScheduler *scheduler_;
304
305 // Queue of all the message send times in the last channel_storage_duration_
306 std::queue<monotonic_clock::time_point> last_times_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307};
308
309namespace {
310
Brian Silverman661eb8d2020-08-12 19:41:01 -0700311std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
Austin Schuhe0ab4de2023-05-03 08:05:08 -0700312 SimulatedChannel *channel, SharedSpan data) {
Austin Schuh62288252020-11-18 23:26:04 -0800313 // The allocations in here are due to infrastructure and don't count in the no
314 // mallocs in RT code.
315 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700316
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700317 auto message = std::make_shared<SimulatedMessage>(channel);
318 message->context.size = data->size();
319 message->context.data = data->data();
320 message->data = std::move(data);
321
322 return message;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700323}
324
325SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
326 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700327 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700328}
329
330SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700331 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700332}
333
334class SimulatedSender : public RawSender {
335 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800336 SimulatedSender(SimulatedChannel *simulated_channel,
337 SimulatedEventLoop *event_loop);
338 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700339
340 void *data() override {
341 if (!message_) {
Austin Schuh9b1d6282022-06-10 17:03:21 -0700342 // This API is safe to use in a RT context on a RT system. So annotate it
343 // accordingly.
344 ScopedNotRealtime nrt;
345
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700346 auto [span, mutable_span] =
347 MakeSharedSpan(simulated_channel_->max_size());
348 message_ = SimulatedMessage::Make(simulated_channel_, span);
349 message_->mutable_data = mutable_span;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700350 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700351 CHECK(message_->is_mutable());
352 return message_->mutable_data.data();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700353 }
354
355 size_t size() override { return simulated_channel_->max_size(); }
356
milind1f1dca32021-07-03 13:50:07 -0700357 Error DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
358 realtime_clock::time_point realtime_remote_time,
359 uint32_t remote_queue_index,
360 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700361
milind1f1dca32021-07-03 13:50:07 -0700362 Error DoSend(const void *msg, size_t size,
363 monotonic_clock::time_point monotonic_remote_time,
364 realtime_clock::time_point realtime_remote_time,
365 uint32_t remote_queue_index,
366 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700367
milind1f1dca32021-07-03 13:50:07 -0700368 Error DoSend(const SharedSpan data,
369 aos::monotonic_clock::time_point monotonic_remote_time,
370 aos::realtime_clock::time_point realtime_remote_time,
371 uint32_t remote_queue_index,
372 const UUID &source_boot_uuid) override;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700373
Brian Silverman4f4e0612020-08-12 19:54:41 -0700374 int buffer_index() override {
375 // First, ensure message_ is allocated.
376 data();
377 return message_->context.buffer_index;
378 }
379
Alex Perrycb7da4b2019-08-28 19:35:56 -0700380 private:
381 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700382 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700383
384 std::shared_ptr<SimulatedMessage> message_;
385};
386} // namespace
387
388class SimulatedFetcher : public RawFetcher {
389 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800390 explicit SimulatedFetcher(EventLoop *event_loop,
391 SimulatedChannel *simulated_channel)
392 : RawFetcher(event_loop, simulated_channel->channel()),
393 simulated_channel_(simulated_channel) {}
394 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395
Austin Schuh39788ff2019-12-01 18:22:57 -0800396 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh98ed26f2023-07-19 14:12:28 -0700397 return DoFetchNextIf(std::function<bool(const Context &context)>());
398 }
399
400 std::pair<bool, monotonic_clock::time_point> DoFetchNextIf(
401 std::function<bool(const Context &context)> fn) override {
Austin Schuh62288252020-11-18 23:26:04 -0800402 // The allocations in here are due to infrastructure and don't count in the
403 // no mallocs in RT code.
404 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800405 if (msgs_.size() == 0) {
406 return std::make_pair(false, monotonic_clock::min_time);
407 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700409 CHECK(!fell_behind_) << ": Got behind on "
410 << configuration::StrippedChannelToString(
411 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700412
Austin Schuh98ed26f2023-07-19 14:12:28 -0700413 if (fn) {
414 Context context = msgs_.front()->context;
415 context.data = nullptr;
416 context.buffer_index = -1;
417
418 if (!fn(context)) {
419 return std::make_pair(false, monotonic_clock::min_time);
420 }
421 }
422
423 SetMsg(std::move(msgs_.front()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700424 msgs_.pop_front();
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
Austin Schuh39788ff2019-12-01 18:22:57 -0800428 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh98ed26f2023-07-19 14:12:28 -0700429 return DoFetchIf(std::function<bool(const Context &context)>());
430 }
431
432 std::pair<bool, monotonic_clock::time_point> DoFetchIf(
433 std::function<bool(const Context &context)> fn) override {
Austin Schuh62288252020-11-18 23:26:04 -0800434 // The allocations in here are due to infrastructure and don't count in the
435 // no mallocs in RT code.
436 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700437 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800438 // TODO(austin): Can we just do this logic unconditionally? It is a lot
439 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800440 if (!msg_ && simulated_channel_->latest_message()) {
Austin Schuh98ed26f2023-07-19 14:12:28 -0700441 std::shared_ptr<SimulatedMessage> latest_message =
442 simulated_channel_->latest_message();
443
444 if (fn) {
445 Context context = latest_message->context;
446 context.data = nullptr;
447 context.buffer_index = -1;
448
449 if (!fn(context)) {
450 return std::make_pair(false, monotonic_clock::min_time);
451 }
452 }
453 SetMsg(std::move(latest_message));
Austin Schuha5e14192020-01-06 18:02:41 -0800454 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700455 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800456 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457 }
458 }
459
Austin Schuh98ed26f2023-07-19 14:12:28 -0700460 if (fn) {
461 Context context = msgs_.back()->context;
462 context.data = nullptr;
463 context.buffer_index = -1;
464
465 if (!fn(context)) {
466 return std::make_pair(false, monotonic_clock::min_time);
467 }
468 }
469
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470 // We've had a message enqueued, so we don't need to go looking for the
471 // latest message from before we started.
472 SetMsg(msgs_.back());
473 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700474 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800475 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700476 }
477
478 private:
479 friend class SimulatedChannel;
480
481 // Updates the state inside RawFetcher to point to the data in msg_.
482 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800483 msg_ = std::move(msg);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700484 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700485 if (channel()->read_method() != ReadMethod::PIN) {
486 context_.buffer_index = -1;
487 }
Austin Schuhad154822019-12-27 15:45:13 -0800488 if (context_.remote_queue_index == 0xffffffffu) {
489 context_.remote_queue_index = context_.queue_index;
490 }
Austin Schuh58646e22021-08-23 23:51:46 -0700491 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800492 context_.monotonic_remote_time = context_.monotonic_event_time;
493 }
Austin Schuh58646e22021-08-23 23:51:46 -0700494 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800495 context_.realtime_remote_time = context_.realtime_event_time;
496 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700497 }
498
499 // Internal method for Simulation to add a message to the buffer.
500 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800501 msgs_.emplace_back(std::move(buffer));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700502 if (fell_behind_ ||
503 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
504 fell_behind_ = true;
505 // Might as well empty out all the intermediate messages now.
506 while (msgs_.size() > 1) {
507 msgs_.pop_front();
508 }
509 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700510 }
511
Austin Schuhac0771c2020-01-07 18:36:30 -0800512 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700513 std::shared_ptr<SimulatedMessage> msg_;
514
515 // Messages queued up but not in use.
516 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700517
518 // Whether we're currently "behind", which means a FetchNext call will fail.
519 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700520};
521
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800522class SimulatedTimerHandler : public TimerHandler,
523 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700524 public:
525 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800526 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800527 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800528 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700529
Philipp Schradera6712522023-07-05 20:25:11 -0700530 void Schedule(monotonic_clock::time_point base,
531 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700532
Austin Schuhf4b09c72021-12-08 12:04:37 -0800533 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700534
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800535 void Handle() noexcept override;
536
Austin Schuh7d87b672019-12-01 20:23:49 -0800537 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700539 bool IsDisabled() override;
540
Alex Perrycb7da4b2019-08-28 19:35:56 -0700541 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800542 SimulatedEventLoop *simulated_event_loop_;
543 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544 EventScheduler *scheduler_;
545 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800546
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547 monotonic_clock::time_point base_;
548 monotonic_clock::duration repeat_offset_;
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700549 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550};
551
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800552class SimulatedPhasedLoopHandler : public PhasedLoopHandler,
553 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700554 public:
555 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800556 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557 ::std::function<void(int)> fn,
558 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800559 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800560 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700561
Austin Schuhf4b09c72021-12-08 12:04:37 -0800562 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700563
Austin Schuh7d87b672019-12-01 20:23:49 -0800564 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800566 void Handle() noexcept override;
567
Alex Perrycb7da4b2019-08-28 19:35:56 -0700568 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800569 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800570 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700571
Austin Schuh39788ff2019-12-01 18:22:57 -0800572 EventScheduler *scheduler_;
573 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700574};
575
576class SimulatedEventLoop : public EventLoop {
577 public:
578 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700579 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
581 *channels,
582 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700583 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
James Kuszmaul890c2492022-04-06 14:59:31 -0700584 pid_t tid, EventLoopOptions options)
Austin Schuh83c7f702021-01-19 22:36:29 -0800585 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700586 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800587 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700588 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700589 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800590 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700591 tid_(tid),
James Kuszmaul890c2492022-04-06 14:59:31 -0700592 startup_tracker_(std::make_shared<StartupTracker>()),
593 options_(options) {
Austin Schuh0debde12022-08-17 16:25:17 -0700594 ClearContext();
Austin Schuh58646e22021-08-23 23:51:46 -0700595 startup_tracker_->loop = this;
596 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
597 if (startup_tracker->loop) {
598 startup_tracker->loop->Setup();
599 startup_tracker->has_setup = true;
600 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700601 });
602
603 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700604 }
Austin Schuh58646e22021-08-23 23:51:46 -0700605
Alex Perrycb7da4b2019-08-28 19:35:56 -0700606 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800607 // Trigger any remaining senders or fetchers to be cleared before destroying
608 // the event loop so the book keeping matches.
609 timing_report_sender_.reset();
610
611 // Force everything with a registered fd with epoll to be destroyed now.
612 timers_.clear();
613 phased_loops_.clear();
614 watchers_.clear();
615
Austin Schuh58646e22021-08-23 23:51:46 -0700616 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700617 if (*it == this) {
618 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700619 break;
620 }
621 }
Austin Schuh58646e22021-08-23 23:51:46 -0700622 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
623 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
624 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700625 }
626
Austin Schuh057d29f2021-08-21 23:05:15 -0700627 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700628 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
629 << monotonic_now() << " " << name_ << " set_is_running(" << running
630 << ")";
631 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700632
633 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700634 if (running) {
635 has_run_ = true;
636 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700637 }
638
Austin Schuh8fb315a2020-11-19 22:33:58 -0800639 bool has_run() const { return has_run_; }
640
Austin Schuh7d87b672019-12-01 20:23:49 -0800641 std::chrono::nanoseconds send_delay() const { return send_delay_; }
642 void set_send_delay(std::chrono::nanoseconds send_delay) {
643 send_delay_ = send_delay;
644 }
645
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800646 monotonic_clock::time_point monotonic_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800647 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700648 }
649
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800650 realtime_clock::time_point realtime_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800651 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700652 }
653
Austin Schuh58646e22021-08-23 23:51:46 -0700654 distributed_clock::time_point distributed_now() {
655 return scheduler_->distributed_now();
656 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700657
Austin Schuh58646e22021-08-23 23:51:46 -0700658 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
659
660 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700661
662 void MakeRawWatcher(
663 const Channel *channel,
664 ::std::function<void(const Context &context, const void *message)>
665 watcher) override;
666
667 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800668 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800669 return NewTimer(::std::unique_ptr<TimerHandler>(
670 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700671 }
672
673 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
674 const monotonic_clock::duration interval,
675 const monotonic_clock::duration offset =
676 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800677 return NewPhasedLoop(
678 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
679 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700680 }
681
682 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800683 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700684 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800685 logging::ScopedLogRestorer prev_logger;
686 if (log_impl_) {
687 prev_logger.Swap(log_impl_);
688 }
Austin Schuh65493d62022-08-17 15:10:37 -0700689 ScopedMarkRealtimeRestorer rt(runtime_realtime_priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700690 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700691 on_run();
Austin Schuh0debde12022-08-17 16:25:17 -0700692 ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700693 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700694 }
695
Austin Schuh217a9782019-12-21 23:02:50 -0800696 const Node *node() const override { return node_; }
697
James Kuszmaul3ae42262019-11-08 12:33:41 -0800698 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700699 name_ = std::string(name);
700 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800701 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700702
703 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
704
Austin Schuh39788ff2019-12-01 18:22:57 -0800705 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700706 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800707 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700708 }
709
Austin Schuh65493d62022-08-17 15:10:37 -0700710 int runtime_realtime_priority() const override { return priority_; }
711 const cpu_set_t &runtime_affinity() const override { return affinity_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800712
Austin Schuh65493d62022-08-17 15:10:37 -0700713 void SetRuntimeAffinity(const cpu_set_t &affinity) override {
Brian Silverman6a54ff32020-04-28 16:41:39 -0700714 CHECK(!is_running()) << ": Cannot set affinity while running.";
Austin Schuh65493d62022-08-17 15:10:37 -0700715 affinity_ = affinity;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700716 }
717
Tyler Chatow67ddb032020-01-12 14:30:04 -0800718 void Setup() {
719 MaybeScheduleTimingReports();
720 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800721 log_sender_.Initialize(&name_,
722 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700723 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800724 }
725 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800726
Brian Silverman4f4e0612020-08-12 19:54:41 -0700727 int NumberBuffers(const Channel *channel) override;
728
Austin Schuh83c7f702021-01-19 22:36:29 -0800729 const UUID &boot_uuid() const override {
730 return node_event_loop_factory_->boot_uuid();
731 }
732
James Kuszmaul890c2492022-04-06 14:59:31 -0700733 const EventLoopOptions &options() const { return options_; }
734
Alex Perrycb7da4b2019-08-28 19:35:56 -0700735 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800736 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800737 friend class SimulatedPhasedLoopHandler;
738 friend class SimulatedWatcher;
739
Austin Schuh58646e22021-08-23 23:51:46 -0700740 // We have a condition where we register a startup handler, but then get shut
741 // down before it runs. This results in a segfault if we are lucky, and
742 // corruption otherwise. To handle that, allocate a small object which points
743 // back to us and can be freed when the function is freed. That object can
744 // then be updated when we get destroyed so setup is not called.
745 struct StartupTracker {
746 SimulatedEventLoop *loop = nullptr;
747 bool has_setup = false;
748 };
749
Austin Schuh7d87b672019-12-01 20:23:49 -0800750 void HandleEvent() {
751 while (true) {
752 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
753 break;
754 }
755
756 EventLoopEvent *event = PopEvent();
757 event->HandleEvent();
758 }
759 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800760
Austin Schuh39788ff2019-12-01 18:22:57 -0800761 pid_t GetTid() override { return tid_; }
762
Alex Perrycb7da4b2019-08-28 19:35:56 -0700763 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800764 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700765 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700766 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700767
768 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800769
770 int priority_ = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700771 cpu_set_t affinity_ = DefaultAffinity();
Austin Schuh39788ff2019-12-01 18:22:57 -0800772
Austin Schuh7d87b672019-12-01 20:23:49 -0800773 std::chrono::nanoseconds send_delay_;
774
Austin Schuh217a9782019-12-21 23:02:50 -0800775 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800776 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800777
778 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700779 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800780
781 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700782
783 std::shared_ptr<StartupTracker> startup_tracker_;
James Kuszmaul890c2492022-04-06 14:59:31 -0700784
785 EventLoopOptions options_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700786};
787
Austin Schuh7d87b672019-12-01 20:23:49 -0800788void SimulatedEventLoopFactory::set_send_delay(
789 std::chrono::nanoseconds send_delay) {
790 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700791 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700792 if (node) {
793 for (SimulatedEventLoop *loop : node->event_loops_) {
794 loop->set_send_delay(send_delay_);
795 }
796 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800797 }
798}
799
James Kuszmaulb67409b2022-06-20 16:25:03 -0700800void SimulatedEventLoopFactory::SetRealtimeReplayRate(double replay_rate) {
801 scheduler_scheduler_.SetReplayRate(replay_rate);
802}
803
Alex Perrycb7da4b2019-08-28 19:35:56 -0700804void SimulatedEventLoop::MakeRawWatcher(
805 const Channel *channel,
806 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800807 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800808
Austin Schuh057d29f2021-08-21 23:05:15 -0700809 std::unique_ptr<SimulatedWatcher> shm_watcher =
810 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
811 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800812
813 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700814
Austin Schuh39788ff2019-12-01 18:22:57 -0800815 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700816 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
817 << " " << name() << " MakeRawWatcher(\""
818 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800819
820 // Order of operations gets kinda wonky if we let people make watchers after
821 // running once. If someone has a valid use case, we can reconsider.
822 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700823}
824
825std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
826 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800827 TakeSender(channel);
828
Austin Schuh58646e22021-08-23 23:51:46 -0700829 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
830 << " " << name() << " MakeRawSender(\""
831 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700832 return GetSimulatedChannel(channel)->MakeRawSender(this);
833}
834
835std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
836 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800837 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800838
Austin Schuhca4828c2019-12-28 14:21:35 -0800839 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
840 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
841 << "\", \"type\": \"" << channel->type()->string_view()
842 << "\" } is not able to be fetched on this node. Check your "
843 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800844 }
845
Austin Schuh58646e22021-08-23 23:51:46 -0700846 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
847 << " " << name() << " MakeRawFetcher(\""
848 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800849 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700850}
851
852SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
853 const Channel *channel) {
854 auto it = channels_->find(SimpleChannel(channel));
855 if (it == channels_->end()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700856 it = channels_
857 ->emplace(SimpleChannel(channel),
858 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
859 channel,
Austin Schuhfff9c3a2023-06-16 18:48:23 -0700860 configuration::ChannelStorageDuration(
861 configuration(), channel),
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700862 scheduler_)))
863 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700864 }
865 return it->second.get();
866}
867
Brian Silverman4f4e0612020-08-12 19:54:41 -0700868int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
869 return GetSimulatedChannel(channel)->number_buffers();
870}
871
Austin Schuh7d87b672019-12-01 20:23:49 -0800872SimulatedWatcher::SimulatedWatcher(
873 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800874 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800875 std::function<void(const Context &context, const void *message)> fn)
876 : WatcherState(simulated_event_loop, channel, std::move(fn)),
877 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700878 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800879 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700880 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700881 token_(scheduler_->InvalidToken()) {
882 VLOG(1) << simulated_event_loop_->distributed_now() << " "
883 << NodeName(simulated_event_loop_->node())
884 << simulated_event_loop_->monotonic_now() << " "
885 << simulated_event_loop_->name() << " Watching "
886 << configuration::StrippedChannelToString(channel_);
887}
Austin Schuh7d87b672019-12-01 20:23:49 -0800888
889SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700890 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700891 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700892 << simulated_event_loop_->monotonic_now() << " "
893 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700894 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800895 simulated_event_loop_->RemoveEvent(&event_);
896 if (token_ != scheduler_->InvalidToken()) {
897 scheduler_->Deschedule(token_);
898 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700899 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800900}
901
Austin Schuh8fb315a2020-11-19 22:33:58 -0800902bool SimulatedWatcher::has_run() const {
903 return simulated_event_loop_->has_run();
904}
905
Austin Schuh7d87b672019-12-01 20:23:49 -0800906void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800907 monotonic_clock::time_point event_time =
908 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800909
910 // Messages are queued in order. If we are the first, add ourselves.
911 // Otherwise, don't.
912 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800913 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800914 simulated_event_loop_->AddEvent(&event_);
915
916 DoSchedule(event_time);
917 }
918
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800919 msgs_.emplace_back(std::move(message));
Austin Schuh7d87b672019-12-01 20:23:49 -0800920}
921
Austin Schuhf4b09c72021-12-08 12:04:37 -0800922void SimulatedWatcher::HandleEvent() noexcept {
Austin Schuh7d87b672019-12-01 20:23:49 -0800923 const monotonic_clock::time_point monotonic_now =
924 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700925 VLOG(1) << simulated_event_loop_->distributed_now() << " "
926 << NodeName(simulated_event_loop_->node())
927 << simulated_event_loop_->monotonic_now() << " "
928 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700929 << configuration::StrippedChannelToString(channel_);
930 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
931
Tyler Chatow67ddb032020-01-12 14:30:04 -0800932 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700933 if (simulated_event_loop_->log_impl_) {
934 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800935 }
Austin Schuhad154822019-12-27 15:45:13 -0800936 Context context = msgs_.front()->context;
937
Brian Silverman4f4e0612020-08-12 19:54:41 -0700938 if (channel_->read_method() != ReadMethod::PIN) {
939 context.buffer_index = -1;
940 }
Austin Schuhad154822019-12-27 15:45:13 -0800941 if (context.remote_queue_index == 0xffffffffu) {
942 context.remote_queue_index = context.queue_index;
943 }
Austin Schuh58646e22021-08-23 23:51:46 -0700944 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800945 context.monotonic_remote_time = context.monotonic_event_time;
946 }
Austin Schuh58646e22021-08-23 23:51:46 -0700947 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800948 context.realtime_remote_time = context.realtime_event_time;
949 }
950
Austin Schuhcc6070c2020-10-10 20:25:56 -0700951 {
Austin Schuh65493d62022-08-17 15:10:37 -0700952 ScopedMarkRealtimeRestorer rt(
953 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700954 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh0debde12022-08-17 16:25:17 -0700955 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700956 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800957
958 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700959 if (token_ != scheduler_->InvalidToken()) {
960 scheduler_->Deschedule(token_);
961 token_ = scheduler_->InvalidToken();
962 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800963 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800964 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800965 simulated_event_loop_->AddEvent(&event_);
966
967 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800968 }
969}
970
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800971void SimulatedWatcher::Handle() noexcept {
972 DCHECK(token_ != scheduler_->InvalidToken());
973 token_ = scheduler_->InvalidToken();
974 simulated_event_loop_->HandleEvent();
975}
976
Austin Schuh7d87b672019-12-01 20:23:49 -0800977void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700978 CHECK(token_ == scheduler_->InvalidToken())
979 << ": May not schedule multiple times";
980 token_ = scheduler_->Schedule(
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800981 event_time + simulated_event_loop_->send_delay(), this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800982}
983
984void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700985 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800986 watcher->SetSimulatedChannel(this);
987 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700988}
989
990::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800991 SimulatedEventLoop *event_loop) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700992 CHECK(allow_new_senders_)
993 << ": Attempted to create a new sender on exclusive channel "
994 << configuration::StrippedChannelToString(channel_);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700995 std::optional<ExclusiveSenders> per_channel_option;
996 for (const std::pair<const aos::Channel *, ExclusiveSenders> &per_channel :
997 event_loop->options().per_channel_exclusivity) {
998 if (per_channel.first->name()->string_view() ==
999 channel_->name()->string_view() &&
1000 per_channel.first->type()->string_view() ==
1001 channel_->type()->string_view()) {
1002 CHECK(!per_channel_option.has_value())
1003 << ": Channel " << configuration::StrippedChannelToString(channel_)
1004 << " listed twice in per-channel list.";
1005 per_channel_option = per_channel.second;
1006 }
1007 }
1008 if (!per_channel_option.has_value()) {
1009 // This could just as easily be implemented by setting
1010 // per_channel_option to the global setting when we initialize it, but
1011 // then we'd lose track of whether a given channel appears twice in
1012 // the list.
1013 per_channel_option = event_loop->options().exclusive_senders;
1014 }
1015 if (per_channel_option.value() == ExclusiveSenders::kYes) {
James Kuszmaul890c2492022-04-06 14:59:31 -07001016 CHECK_EQ(0, sender_count_)
1017 << ": Attempted to add an exclusive sender on a channel with existing "
1018 "senders: "
1019 << configuration::StrippedChannelToString(channel_);
1020 allow_new_senders_ = false;
1021 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001022 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
1023}
1024
Austin Schuh39788ff2019-12-01 18:22:57 -08001025::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
1026 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -07001027 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -08001028 ::std::unique_ptr<SimulatedFetcher> fetcher(
1029 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -07001030 fetchers_.push_back(fetcher.get());
James Kuszmaul9776b392023-01-14 14:08:08 -08001031 return fetcher;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001032}
1033
milind1f1dca32021-07-03 13:50:07 -07001034std::optional<uint32_t> SimulatedChannel::Send(
Austin Schuh60e77942022-05-16 17:48:24 -07001035 std::shared_ptr<SimulatedMessage> message,
1036 CheckSentTooFast check_sent_too_fast) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001037 const auto now = scheduler_->monotonic_now();
1038 // Remove times that are greater than or equal to a channel_storage_duration_
1039 // ago
1040 while (!last_times_.empty() &&
1041 (now - last_times_.front() >= channel_storage_duration_)) {
1042 last_times_.pop();
1043 }
1044
1045 // Check that we are not sending messages too fast
James Kuszmaul890c2492022-04-06 14:59:31 -07001046 if (check_sent_too_fast == CheckSentTooFast::kYes &&
1047 static_cast<int>(last_times_.size()) >= queue_size()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001048 return std::nullopt;
1049 }
1050
1051 const std::optional<uint32_t> queue_index = {next_queue_index_.index()};
1052 last_times_.push(now);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001053
milind1f1dca32021-07-03 13:50:07 -07001054 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001055 // Points to the actual data depending on the size set in context. Data may
1056 // allocate more than the actual size of the message, so offset from the back
1057 // of that to get the actual start of the data.
1058 message->context.data =
1059 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -07001060
1061 DCHECK(channel()->has_schema())
1062 << ": Missing schema for channel "
1063 << configuration::StrippedChannelToString(channel());
1064 DCHECK(flatbuffers::Verify(
1065 *channel()->schema(), *channel()->schema()->root_table(),
1066 static_cast<const uint8_t *>(message->context.data),
1067 message->context.size))
1068 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
1069 << channel()->type()->c_str();
1070
Alex Perrycb7da4b2019-08-28 19:35:56 -07001071 next_queue_index_ = next_queue_index_.Increment();
1072
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001073 latest_message_ = std::move(message);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001074 for (SimulatedWatcher *watcher : watchers_) {
1075 if (watcher->has_run()) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001076 watcher->Schedule(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001077 }
1078 }
1079 for (auto &fetcher : fetchers_) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001080 fetcher->Enqueue(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001081 }
Austin Schuhad154822019-12-27 15:45:13 -08001082 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001083}
1084
1085void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
1086 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
1087}
1088
Austin Schuh8fb315a2020-11-19 22:33:58 -08001089SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
1090 SimulatedEventLoop *event_loop)
1091 : RawSender(event_loop, simulated_channel->channel()),
1092 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -07001093 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -08001094 simulated_channel_->CountSenderCreated();
1095}
1096
1097SimulatedSender::~SimulatedSender() {
1098 simulated_channel_->CountSenderDestroyed();
1099}
1100
milind1f1dca32021-07-03 13:50:07 -07001101RawSender::Error SimulatedSender::DoSend(
1102 size_t length, monotonic_clock::time_point monotonic_remote_time,
1103 realtime_clock::time_point realtime_remote_time,
1104 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001105 // The allocations in here are due to infrastructure and don't count in the
1106 // no mallocs in RT code.
1107 ScopedNotRealtime nrt;
1108
Austin Schuh58646e22021-08-23 23:51:46 -07001109 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1110 << NodeName(simulated_event_loop_->node())
1111 << simulated_event_loop_->monotonic_now() << " "
1112 << simulated_event_loop_->name() << " Send "
1113 << configuration::StrippedChannelToString(channel());
1114
Austin Schuh8fb315a2020-11-19 22:33:58 -08001115 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -07001116 message_->context.monotonic_event_time =
1117 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001118 message_->context.monotonic_remote_time = monotonic_remote_time;
1119 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001120 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001121 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001122 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001123 CHECK_LE(length, message_->context.size);
1124 message_->context.size = length;
1125
Austin Schuh60e77942022-05-16 17:48:24 -07001126 const std::optional<uint32_t> optional_queue_index = simulated_channel_->Send(
1127 message_, simulated_event_loop_->options().check_sent_too_fast);
milind1f1dca32021-07-03 13:50:07 -07001128
1129 // Check that we are not sending messages too fast
1130 if (!optional_queue_index) {
1131 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1132 << NodeName(simulated_event_loop_->node())
1133 << simulated_event_loop_->monotonic_now() << " "
1134 << simulated_event_loop_->name()
1135 << "\nMessages were sent too fast:\n"
1136 << "For channel: "
1137 << configuration::CleanedChannelToString(
1138 simulated_channel_->channel())
1139 << '\n'
1140 << "Tried to send more than " << simulated_channel_->queue_size()
1141 << " (queue size) messages in the last "
1142 << std::chrono::duration<double>(
1143 simulated_channel_->channel_storage_duration())
1144 .count()
1145 << " seconds (channel storage duration)"
1146 << "\n\n";
1147 return Error::kMessagesSentTooFast;
1148 }
1149
1150 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001151 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1152 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001153
1154 // Drop the reference to the message so that we allocate a new message for
1155 // next time. Otherwise we will continue to reuse the same memory for all
1156 // messages and corrupt it.
1157 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001158 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001159}
1160
milind1f1dca32021-07-03 13:50:07 -07001161RawSender::Error SimulatedSender::DoSend(
1162 const void *msg, size_t size,
1163 monotonic_clock::time_point monotonic_remote_time,
1164 realtime_clock::time_point realtime_remote_time,
1165 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001166 CHECK_LE(size, this->size())
1167 << ": Attempting to send too big a message on "
1168 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001169
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001170 // Allocates an aligned buffer in which to copy unaligned msg.
1171 auto [span, mutable_span] = MakeSharedSpan(size);
1172 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001173
1174 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001175 // queue_index will be populated in simulated_channel_.
1176 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001177
1178 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001179 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001180}
1181
milind1f1dca32021-07-03 13:50:07 -07001182RawSender::Error SimulatedSender::DoSend(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001183 const SharedSpan data, monotonic_clock::time_point monotonic_remote_time,
milind1f1dca32021-07-03 13:50:07 -07001184 realtime_clock::time_point realtime_remote_time,
1185 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001186 CHECK_LE(data->size(), this->size())
1187 << ": Attempting to send too big a message on "
1188 << configuration::CleanedChannelToString(simulated_channel_->channel());
1189
1190 // Constructs a message sharing the already allocated and aligned message
1191 // data.
1192 message_ = SimulatedMessage::Make(simulated_channel_, data);
1193
1194 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1195 remote_queue_index, source_boot_uuid);
1196}
1197
Austin Schuh39788ff2019-12-01 18:22:57 -08001198SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001199 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1200 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001201 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001202 simulated_event_loop_(simulated_event_loop),
1203 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001204 scheduler_(scheduler),
1205 token_(scheduler_->InvalidToken()) {}
1206
Philipp Schradera6712522023-07-05 20:25:11 -07001207void SimulatedTimerHandler::Schedule(monotonic_clock::time_point base,
1208 monotonic_clock::duration repeat_offset) {
James Kuszmaul86e86c32022-07-21 17:39:47 -07001209 CHECK_GE(base, monotonic_clock::epoch());
Austin Schuh62288252020-11-18 23:26:04 -08001210 // The allocations in here are due to infrastructure and don't count in the no
1211 // mallocs in RT code.
1212 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001213 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001214 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001215 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001216 base_ = base;
1217 repeat_offset_ = repeat_offset;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001218 token_ = scheduler_->Schedule(std::max(base, monotonic_now), this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001219 event_.set_event_time(base_);
1220 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001221 disabled_ = false;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001222}
1223
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001224void SimulatedTimerHandler::Handle() noexcept {
1225 DCHECK(token_ != scheduler_->InvalidToken());
1226 token_ = scheduler_->InvalidToken();
1227 simulated_event_loop_->HandleEvent();
1228}
1229
Austin Schuhf4b09c72021-12-08 12:04:37 -08001230void SimulatedTimerHandler::HandleEvent() noexcept {
Austin Schuh58646e22021-08-23 23:51:46 -07001231 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001232 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001233 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1234 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1235 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001236 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001237 if (simulated_event_loop_->log_impl_) {
1238 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001239 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001240 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001241 {
1242 ScopedNotRealtime nrt;
1243 scheduler_->Deschedule(token_);
1244 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001245 token_ = scheduler_->InvalidToken();
1246 }
Austin Schuh58646e22021-08-23 23:51:46 -07001247 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001248 // Reschedule.
1249 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001250 token_ = scheduler_->Schedule(base_, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001251 event_.set_event_time(base_);
1252 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001253 disabled_ = false;
1254 } else {
1255 disabled_ = true;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001256 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001257 {
Austin Schuh65493d62022-08-17 15:10:37 -07001258 ScopedMarkRealtimeRestorer rt(
1259 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -07001260 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuh0debde12022-08-17 16:25:17 -07001261 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001262 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001263}
1264
Austin Schuh7d87b672019-12-01 20:23:49 -08001265void SimulatedTimerHandler::Disable() {
1266 simulated_event_loop_->RemoveEvent(&event_);
1267 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001268 {
1269 ScopedNotRealtime nrt;
1270 scheduler_->Deschedule(token_);
1271 }
Austin Schuh7d87b672019-12-01 20:23:49 -08001272 token_ = scheduler_->InvalidToken();
1273 }
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001274 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -08001275}
1276
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001277bool SimulatedTimerHandler::IsDisabled() { return disabled_; }
1278
Austin Schuh39788ff2019-12-01 18:22:57 -08001279SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001280 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1281 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001282 const monotonic_clock::duration offset)
1283 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1284 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001285 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001286 scheduler_(scheduler),
1287 token_(scheduler_->InvalidToken()) {}
1288
Austin Schuh7d87b672019-12-01 20:23:49 -08001289SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1290 if (token_ != scheduler_->InvalidToken()) {
1291 scheduler_->Deschedule(token_);
1292 token_ = scheduler_->InvalidToken();
1293 }
1294 simulated_event_loop_->RemoveEvent(&event_);
1295}
1296
Austin Schuhf4b09c72021-12-08 12:04:37 -08001297void SimulatedPhasedLoopHandler::HandleEvent() noexcept {
Austin Schuh39788ff2019-12-01 18:22:57 -08001298 monotonic_clock::time_point monotonic_now =
1299 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001300 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1301 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001302 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001303 if (simulated_event_loop_->log_impl_) {
1304 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001305 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001306
1307 {
Austin Schuh65493d62022-08-17 15:10:37 -07001308 ScopedMarkRealtimeRestorer rt(
1309 simulated_event_loop_->runtime_realtime_priority() > 0);
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001310 Call([monotonic_now]() { return monotonic_now; });
Austin Schuh0debde12022-08-17 16:25:17 -07001311 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001312 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001313}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001314
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001315void SimulatedPhasedLoopHandler::Handle() noexcept {
1316 DCHECK(token_ != scheduler_->InvalidToken());
1317 token_ = scheduler_->InvalidToken();
1318 simulated_event_loop_->HandleEvent();
1319}
1320
Austin Schuh7d87b672019-12-01 20:23:49 -08001321void SimulatedPhasedLoopHandler::Schedule(
1322 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001323 // The allocations in here are due to infrastructure and don't count in the no
1324 // mallocs in RT code.
1325 ScopedNotRealtime nrt;
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001326 simulated_event_loop_->RemoveEvent(&event_);
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001327 if (token_ != scheduler_->InvalidToken()) {
1328 scheduler_->Deschedule(token_);
1329 token_ = scheduler_->InvalidToken();
1330 }
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001331 token_ = scheduler_->Schedule(sleep_time, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001332 event_.set_event_time(sleep_time);
1333 simulated_event_loop_->AddEvent(&event_);
1334}
1335
Alex Perrycb7da4b2019-08-28 19:35:56 -07001336SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1337 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001338 : configuration_(CHECK_NOTNULL(configuration)),
1339 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001340 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001341 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001342 node_factories_.emplace_back(
1343 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001344 }
Austin Schuh898f4972020-01-11 17:21:25 -08001345
Austin Schuh54ffea42023-08-23 13:27:04 -07001346 if (configuration::NodesCount(configuration) > 1u) {
Austin Schuh898f4972020-01-11 17:21:25 -08001347 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1348 }
Austin Schuh15649d62019-12-28 16:36:38 -08001349}
1350
Brian Silvermane1fe2512022-08-14 23:18:50 -07001351SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {
1352 CHECK_EQ(0, exit_handle_count_)
1353 << ": All ExitHandles must be destroyed before the factory";
1354}
Alex Perrycb7da4b2019-08-28 19:35:56 -07001355
Austin Schuhac0771c2020-01-07 18:36:30 -08001356NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001357 std::string_view node) {
1358 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1359}
1360
1361NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001362 const Node *node) {
1363 auto result = std::find_if(
1364 node_factories_.begin(), node_factories_.end(),
1365 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1366 return node_factory->node() == node;
1367 });
1368
1369 CHECK(result != node_factories_.end())
1370 << ": Failed to find node " << FlatbufferToJson(node);
1371
1372 return result->get();
1373}
1374
Austin Schuh87dd3832021-01-01 23:07:31 -08001375void SimulatedEventLoopFactory::SetTimeConverter(
1376 TimeConverter *time_converter) {
1377 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1378 factory->SetTimeConverter(time_converter);
1379 }
Austin Schuh58646e22021-08-23 23:51:46 -07001380 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001381}
1382
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001383::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001384 std::string_view name, const Node *node) {
1385 if (node == nullptr) {
1386 CHECK(!configuration::MultiNode(configuration()))
1387 << ": Can't make a single node event loop in a multi-node world.";
1388 } else {
1389 CHECK(configuration::MultiNode(configuration()))
1390 << ": Can't make a multi-node event loop in a single-node world.";
1391 }
1392 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1393}
1394
Austin Schuh057d29f2021-08-21 23:05:15 -07001395NodeEventLoopFactory::NodeEventLoopFactory(
1396 EventSchedulerScheduler *scheduler_scheduler,
1397 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001398 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1399 factory_(factory),
1400 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001401 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001402 scheduler_.set_started([this]() {
1403 started_ = true;
1404 for (SimulatedEventLoop *event_loop : event_loops_) {
1405 event_loop->SetIsRunning(true);
1406 }
1407 });
Austin Schuhe33c08d2022-02-03 18:15:21 -08001408 scheduler_.set_stopped([this]() {
1409 for (SimulatedEventLoop *event_loop : event_loops_) {
1410 event_loop->SetIsRunning(false);
1411 }
1412 });
Austin Schuh58646e22021-08-23 23:51:46 -07001413 scheduler_.set_on_shutdown([this]() {
1414 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1415 << monotonic_now() << " Shutting down node.";
1416 Shutdown();
1417 ScheduleStartup();
1418 });
1419 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001420}
1421
1422NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001423 if (started_) {
1424 for (std::function<void()> &fn : on_shutdown_) {
1425 fn();
1426 }
1427
1428 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1429 << monotonic_now() << " Shutting down applications.";
1430 applications_.clear();
1431 started_ = false;
1432 }
1433
1434 if (event_loops_.size() != 0u) {
1435 for (SimulatedEventLoop *event_loop : event_loops_) {
1436 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1437 << monotonic_now() << " Event loop '" << event_loop->name()
1438 << "' failed to shut down";
1439 }
1440 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001441 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1442}
1443
Austin Schuh58646e22021-08-23 23:51:46 -07001444void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001445 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001446 << ": Can only register OnStartup handlers when not running.";
1447 on_startup_.emplace_back(std::move(fn));
1448 if (started_) {
1449 size_t on_startup_index = on_startup_.size() - 1;
1450 scheduler_.ScheduleOnStartup(
1451 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1452 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001453}
1454
Austin Schuh58646e22021-08-23 23:51:46 -07001455void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1456 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001457}
Austin Schuh057d29f2021-08-21 23:05:15 -07001458
Austin Schuh58646e22021-08-23 23:51:46 -07001459void NodeEventLoopFactory::ScheduleStartup() {
1460 scheduler_.ScheduleOnStartup([this]() {
1461 UUID next_uuid = scheduler_.boot_uuid();
1462 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001463 CHECK_EQ(boot_uuid_, UUID::Zero())
1464 << ": Boot UUID changed without restarting. Did TimeConverter "
1465 "change the boot UUID without signaling a restart, or did you "
1466 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001467 boot_uuid_ = next_uuid;
1468 }
1469 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1470 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1471 Startup();
1472 });
1473}
1474
1475void NodeEventLoopFactory::Startup() {
1476 CHECK(!started_);
1477 for (size_t i = 0; i < on_startup_.size(); ++i) {
1478 on_startup_[i]();
1479 }
1480}
1481
1482void NodeEventLoopFactory::Shutdown() {
1483 for (SimulatedEventLoop *event_loop : event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001484 CHECK(!event_loop->is_running());
Austin Schuh58646e22021-08-23 23:51:46 -07001485 }
1486
1487 CHECK(started_);
1488 started_ = false;
1489 for (std::function<void()> &fn : on_shutdown_) {
1490 fn();
1491 }
1492
1493 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1494 << monotonic_now() << " Shutting down applications.";
1495 applications_.clear();
1496
1497 if (event_loops_.size() != 0u) {
1498 for (SimulatedEventLoop *event_loop : event_loops_) {
1499 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1500 << monotonic_now() << " Event loop '" << event_loop->name()
1501 << "' failed to shut down";
1502 }
1503 }
1504 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1505 boot_uuid_ = UUID::Zero();
1506
1507 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001508}
1509
Alex Perrycb7da4b2019-08-28 19:35:56 -07001510void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001511 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001512 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001513 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1514 if (node) {
1515 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001516 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001517 }
1518 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001519 }
1520}
1521
1522void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001523 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001524 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001525 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1526 if (node) {
1527 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001528 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001529 }
1530 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001531 }
1532}
1533
Austin Schuh87dd3832021-01-01 23:07:31 -08001534void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001535
Brian Silvermane1fe2512022-08-14 23:18:50 -07001536std::unique_ptr<ExitHandle> SimulatedEventLoopFactory::MakeExitHandle() {
1537 return std::make_unique<SimulatedFactoryExitHandle>(this);
1538}
1539
Austin Schuh6f3babe2020-01-26 20:34:50 -08001540void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001541 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001542 bridge_->DisableForwarding(channel);
1543}
1544
Austin Schuh4c3b9702020-08-30 11:34:55 -07001545void SimulatedEventLoopFactory::DisableStatistics() {
1546 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
James Kuszmaul94ca5132022-07-19 09:11:08 -07001547 bridge_->DisableStatistics(
1548 message_bridge::SimulatedMessageBridge::DestroySenders::kNo);
1549}
1550
1551void SimulatedEventLoopFactory::PermanentlyDisableStatistics() {
1552 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1553 bridge_->DisableStatistics(
1554 message_bridge::SimulatedMessageBridge::DestroySenders::kYes);
Austin Schuh4c3b9702020-08-30 11:34:55 -07001555}
1556
Austin Schuh48205e62021-11-12 14:13:18 -08001557void SimulatedEventLoopFactory::EnableStatistics() {
1558 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1559 bridge_->EnableStatistics();
1560}
1561
Austin Schuh2928ebe2021-02-07 22:10:27 -08001562void SimulatedEventLoopFactory::SkipTimingReport() {
1563 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001564
1565 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1566 if (node) {
1567 node->SkipTimingReport();
1568 }
1569 }
1570}
1571
1572void NodeEventLoopFactory::SkipTimingReport() {
1573 for (SimulatedEventLoop *event_loop : event_loops_) {
1574 event_loop->SkipTimingReport();
1575 }
1576 skip_timing_report_ = true;
1577}
1578
1579void NodeEventLoopFactory::EnableStatistics() {
1580 CHECK(factory_->bridge_)
1581 << ": Can't enable statistics without a message bridge.";
1582 factory_->bridge_->EnableStatistics(node_);
1583}
1584
1585void NodeEventLoopFactory::DisableStatistics() {
1586 CHECK(factory_->bridge_)
1587 << ": Can't disable statistics without a message bridge.";
1588 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001589}
1590
Austin Schuh58646e22021-08-23 23:51:46 -07001591::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
James Kuszmaul890c2492022-04-06 14:59:31 -07001592 std::string_view name, EventLoopOptions options) {
Austin Schuh58646e22021-08-23 23:51:46 -07001593 CHECK(!scheduler_.is_running() || !started_)
1594 << ": Can't create an event loop while running";
1595
1596 pid_t tid = tid_;
1597 ++tid_;
1598 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1599 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
James Kuszmaul890c2492022-04-06 14:59:31 -07001600 node_, tid, options));
Austin Schuh58646e22021-08-23 23:51:46 -07001601 result->set_name(name);
1602 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001603 if (skip_timing_report_) {
1604 result->SkipTimingReport();
1605 }
Austin Schuh58646e22021-08-23 23:51:46 -07001606
1607 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1608 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
James Kuszmaul9776b392023-01-14 14:08:08 -08001609 return result;
Austin Schuh58646e22021-08-23 23:51:46 -07001610}
1611
Austin Schuhe33c08d2022-02-03 18:15:21 -08001612void SimulatedEventLoopFactory::AllowApplicationCreationDuring(
1613 std::function<void()> fn) {
1614 scheduler_scheduler_.TemporarilyStopAndRun(std::move(fn));
1615}
1616
Austin Schuh58646e22021-08-23 23:51:46 -07001617void NodeEventLoopFactory::Disconnect(const Node *other) {
1618 factory_->bridge_->Disconnect(node_, other);
1619}
1620
1621void NodeEventLoopFactory::Connect(const Node *other) {
1622 factory_->bridge_->Connect(node_, other);
1623}
1624
Alex Perrycb7da4b2019-08-28 19:35:56 -07001625} // namespace aos