blob: b17e5ffc9dfbdfadafe559eeb647f49879a428d6 [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) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700152 available_buffer_indices_.resize(number_buffers());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700153 for (int i = 0; i < number_buffers(); ++i) {
Brian Silvermanbc596c62021-10-15 14:04:54 -0700154 available_buffer_indices_[i] = i;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700155 }
156 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700157
Brian Silverman661eb8d2020-08-12 19:41:01 -0700158 ~SimulatedChannel() {
159 latest_message_.reset();
160 CHECK_EQ(static_cast<size_t>(number_buffers()),
161 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800162 CHECK_EQ(0u, fetchers_.size())
163 << configuration::StrippedChannelToString(channel());
164 CHECK_EQ(0u, watchers_.size())
165 << configuration::StrippedChannelToString(channel());
166 CHECK_EQ(0, sender_count_)
167 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700168 }
169
170 // The number of messages we pretend to have in the queue.
171 int queue_size() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700172 return configuration::QueueSize(channel()->frequency(),
173 channel_storage_duration_);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700174 }
175
milind1f1dca32021-07-03 13:50:07 -0700176 std::chrono::nanoseconds channel_storage_duration() const {
177 return channel_storage_duration_;
178 }
179
Brian Silverman661eb8d2020-08-12 19:41:01 -0700180 // The number of extra buffers (beyond the queue) we pretend to have.
181 int number_scratch_buffers() const {
Austin Schuhfb37c612022-08-11 15:24:51 -0700182 return configuration::QueueScratchBufferSize(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700183 }
184
185 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
186
187 int GetBufferIndex() {
188 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
189 const int result = available_buffer_indices_.back();
190 available_buffer_indices_.pop_back();
191 return result;
192 }
193
194 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700195 // This extra checking has a large performance hit with sanitizers that
196 // track memory accesses, so just skip it.
197#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700198 DCHECK(std::find(available_buffer_indices_.begin(),
199 available_buffer_indices_.end(),
200 i) == available_buffer_indices_.end())
201 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800202#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700203 available_buffer_indices_.push_back(i);
204 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700205
206 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800207 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700208
209 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800210 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700211
212 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800213 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800214
Austin Schuh7d87b672019-12-01 20:23:49 -0800215 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
217 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700218
Austin Schuhad154822019-12-27 15:45:13 -0800219 // Sends the message to all the connected receivers and fetchers. Returns the
milind1f1dca32021-07-03 13:50:07 -0700220 // sent queue index, or std::nullopt if messages were sent too fast.
James Kuszmaul890c2492022-04-06 14:59:31 -0700221 std::optional<uint32_t> Send(std::shared_ptr<SimulatedMessage> message,
222 CheckSentTooFast check_sent_too_fast);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700223
224 // Unregisters a fetcher.
225 void UnregisterFetcher(SimulatedFetcher *fetcher);
226
227 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
228
Austin Schuh39788ff2019-12-01 18:22:57 -0800229 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700230
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800231 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800232 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700233 }
234
Austin Schuh39788ff2019-12-01 18:22:57 -0800235 const Channel *channel() const { return channel_; }
236
Austin Schuhe516ab02020-05-06 21:37:04 -0700237 void CountSenderCreated() {
238 if (sender_count_ >= channel()->num_senders()) {
239 LOG(FATAL) << "Failed to create sender on "
240 << configuration::CleanedChannelToString(channel())
241 << ", too many senders.";
242 }
Austin Schuhfb37c612022-08-11 15:24:51 -0700243 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700244 ++sender_count_;
245 }
Brian Silverman77162972020-08-12 19:52:40 -0700246
Austin Schuhe516ab02020-05-06 21:37:04 -0700247 void CountSenderDestroyed() {
248 --sender_count_;
249 CHECK_GE(sender_count_, 0);
James Kuszmaul890c2492022-04-06 14:59:31 -0700250 if (sender_count_ == 0) {
251 allow_new_senders_ = true;
252 }
Austin Schuhe516ab02020-05-06 21:37:04 -0700253 }
254
Alex Perrycb7da4b2019-08-28 19:35:56 -0700255 private:
Brian Silverman77162972020-08-12 19:52:40 -0700256 void CheckBufferCount() {
257 int reader_count = 0;
258 if (channel()->read_method() == ReadMethod::PIN) {
259 reader_count = watchers_.size() + fetchers_.size();
260 }
261 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
262 }
263
264 void CheckReaderCount() {
265 if (channel()->read_method() != ReadMethod::PIN) {
266 return;
267 }
268 CheckBufferCount();
269 const int reader_count = watchers_.size() + fetchers_.size();
270 if (reader_count >= channel()->num_readers()) {
271 LOG(FATAL) << "Failed to create reader on "
272 << configuration::CleanedChannelToString(channel())
273 << ", too many readers.";
274 }
275 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700276
277 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700278 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700279
280 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800281 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700282
283 // List of all fetchers.
284 ::std::vector<SimulatedFetcher *> fetchers_;
285 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700286
287 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700288
289 int sender_count_ = 0;
James Kuszmaul890c2492022-04-06 14:59:31 -0700290 // Used to track when an exclusive sender has been created (e.g., for log
291 // replay) and we want to prevent new senders from being accidentally created.
292 bool allow_new_senders_ = true;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700293
294 std::vector<uint16_t> available_buffer_indices_;
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700295
296 const EventScheduler *scheduler_;
297
298 // Queue of all the message send times in the last channel_storage_duration_
299 std::queue<monotonic_clock::time_point> last_times_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700300};
301
302namespace {
303
Brian Silverman661eb8d2020-08-12 19:41:01 -0700304std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
Austin Schuhe0ab4de2023-05-03 08:05:08 -0700305 SimulatedChannel *channel, SharedSpan data) {
Austin Schuh62288252020-11-18 23:26:04 -0800306 // The allocations in here are due to infrastructure and don't count in the no
307 // mallocs in RT code.
308 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700310 auto message = std::make_shared<SimulatedMessage>(channel);
311 message->context.size = data->size();
312 message->context.data = data->data();
313 message->data = std::move(data);
314
315 return message;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700316}
317
318SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
319 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700320 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700321}
322
323SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700324 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700325}
326
327class SimulatedSender : public RawSender {
328 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800329 SimulatedSender(SimulatedChannel *simulated_channel,
330 SimulatedEventLoop *event_loop);
331 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700332
333 void *data() override {
334 if (!message_) {
Austin Schuh9b1d6282022-06-10 17:03:21 -0700335 // This API is safe to use in a RT context on a RT system. So annotate it
336 // accordingly.
337 ScopedNotRealtime nrt;
338
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700339 auto [span, mutable_span] =
340 MakeSharedSpan(simulated_channel_->max_size());
341 message_ = SimulatedMessage::Make(simulated_channel_, span);
342 message_->mutable_data = mutable_span;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700344 CHECK(message_->is_mutable());
345 return message_->mutable_data.data();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700346 }
347
348 size_t size() override { return simulated_channel_->max_size(); }
349
milind1f1dca32021-07-03 13:50:07 -0700350 Error DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
351 realtime_clock::time_point realtime_remote_time,
352 uint32_t remote_queue_index,
353 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354
milind1f1dca32021-07-03 13:50:07 -0700355 Error DoSend(const void *msg, size_t size,
356 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 SharedSpan data,
362 aos::monotonic_clock::time_point monotonic_remote_time,
363 aos::realtime_clock::time_point realtime_remote_time,
364 uint32_t remote_queue_index,
365 const UUID &source_boot_uuid) override;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700366
Brian Silverman4f4e0612020-08-12 19:54:41 -0700367 int buffer_index() override {
368 // First, ensure message_ is allocated.
369 data();
370 return message_->context.buffer_index;
371 }
372
Alex Perrycb7da4b2019-08-28 19:35:56 -0700373 private:
374 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700375 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376
377 std::shared_ptr<SimulatedMessage> message_;
378};
379} // namespace
380
381class SimulatedFetcher : public RawFetcher {
382 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800383 explicit SimulatedFetcher(EventLoop *event_loop,
384 SimulatedChannel *simulated_channel)
385 : RawFetcher(event_loop, simulated_channel->channel()),
386 simulated_channel_(simulated_channel) {}
387 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700388
Austin Schuh39788ff2019-12-01 18:22:57 -0800389 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800390 // The allocations in here are due to infrastructure and don't count in the
391 // no mallocs in RT code.
392 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800393 if (msgs_.size() == 0) {
394 return std::make_pair(false, monotonic_clock::min_time);
395 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700396
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700397 CHECK(!fell_behind_) << ": Got behind on "
398 << configuration::StrippedChannelToString(
399 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700400
Alex Perrycb7da4b2019-08-28 19:35:56 -0700401 SetMsg(msgs_.front());
402 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800403 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700404 }
405
Austin Schuh39788ff2019-12-01 18:22:57 -0800406 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800407 // The allocations in here are due to infrastructure and don't count in the
408 // no mallocs in RT code.
409 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700410 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800411 // TODO(austin): Can we just do this logic unconditionally? It is a lot
412 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800413 if (!msg_ && simulated_channel_->latest_message()) {
414 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800415 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800417 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700418 }
419 }
420
421 // We've had a message enqueued, so we don't need to go looking for the
422 // latest message from before we started.
423 SetMsg(msgs_.back());
424 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700425 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800426 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700427 }
428
429 private:
430 friend class SimulatedChannel;
431
432 // Updates the state inside RawFetcher to point to the data in msg_.
433 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800434 msg_ = std::move(msg);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700436 if (channel()->read_method() != ReadMethod::PIN) {
437 context_.buffer_index = -1;
438 }
Austin Schuhad154822019-12-27 15:45:13 -0800439 if (context_.remote_queue_index == 0xffffffffu) {
440 context_.remote_queue_index = context_.queue_index;
441 }
Austin Schuh58646e22021-08-23 23:51:46 -0700442 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800443 context_.monotonic_remote_time = context_.monotonic_event_time;
444 }
Austin Schuh58646e22021-08-23 23:51:46 -0700445 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800446 context_.realtime_remote_time = context_.realtime_event_time;
447 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 }
449
450 // Internal method for Simulation to add a message to the buffer.
451 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800452 msgs_.emplace_back(std::move(buffer));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700453 if (fell_behind_ ||
454 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
455 fell_behind_ = true;
456 // Might as well empty out all the intermediate messages now.
457 while (msgs_.size() > 1) {
458 msgs_.pop_front();
459 }
460 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700461 }
462
Austin Schuhac0771c2020-01-07 18:36:30 -0800463 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700464 std::shared_ptr<SimulatedMessage> msg_;
465
466 // Messages queued up but not in use.
467 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700468
469 // Whether we're currently "behind", which means a FetchNext call will fail.
470 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700471};
472
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800473class SimulatedTimerHandler : public TimerHandler,
474 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700475 public:
476 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800477 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800478 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800479 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480
Philipp Schradera6712522023-07-05 20:25:11 -0700481 void Schedule(monotonic_clock::time_point base,
482 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483
Austin Schuhf4b09c72021-12-08 12:04:37 -0800484 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700485
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800486 void Handle() noexcept override;
487
Austin Schuh7d87b672019-12-01 20:23:49 -0800488 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700490 bool IsDisabled() override;
491
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800493 SimulatedEventLoop *simulated_event_loop_;
494 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700495 EventScheduler *scheduler_;
496 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800497
Alex Perrycb7da4b2019-08-28 19:35:56 -0700498 monotonic_clock::time_point base_;
499 monotonic_clock::duration repeat_offset_;
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700500 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700501};
502
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800503class SimulatedPhasedLoopHandler : public PhasedLoopHandler,
504 public EventScheduler::Event {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700505 public:
506 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800507 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700508 ::std::function<void(int)> fn,
509 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800510 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800511 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512
Austin Schuhf4b09c72021-12-08 12:04:37 -0800513 void HandleEvent() noexcept;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514
Austin Schuh7d87b672019-12-01 20:23:49 -0800515 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700516
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800517 void Handle() noexcept override;
518
Alex Perrycb7da4b2019-08-28 19:35:56 -0700519 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800520 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800521 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700522
Austin Schuh39788ff2019-12-01 18:22:57 -0800523 EventScheduler *scheduler_;
524 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525};
526
527class SimulatedEventLoop : public EventLoop {
528 public:
529 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700530 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
532 *channels,
533 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700534 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
James Kuszmaul890c2492022-04-06 14:59:31 -0700535 pid_t tid, EventLoopOptions options)
Austin Schuh83c7f702021-01-19 22:36:29 -0800536 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800538 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700539 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700540 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800541 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700542 tid_(tid),
James Kuszmaul890c2492022-04-06 14:59:31 -0700543 startup_tracker_(std::make_shared<StartupTracker>()),
544 options_(options) {
Austin Schuh0debde12022-08-17 16:25:17 -0700545 ClearContext();
Austin Schuh58646e22021-08-23 23:51:46 -0700546 startup_tracker_->loop = this;
547 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
548 if (startup_tracker->loop) {
549 startup_tracker->loop->Setup();
550 startup_tracker->has_setup = true;
551 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700552 });
553
554 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555 }
Austin Schuh58646e22021-08-23 23:51:46 -0700556
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800558 // Trigger any remaining senders or fetchers to be cleared before destroying
559 // the event loop so the book keeping matches.
560 timing_report_sender_.reset();
561
562 // Force everything with a registered fd with epoll to be destroyed now.
563 timers_.clear();
564 phased_loops_.clear();
565 watchers_.clear();
566
Austin Schuh58646e22021-08-23 23:51:46 -0700567 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700568 if (*it == this) {
569 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570 break;
571 }
572 }
Austin Schuh58646e22021-08-23 23:51:46 -0700573 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
574 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
575 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700576 }
577
Austin Schuh057d29f2021-08-21 23:05:15 -0700578 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700579 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
580 << monotonic_now() << " " << name_ << " set_is_running(" << running
581 << ")";
582 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700583
584 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700585 if (running) {
586 has_run_ = true;
587 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700588 }
589
Austin Schuh8fb315a2020-11-19 22:33:58 -0800590 bool has_run() const { return has_run_; }
591
Austin Schuh7d87b672019-12-01 20:23:49 -0800592 std::chrono::nanoseconds send_delay() const { return send_delay_; }
593 void set_send_delay(std::chrono::nanoseconds send_delay) {
594 send_delay_ = send_delay;
595 }
596
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800597 monotonic_clock::time_point monotonic_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800598 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700599 }
600
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800601 realtime_clock::time_point realtime_now() const override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800602 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700603 }
604
Austin Schuh58646e22021-08-23 23:51:46 -0700605 distributed_clock::time_point distributed_now() {
606 return scheduler_->distributed_now();
607 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700608
Austin Schuh58646e22021-08-23 23:51:46 -0700609 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
610
611 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700612
613 void MakeRawWatcher(
614 const Channel *channel,
615 ::std::function<void(const Context &context, const void *message)>
616 watcher) override;
617
618 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800619 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800620 return NewTimer(::std::unique_ptr<TimerHandler>(
621 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700622 }
623
624 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
625 const monotonic_clock::duration interval,
626 const monotonic_clock::duration offset =
627 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800628 return NewPhasedLoop(
629 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
630 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700631 }
632
633 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800634 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700635 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800636 logging::ScopedLogRestorer prev_logger;
637 if (log_impl_) {
638 prev_logger.Swap(log_impl_);
639 }
Austin Schuh65493d62022-08-17 15:10:37 -0700640 ScopedMarkRealtimeRestorer rt(runtime_realtime_priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700641 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700642 on_run();
Austin Schuh0debde12022-08-17 16:25:17 -0700643 ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700644 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645 }
646
Austin Schuh217a9782019-12-21 23:02:50 -0800647 const Node *node() const override { return node_; }
648
James Kuszmaul3ae42262019-11-08 12:33:41 -0800649 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700650 name_ = std::string(name);
651 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800652 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700653
654 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
655
Austin Schuh39788ff2019-12-01 18:22:57 -0800656 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700657 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800658 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700659 }
660
Austin Schuh65493d62022-08-17 15:10:37 -0700661 int runtime_realtime_priority() const override { return priority_; }
662 const cpu_set_t &runtime_affinity() const override { return affinity_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800663
Austin Schuh65493d62022-08-17 15:10:37 -0700664 void SetRuntimeAffinity(const cpu_set_t &affinity) override {
Brian Silverman6a54ff32020-04-28 16:41:39 -0700665 CHECK(!is_running()) << ": Cannot set affinity while running.";
Austin Schuh65493d62022-08-17 15:10:37 -0700666 affinity_ = affinity;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700667 }
668
Tyler Chatow67ddb032020-01-12 14:30:04 -0800669 void Setup() {
670 MaybeScheduleTimingReports();
671 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800672 log_sender_.Initialize(&name_,
673 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700674 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800675 }
676 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800677
Brian Silverman4f4e0612020-08-12 19:54:41 -0700678 int NumberBuffers(const Channel *channel) override;
679
Austin Schuh83c7f702021-01-19 22:36:29 -0800680 const UUID &boot_uuid() const override {
681 return node_event_loop_factory_->boot_uuid();
682 }
683
James Kuszmaul890c2492022-04-06 14:59:31 -0700684 const EventLoopOptions &options() const { return options_; }
685
Alex Perrycb7da4b2019-08-28 19:35:56 -0700686 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800687 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800688 friend class SimulatedPhasedLoopHandler;
689 friend class SimulatedWatcher;
690
Austin Schuh58646e22021-08-23 23:51:46 -0700691 // We have a condition where we register a startup handler, but then get shut
692 // down before it runs. This results in a segfault if we are lucky, and
693 // corruption otherwise. To handle that, allocate a small object which points
694 // back to us and can be freed when the function is freed. That object can
695 // then be updated when we get destroyed so setup is not called.
696 struct StartupTracker {
697 SimulatedEventLoop *loop = nullptr;
698 bool has_setup = false;
699 };
700
Austin Schuh7d87b672019-12-01 20:23:49 -0800701 void HandleEvent() {
702 while (true) {
703 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
704 break;
705 }
706
707 EventLoopEvent *event = PopEvent();
708 event->HandleEvent();
709 }
710 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800711
Austin Schuh39788ff2019-12-01 18:22:57 -0800712 pid_t GetTid() override { return tid_; }
713
Alex Perrycb7da4b2019-08-28 19:35:56 -0700714 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800715 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700716 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700717 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700718
719 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800720
721 int priority_ = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700722 cpu_set_t affinity_ = DefaultAffinity();
Austin Schuh39788ff2019-12-01 18:22:57 -0800723
Austin Schuh7d87b672019-12-01 20:23:49 -0800724 std::chrono::nanoseconds send_delay_;
725
Austin Schuh217a9782019-12-21 23:02:50 -0800726 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800727 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800728
729 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700730 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800731
732 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700733
734 std::shared_ptr<StartupTracker> startup_tracker_;
James Kuszmaul890c2492022-04-06 14:59:31 -0700735
736 EventLoopOptions options_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700737};
738
Austin Schuh7d87b672019-12-01 20:23:49 -0800739void SimulatedEventLoopFactory::set_send_delay(
740 std::chrono::nanoseconds send_delay) {
741 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700742 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700743 if (node) {
744 for (SimulatedEventLoop *loop : node->event_loops_) {
745 loop->set_send_delay(send_delay_);
746 }
747 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800748 }
749}
750
James Kuszmaulb67409b2022-06-20 16:25:03 -0700751void SimulatedEventLoopFactory::SetRealtimeReplayRate(double replay_rate) {
752 scheduler_scheduler_.SetReplayRate(replay_rate);
753}
754
Alex Perrycb7da4b2019-08-28 19:35:56 -0700755void SimulatedEventLoop::MakeRawWatcher(
756 const Channel *channel,
757 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800758 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800759
Austin Schuh057d29f2021-08-21 23:05:15 -0700760 std::unique_ptr<SimulatedWatcher> shm_watcher =
761 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
762 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800763
764 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700765
Austin Schuh39788ff2019-12-01 18:22:57 -0800766 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700767 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
768 << " " << name() << " MakeRawWatcher(\""
769 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800770
771 // Order of operations gets kinda wonky if we let people make watchers after
772 // running once. If someone has a valid use case, we can reconsider.
773 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700774}
775
776std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
777 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800778 TakeSender(channel);
779
Austin Schuh58646e22021-08-23 23:51:46 -0700780 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
781 << " " << name() << " MakeRawSender(\""
782 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700783 return GetSimulatedChannel(channel)->MakeRawSender(this);
784}
785
786std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
787 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800788 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800789
Austin Schuhca4828c2019-12-28 14:21:35 -0800790 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
791 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
792 << "\", \"type\": \"" << channel->type()->string_view()
793 << "\" } is not able to be fetched on this node. Check your "
794 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800795 }
796
Austin Schuh58646e22021-08-23 23:51:46 -0700797 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
798 << " " << name() << " MakeRawFetcher(\""
799 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800800 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700801}
802
803SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
804 const Channel *channel) {
805 auto it = channels_->find(SimpleChannel(channel));
806 if (it == channels_->end()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700807 it = channels_
808 ->emplace(SimpleChannel(channel),
809 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
810 channel,
811 std::chrono::nanoseconds(
812 configuration()->channel_storage_duration()),
813 scheduler_)))
814 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700815 }
816 return it->second.get();
817}
818
Brian Silverman4f4e0612020-08-12 19:54:41 -0700819int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
820 return GetSimulatedChannel(channel)->number_buffers();
821}
822
Austin Schuh7d87b672019-12-01 20:23:49 -0800823SimulatedWatcher::SimulatedWatcher(
824 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800825 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800826 std::function<void(const Context &context, const void *message)> fn)
827 : WatcherState(simulated_event_loop, channel, std::move(fn)),
828 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700829 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800830 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700831 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700832 token_(scheduler_->InvalidToken()) {
833 VLOG(1) << simulated_event_loop_->distributed_now() << " "
834 << NodeName(simulated_event_loop_->node())
835 << simulated_event_loop_->monotonic_now() << " "
836 << simulated_event_loop_->name() << " Watching "
837 << configuration::StrippedChannelToString(channel_);
838}
Austin Schuh7d87b672019-12-01 20:23:49 -0800839
840SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700841 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700842 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700843 << simulated_event_loop_->monotonic_now() << " "
844 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700845 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800846 simulated_event_loop_->RemoveEvent(&event_);
847 if (token_ != scheduler_->InvalidToken()) {
848 scheduler_->Deschedule(token_);
849 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700850 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800851}
852
Austin Schuh8fb315a2020-11-19 22:33:58 -0800853bool SimulatedWatcher::has_run() const {
854 return simulated_event_loop_->has_run();
855}
856
Austin Schuh7d87b672019-12-01 20:23:49 -0800857void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800858 monotonic_clock::time_point event_time =
859 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800860
861 // Messages are queued in order. If we are the first, add ourselves.
862 // Otherwise, don't.
863 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800864 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800865 simulated_event_loop_->AddEvent(&event_);
866
867 DoSchedule(event_time);
868 }
869
Austin Schuhe6f4c8d2021-12-11 12:36:06 -0800870 msgs_.emplace_back(std::move(message));
Austin Schuh7d87b672019-12-01 20:23:49 -0800871}
872
Austin Schuhf4b09c72021-12-08 12:04:37 -0800873void SimulatedWatcher::HandleEvent() noexcept {
Austin Schuh7d87b672019-12-01 20:23:49 -0800874 const monotonic_clock::time_point monotonic_now =
875 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700876 VLOG(1) << simulated_event_loop_->distributed_now() << " "
877 << NodeName(simulated_event_loop_->node())
878 << simulated_event_loop_->monotonic_now() << " "
879 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700880 << configuration::StrippedChannelToString(channel_);
881 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
882
Tyler Chatow67ddb032020-01-12 14:30:04 -0800883 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700884 if (simulated_event_loop_->log_impl_) {
885 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800886 }
Austin Schuhad154822019-12-27 15:45:13 -0800887 Context context = msgs_.front()->context;
888
Brian Silverman4f4e0612020-08-12 19:54:41 -0700889 if (channel_->read_method() != ReadMethod::PIN) {
890 context.buffer_index = -1;
891 }
Austin Schuhad154822019-12-27 15:45:13 -0800892 if (context.remote_queue_index == 0xffffffffu) {
893 context.remote_queue_index = context.queue_index;
894 }
Austin Schuh58646e22021-08-23 23:51:46 -0700895 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800896 context.monotonic_remote_time = context.monotonic_event_time;
897 }
Austin Schuh58646e22021-08-23 23:51:46 -0700898 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800899 context.realtime_remote_time = context.realtime_event_time;
900 }
901
Austin Schuhcc6070c2020-10-10 20:25:56 -0700902 {
Austin Schuh65493d62022-08-17 15:10:37 -0700903 ScopedMarkRealtimeRestorer rt(
904 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700905 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh0debde12022-08-17 16:25:17 -0700906 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -0700907 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800908
909 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700910 if (token_ != scheduler_->InvalidToken()) {
911 scheduler_->Deschedule(token_);
912 token_ = scheduler_->InvalidToken();
913 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800914 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800915 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800916 simulated_event_loop_->AddEvent(&event_);
917
918 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800919 }
920}
921
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800922void SimulatedWatcher::Handle() noexcept {
923 DCHECK(token_ != scheduler_->InvalidToken());
924 token_ = scheduler_->InvalidToken();
925 simulated_event_loop_->HandleEvent();
926}
927
Austin Schuh7d87b672019-12-01 20:23:49 -0800928void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700929 CHECK(token_ == scheduler_->InvalidToken())
930 << ": May not schedule multiple times";
931 token_ = scheduler_->Schedule(
Austin Schuhef8f1ae2021-12-11 12:35:05 -0800932 event_time + simulated_event_loop_->send_delay(), this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800933}
934
935void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700936 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800937 watcher->SetSimulatedChannel(this);
938 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700939}
940
941::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800942 SimulatedEventLoop *event_loop) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700943 CHECK(allow_new_senders_)
944 << ": Attempted to create a new sender on exclusive channel "
945 << configuration::StrippedChannelToString(channel_);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700946 std::optional<ExclusiveSenders> per_channel_option;
947 for (const std::pair<const aos::Channel *, ExclusiveSenders> &per_channel :
948 event_loop->options().per_channel_exclusivity) {
949 if (per_channel.first->name()->string_view() ==
950 channel_->name()->string_view() &&
951 per_channel.first->type()->string_view() ==
952 channel_->type()->string_view()) {
953 CHECK(!per_channel_option.has_value())
954 << ": Channel " << configuration::StrippedChannelToString(channel_)
955 << " listed twice in per-channel list.";
956 per_channel_option = per_channel.second;
957 }
958 }
959 if (!per_channel_option.has_value()) {
960 // This could just as easily be implemented by setting
961 // per_channel_option to the global setting when we initialize it, but
962 // then we'd lose track of whether a given channel appears twice in
963 // the list.
964 per_channel_option = event_loop->options().exclusive_senders;
965 }
966 if (per_channel_option.value() == ExclusiveSenders::kYes) {
James Kuszmaul890c2492022-04-06 14:59:31 -0700967 CHECK_EQ(0, sender_count_)
968 << ": Attempted to add an exclusive sender on a channel with existing "
969 "senders: "
970 << configuration::StrippedChannelToString(channel_);
971 allow_new_senders_ = false;
972 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700973 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
974}
975
Austin Schuh39788ff2019-12-01 18:22:57 -0800976::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
977 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700978 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800979 ::std::unique_ptr<SimulatedFetcher> fetcher(
980 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700981 fetchers_.push_back(fetcher.get());
James Kuszmaul9776b392023-01-14 14:08:08 -0800982 return fetcher;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700983}
984
milind1f1dca32021-07-03 13:50:07 -0700985std::optional<uint32_t> SimulatedChannel::Send(
Austin Schuh60e77942022-05-16 17:48:24 -0700986 std::shared_ptr<SimulatedMessage> message,
987 CheckSentTooFast check_sent_too_fast) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700988 const auto now = scheduler_->monotonic_now();
989 // Remove times that are greater than or equal to a channel_storage_duration_
990 // ago
991 while (!last_times_.empty() &&
992 (now - last_times_.front() >= channel_storage_duration_)) {
993 last_times_.pop();
994 }
995
996 // Check that we are not sending messages too fast
James Kuszmaul890c2492022-04-06 14:59:31 -0700997 if (check_sent_too_fast == CheckSentTooFast::kYes &&
998 static_cast<int>(last_times_.size()) >= queue_size()) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700999 return std::nullopt;
1000 }
1001
1002 const std::optional<uint32_t> queue_index = {next_queue_index_.index()};
1003 last_times_.push(now);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001004
milind1f1dca32021-07-03 13:50:07 -07001005 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001006 // Points to the actual data depending on the size set in context. Data may
1007 // allocate more than the actual size of the message, so offset from the back
1008 // of that to get the actual start of the data.
1009 message->context.data =
1010 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -07001011
1012 DCHECK(channel()->has_schema())
1013 << ": Missing schema for channel "
1014 << configuration::StrippedChannelToString(channel());
1015 DCHECK(flatbuffers::Verify(
1016 *channel()->schema(), *channel()->schema()->root_table(),
1017 static_cast<const uint8_t *>(message->context.data),
1018 message->context.size))
1019 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
1020 << channel()->type()->c_str();
1021
Alex Perrycb7da4b2019-08-28 19:35:56 -07001022 next_queue_index_ = next_queue_index_.Increment();
1023
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001024 latest_message_ = std::move(message);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001025 for (SimulatedWatcher *watcher : watchers_) {
1026 if (watcher->has_run()) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001027 watcher->Schedule(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001028 }
1029 }
1030 for (auto &fetcher : fetchers_) {
Austin Schuhe6f4c8d2021-12-11 12:36:06 -08001031 fetcher->Enqueue(latest_message_);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001032 }
Austin Schuhad154822019-12-27 15:45:13 -08001033 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001034}
1035
1036void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
1037 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
1038}
1039
Austin Schuh8fb315a2020-11-19 22:33:58 -08001040SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
1041 SimulatedEventLoop *event_loop)
1042 : RawSender(event_loop, simulated_channel->channel()),
1043 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -07001044 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -08001045 simulated_channel_->CountSenderCreated();
1046}
1047
1048SimulatedSender::~SimulatedSender() {
1049 simulated_channel_->CountSenderDestroyed();
1050}
1051
milind1f1dca32021-07-03 13:50:07 -07001052RawSender::Error SimulatedSender::DoSend(
1053 size_t length, monotonic_clock::time_point monotonic_remote_time,
1054 realtime_clock::time_point realtime_remote_time,
1055 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001056 // The allocations in here are due to infrastructure and don't count in the
1057 // no mallocs in RT code.
1058 ScopedNotRealtime nrt;
1059
Austin Schuh58646e22021-08-23 23:51:46 -07001060 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1061 << NodeName(simulated_event_loop_->node())
1062 << simulated_event_loop_->monotonic_now() << " "
1063 << simulated_event_loop_->name() << " Send "
1064 << configuration::StrippedChannelToString(channel());
1065
Austin Schuh8fb315a2020-11-19 22:33:58 -08001066 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -07001067 message_->context.monotonic_event_time =
1068 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001069 message_->context.monotonic_remote_time = monotonic_remote_time;
1070 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001071 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001072 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001073 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001074 CHECK_LE(length, message_->context.size);
1075 message_->context.size = length;
1076
Austin Schuh60e77942022-05-16 17:48:24 -07001077 const std::optional<uint32_t> optional_queue_index = simulated_channel_->Send(
1078 message_, simulated_event_loop_->options().check_sent_too_fast);
milind1f1dca32021-07-03 13:50:07 -07001079
1080 // Check that we are not sending messages too fast
1081 if (!optional_queue_index) {
1082 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1083 << NodeName(simulated_event_loop_->node())
1084 << simulated_event_loop_->monotonic_now() << " "
1085 << simulated_event_loop_->name()
1086 << "\nMessages were sent too fast:\n"
1087 << "For channel: "
1088 << configuration::CleanedChannelToString(
1089 simulated_channel_->channel())
1090 << '\n'
1091 << "Tried to send more than " << simulated_channel_->queue_size()
1092 << " (queue size) messages in the last "
1093 << std::chrono::duration<double>(
1094 simulated_channel_->channel_storage_duration())
1095 .count()
1096 << " seconds (channel storage duration)"
1097 << "\n\n";
1098 return Error::kMessagesSentTooFast;
1099 }
1100
1101 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001102 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1103 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001104
1105 // Drop the reference to the message so that we allocate a new message for
1106 // next time. Otherwise we will continue to reuse the same memory for all
1107 // messages and corrupt it.
1108 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001109 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001110}
1111
milind1f1dca32021-07-03 13:50:07 -07001112RawSender::Error SimulatedSender::DoSend(
1113 const void *msg, size_t size,
1114 monotonic_clock::time_point monotonic_remote_time,
1115 realtime_clock::time_point realtime_remote_time,
1116 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001117 CHECK_LE(size, this->size())
1118 << ": Attempting to send too big a message on "
1119 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001120
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001121 // Allocates an aligned buffer in which to copy unaligned msg.
1122 auto [span, mutable_span] = MakeSharedSpan(size);
1123 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001124
1125 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001126 // queue_index will be populated in simulated_channel_.
1127 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001128
1129 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001130 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001131}
1132
milind1f1dca32021-07-03 13:50:07 -07001133RawSender::Error SimulatedSender::DoSend(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001134 const SharedSpan data, monotonic_clock::time_point monotonic_remote_time,
milind1f1dca32021-07-03 13:50:07 -07001135 realtime_clock::time_point realtime_remote_time,
1136 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001137 CHECK_LE(data->size(), this->size())
1138 << ": Attempting to send too big a message on "
1139 << configuration::CleanedChannelToString(simulated_channel_->channel());
1140
1141 // Constructs a message sharing the already allocated and aligned message
1142 // data.
1143 message_ = SimulatedMessage::Make(simulated_channel_, data);
1144
1145 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1146 remote_queue_index, source_boot_uuid);
1147}
1148
Austin Schuh39788ff2019-12-01 18:22:57 -08001149SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001150 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1151 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001152 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001153 simulated_event_loop_(simulated_event_loop),
1154 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001155 scheduler_(scheduler),
1156 token_(scheduler_->InvalidToken()) {}
1157
Philipp Schradera6712522023-07-05 20:25:11 -07001158void SimulatedTimerHandler::Schedule(monotonic_clock::time_point base,
1159 monotonic_clock::duration repeat_offset) {
James Kuszmaul86e86c32022-07-21 17:39:47 -07001160 CHECK_GE(base, monotonic_clock::epoch());
Austin Schuh62288252020-11-18 23:26:04 -08001161 // The allocations in here are due to infrastructure and don't count in the no
1162 // mallocs in RT code.
1163 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001164 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001165 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001166 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001167 base_ = base;
1168 repeat_offset_ = repeat_offset;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001169 token_ = scheduler_->Schedule(std::max(base, monotonic_now), this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001170 event_.set_event_time(base_);
1171 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001172 disabled_ = false;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001173}
1174
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001175void SimulatedTimerHandler::Handle() noexcept {
1176 DCHECK(token_ != scheduler_->InvalidToken());
1177 token_ = scheduler_->InvalidToken();
1178 simulated_event_loop_->HandleEvent();
1179}
1180
Austin Schuhf4b09c72021-12-08 12:04:37 -08001181void SimulatedTimerHandler::HandleEvent() noexcept {
Austin Schuh58646e22021-08-23 23:51:46 -07001182 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001183 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001184 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1185 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1186 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001187 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001188 if (simulated_event_loop_->log_impl_) {
1189 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001190 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001191 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001192 {
1193 ScopedNotRealtime nrt;
1194 scheduler_->Deschedule(token_);
1195 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001196 token_ = scheduler_->InvalidToken();
1197 }
Austin Schuh58646e22021-08-23 23:51:46 -07001198 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001199 // Reschedule.
1200 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001201 token_ = scheduler_->Schedule(base_, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001202 event_.set_event_time(base_);
1203 simulated_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001204 disabled_ = false;
1205 } else {
1206 disabled_ = true;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001207 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001208 {
Austin Schuh65493d62022-08-17 15:10:37 -07001209 ScopedMarkRealtimeRestorer rt(
1210 simulated_event_loop_->runtime_realtime_priority() > 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -07001211 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuh0debde12022-08-17 16:25:17 -07001212 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001213 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001214}
1215
Austin Schuh7d87b672019-12-01 20:23:49 -08001216void SimulatedTimerHandler::Disable() {
1217 simulated_event_loop_->RemoveEvent(&event_);
1218 if (token_ != scheduler_->InvalidToken()) {
Austin Schuh9b1d6282022-06-10 17:03:21 -07001219 {
1220 ScopedNotRealtime nrt;
1221 scheduler_->Deschedule(token_);
1222 }
Austin Schuh7d87b672019-12-01 20:23:49 -08001223 token_ = scheduler_->InvalidToken();
1224 }
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001225 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -08001226}
1227
Naman Gupta4d13b0a2022-10-19 16:41:24 -07001228bool SimulatedTimerHandler::IsDisabled() { return disabled_; }
1229
Austin Schuh39788ff2019-12-01 18:22:57 -08001230SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001231 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1232 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001233 const monotonic_clock::duration offset)
1234 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1235 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001236 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001237 scheduler_(scheduler),
1238 token_(scheduler_->InvalidToken()) {}
1239
Austin Schuh7d87b672019-12-01 20:23:49 -08001240SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1241 if (token_ != scheduler_->InvalidToken()) {
1242 scheduler_->Deschedule(token_);
1243 token_ = scheduler_->InvalidToken();
1244 }
1245 simulated_event_loop_->RemoveEvent(&event_);
1246}
1247
Austin Schuhf4b09c72021-12-08 12:04:37 -08001248void SimulatedPhasedLoopHandler::HandleEvent() noexcept {
Austin Schuh39788ff2019-12-01 18:22:57 -08001249 monotonic_clock::time_point monotonic_now =
1250 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001251 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1252 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001253 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001254 if (simulated_event_loop_->log_impl_) {
1255 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001256 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001257
1258 {
Austin Schuh65493d62022-08-17 15:10:37 -07001259 ScopedMarkRealtimeRestorer rt(
1260 simulated_event_loop_->runtime_realtime_priority() > 0);
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001261 Call([monotonic_now]() { return monotonic_now; });
Austin Schuh0debde12022-08-17 16:25:17 -07001262 simulated_event_loop_->ClearContext();
Austin Schuhcc6070c2020-10-10 20:25:56 -07001263 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001264}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001265
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001266void SimulatedPhasedLoopHandler::Handle() noexcept {
1267 DCHECK(token_ != scheduler_->InvalidToken());
1268 token_ = scheduler_->InvalidToken();
1269 simulated_event_loop_->HandleEvent();
1270}
1271
Austin Schuh7d87b672019-12-01 20:23:49 -08001272void SimulatedPhasedLoopHandler::Schedule(
1273 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001274 // The allocations in here are due to infrastructure and don't count in the no
1275 // mallocs in RT code.
1276 ScopedNotRealtime nrt;
James Kuszmaul20dcc7c2023-01-20 11:06:31 -08001277 simulated_event_loop_->RemoveEvent(&event_);
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001278 if (token_ != scheduler_->InvalidToken()) {
1279 scheduler_->Deschedule(token_);
1280 token_ = scheduler_->InvalidToken();
1281 }
Austin Schuhef8f1ae2021-12-11 12:35:05 -08001282 token_ = scheduler_->Schedule(sleep_time, this);
Austin Schuh7d87b672019-12-01 20:23:49 -08001283 event_.set_event_time(sleep_time);
1284 simulated_event_loop_->AddEvent(&event_);
1285}
1286
Alex Perrycb7da4b2019-08-28 19:35:56 -07001287SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1288 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001289 : configuration_(CHECK_NOTNULL(configuration)),
1290 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001291 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001292 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001293 node_factories_.emplace_back(
1294 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001295 }
Austin Schuh898f4972020-01-11 17:21:25 -08001296
1297 if (configuration::MultiNode(configuration)) {
1298 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1299 }
Austin Schuh15649d62019-12-28 16:36:38 -08001300}
1301
Brian Silvermane1fe2512022-08-14 23:18:50 -07001302SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {
1303 CHECK_EQ(0, exit_handle_count_)
1304 << ": All ExitHandles must be destroyed before the factory";
1305}
Alex Perrycb7da4b2019-08-28 19:35:56 -07001306
Austin Schuhac0771c2020-01-07 18:36:30 -08001307NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001308 std::string_view node) {
1309 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1310}
1311
1312NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001313 const Node *node) {
1314 auto result = std::find_if(
1315 node_factories_.begin(), node_factories_.end(),
1316 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1317 return node_factory->node() == node;
1318 });
1319
1320 CHECK(result != node_factories_.end())
1321 << ": Failed to find node " << FlatbufferToJson(node);
1322
1323 return result->get();
1324}
1325
Austin Schuh87dd3832021-01-01 23:07:31 -08001326void SimulatedEventLoopFactory::SetTimeConverter(
1327 TimeConverter *time_converter) {
1328 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1329 factory->SetTimeConverter(time_converter);
1330 }
Austin Schuh58646e22021-08-23 23:51:46 -07001331 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001332}
1333
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001334::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001335 std::string_view name, const Node *node) {
1336 if (node == nullptr) {
1337 CHECK(!configuration::MultiNode(configuration()))
1338 << ": Can't make a single node event loop in a multi-node world.";
1339 } else {
1340 CHECK(configuration::MultiNode(configuration()))
1341 << ": Can't make a multi-node event loop in a single-node world.";
1342 }
1343 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1344}
1345
Austin Schuh057d29f2021-08-21 23:05:15 -07001346NodeEventLoopFactory::NodeEventLoopFactory(
1347 EventSchedulerScheduler *scheduler_scheduler,
1348 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001349 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1350 factory_(factory),
1351 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001352 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001353 scheduler_.set_started([this]() {
1354 started_ = true;
1355 for (SimulatedEventLoop *event_loop : event_loops_) {
1356 event_loop->SetIsRunning(true);
1357 }
1358 });
Austin Schuhe33c08d2022-02-03 18:15:21 -08001359 scheduler_.set_stopped([this]() {
1360 for (SimulatedEventLoop *event_loop : event_loops_) {
1361 event_loop->SetIsRunning(false);
1362 }
1363 });
Austin Schuh58646e22021-08-23 23:51:46 -07001364 scheduler_.set_on_shutdown([this]() {
1365 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1366 << monotonic_now() << " Shutting down node.";
1367 Shutdown();
1368 ScheduleStartup();
1369 });
1370 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001371}
1372
1373NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001374 if (started_) {
1375 for (std::function<void()> &fn : on_shutdown_) {
1376 fn();
1377 }
1378
1379 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1380 << monotonic_now() << " Shutting down applications.";
1381 applications_.clear();
1382 started_ = false;
1383 }
1384
1385 if (event_loops_.size() != 0u) {
1386 for (SimulatedEventLoop *event_loop : event_loops_) {
1387 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1388 << monotonic_now() << " Event loop '" << event_loop->name()
1389 << "' failed to shut down";
1390 }
1391 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001392 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1393}
1394
Austin Schuh58646e22021-08-23 23:51:46 -07001395void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001396 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001397 << ": Can only register OnStartup handlers when not running.";
1398 on_startup_.emplace_back(std::move(fn));
1399 if (started_) {
1400 size_t on_startup_index = on_startup_.size() - 1;
1401 scheduler_.ScheduleOnStartup(
1402 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1403 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001404}
1405
Austin Schuh58646e22021-08-23 23:51:46 -07001406void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1407 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001408}
Austin Schuh057d29f2021-08-21 23:05:15 -07001409
Austin Schuh58646e22021-08-23 23:51:46 -07001410void NodeEventLoopFactory::ScheduleStartup() {
1411 scheduler_.ScheduleOnStartup([this]() {
1412 UUID next_uuid = scheduler_.boot_uuid();
1413 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001414 CHECK_EQ(boot_uuid_, UUID::Zero())
1415 << ": Boot UUID changed without restarting. Did TimeConverter "
1416 "change the boot UUID without signaling a restart, or did you "
1417 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001418 boot_uuid_ = next_uuid;
1419 }
1420 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1421 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1422 Startup();
1423 });
1424}
1425
1426void NodeEventLoopFactory::Startup() {
1427 CHECK(!started_);
1428 for (size_t i = 0; i < on_startup_.size(); ++i) {
1429 on_startup_[i]();
1430 }
1431}
1432
1433void NodeEventLoopFactory::Shutdown() {
1434 for (SimulatedEventLoop *event_loop : event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001435 CHECK(!event_loop->is_running());
Austin Schuh58646e22021-08-23 23:51:46 -07001436 }
1437
1438 CHECK(started_);
1439 started_ = false;
1440 for (std::function<void()> &fn : on_shutdown_) {
1441 fn();
1442 }
1443
1444 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1445 << monotonic_now() << " Shutting down applications.";
1446 applications_.clear();
1447
1448 if (event_loops_.size() != 0u) {
1449 for (SimulatedEventLoop *event_loop : event_loops_) {
1450 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1451 << monotonic_now() << " Event loop '" << event_loop->name()
1452 << "' failed to shut down";
1453 }
1454 }
1455 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1456 boot_uuid_ = UUID::Zero();
1457
1458 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001459}
1460
Alex Perrycb7da4b2019-08-28 19:35:56 -07001461void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001462 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001463 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001464 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1465 if (node) {
1466 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001467 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001468 }
1469 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001470 }
1471}
1472
1473void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001474 // This sets running to true too.
Austin Schuh8bd96322020-02-13 21:18:22 -08001475 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001476 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1477 if (node) {
1478 for (SimulatedEventLoop *loop : node->event_loops_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001479 CHECK(!loop->is_running());
Austin Schuh057d29f2021-08-21 23:05:15 -07001480 }
1481 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001482 }
1483}
1484
Austin Schuh87dd3832021-01-01 23:07:31 -08001485void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001486
Brian Silvermane1fe2512022-08-14 23:18:50 -07001487std::unique_ptr<ExitHandle> SimulatedEventLoopFactory::MakeExitHandle() {
1488 return std::make_unique<SimulatedFactoryExitHandle>(this);
1489}
1490
Austin Schuh6f3babe2020-01-26 20:34:50 -08001491void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001492 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001493 bridge_->DisableForwarding(channel);
1494}
1495
Austin Schuh4c3b9702020-08-30 11:34:55 -07001496void SimulatedEventLoopFactory::DisableStatistics() {
1497 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
James Kuszmaul94ca5132022-07-19 09:11:08 -07001498 bridge_->DisableStatistics(
1499 message_bridge::SimulatedMessageBridge::DestroySenders::kNo);
1500}
1501
1502void SimulatedEventLoopFactory::PermanentlyDisableStatistics() {
1503 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1504 bridge_->DisableStatistics(
1505 message_bridge::SimulatedMessageBridge::DestroySenders::kYes);
Austin Schuh4c3b9702020-08-30 11:34:55 -07001506}
1507
Austin Schuh48205e62021-11-12 14:13:18 -08001508void SimulatedEventLoopFactory::EnableStatistics() {
1509 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1510 bridge_->EnableStatistics();
1511}
1512
Austin Schuh2928ebe2021-02-07 22:10:27 -08001513void SimulatedEventLoopFactory::SkipTimingReport() {
1514 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001515
1516 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1517 if (node) {
1518 node->SkipTimingReport();
1519 }
1520 }
1521}
1522
1523void NodeEventLoopFactory::SkipTimingReport() {
1524 for (SimulatedEventLoop *event_loop : event_loops_) {
1525 event_loop->SkipTimingReport();
1526 }
1527 skip_timing_report_ = true;
1528}
1529
1530void NodeEventLoopFactory::EnableStatistics() {
1531 CHECK(factory_->bridge_)
1532 << ": Can't enable statistics without a message bridge.";
1533 factory_->bridge_->EnableStatistics(node_);
1534}
1535
1536void NodeEventLoopFactory::DisableStatistics() {
1537 CHECK(factory_->bridge_)
1538 << ": Can't disable statistics without a message bridge.";
1539 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001540}
1541
Austin Schuh58646e22021-08-23 23:51:46 -07001542::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
James Kuszmaul890c2492022-04-06 14:59:31 -07001543 std::string_view name, EventLoopOptions options) {
Austin Schuh58646e22021-08-23 23:51:46 -07001544 CHECK(!scheduler_.is_running() || !started_)
1545 << ": Can't create an event loop while running";
1546
1547 pid_t tid = tid_;
1548 ++tid_;
1549 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1550 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
James Kuszmaul890c2492022-04-06 14:59:31 -07001551 node_, tid, options));
Austin Schuh58646e22021-08-23 23:51:46 -07001552 result->set_name(name);
1553 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001554 if (skip_timing_report_) {
1555 result->SkipTimingReport();
1556 }
Austin Schuh58646e22021-08-23 23:51:46 -07001557
1558 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1559 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
James Kuszmaul9776b392023-01-14 14:08:08 -08001560 return result;
Austin Schuh58646e22021-08-23 23:51:46 -07001561}
1562
Austin Schuhe33c08d2022-02-03 18:15:21 -08001563void SimulatedEventLoopFactory::AllowApplicationCreationDuring(
1564 std::function<void()> fn) {
1565 scheduler_scheduler_.TemporarilyStopAndRun(std::move(fn));
1566}
1567
Austin Schuh58646e22021-08-23 23:51:46 -07001568void NodeEventLoopFactory::Disconnect(const Node *other) {
1569 factory_->bridge_->Disconnect(node_, other);
1570}
1571
1572void NodeEventLoopFactory::Connect(const Node *other) {
1573 factory_->bridge_->Connect(node_, other);
1574}
1575
Alex Perrycb7da4b2019-08-28 19:35:56 -07001576} // namespace aos