blob: 083e2467bae303feb963f7534aaf91199f2c4097 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/events/simulated_event_loop.h"
2
3#include <algorithm>
4#include <deque>
milind1f1dca32021-07-03 13:50:07 -07005#include <optional>
6#include <queue>
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08007#include <string_view>
Brian Silverman661eb8d2020-08-12 19:41:01 -07008#include <vector>
Alex Perrycb7da4b2019-08-28 19:35:56 -07009
10#include "absl/container/btree_map.h"
Brian Silverman661eb8d2020-08-12 19:41:01 -070011#include "aos/events/aos_logging.h"
Austin Schuh898f4972020-01-11 17:21:25 -080012#include "aos/events/simulated_network_bridge.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080013#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/json_to_flatbuffer.h"
Austin Schuhcc6070c2020-10-10 20:25:56 -070015#include "aos/realtime.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "aos/util/phased_loop.h"
17
18namespace aos {
19
Brian Silverman661eb8d2020-08-12 19:41:01 -070020class SimulatedEventLoop;
21class SimulatedFetcher;
22class SimulatedChannel;
23
24namespace {
25
Austin Schuh057d29f2021-08-21 23:05:15 -070026std::string NodeName(const Node *node) {
27 if (node == nullptr) {
28 return "";
29 }
30
31 return absl::StrCat(node->name()->string_view(), " ");
32}
33
Austin Schuhcc6070c2020-10-10 20:25:56 -070034class ScopedMarkRealtimeRestorer {
35 public:
36 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
37 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
38
39 private:
40 const bool rt_;
41 const bool prior_;
42};
43
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070044// Holds storage for a span object and the data referenced by that span for
45// compatibility with RawSender::SharedSpan users. If constructed with
46// MakeSharedSpan, span points to only the aligned segment of the entire data.
47struct AlignedOwningSpan {
48 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
49 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
50 absl::Span<const uint8_t> span;
51 char data[];
52};
53
54// Constructs a span which owns its data through a shared_ptr. The owning span
55// points to a const view of the data; also returns a temporary mutable span
56// which is only valid while the const shared span is kept alive.
57std::pair<RawSender::SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(
58 size_t size) {
59 AlignedOwningSpan *const span = reinterpret_cast<AlignedOwningSpan *>(
60 malloc(sizeof(AlignedOwningSpan) + size + kChannelDataAlignment - 1));
61
62 absl::Span mutable_span(
63 reinterpret_cast<uint8_t *>(RoundChannelData(&span->data[0], size)),
64 size);
65 new (span) AlignedOwningSpan{.span = mutable_span};
66
67 return std::make_pair(
68 RawSender::SharedSpan(
69 std::shared_ptr<AlignedOwningSpan>(span,
70 [](AlignedOwningSpan *s) {
71 s->~AlignedOwningSpan();
72 free(s);
73 }),
74 &span->span),
75 mutable_span);
76}
77
Alex Perrycb7da4b2019-08-28 19:35:56 -070078// Container for both a message, and the context for it for simulation. This
79// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070080struct SimulatedMessage final {
81 SimulatedMessage(const SimulatedMessage &) = delete;
82 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070083 ~SimulatedMessage();
Brian Silverman661eb8d2020-08-12 19:41:01 -070084
85 // Creates a SimulatedMessage with size bytes of storage.
86 // This is a shared_ptr so we don't have to implement refcounting or copying.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070087 static std::shared_ptr<SimulatedMessage> Make(
88 SimulatedChannel *channel, const RawSender::SharedSpan data);
Brian Silverman661eb8d2020-08-12 19:41:01 -070089
Alex Perrycb7da4b2019-08-28 19:35:56 -070090 // Context for the data.
91 Context context;
92
Brian Silverman661eb8d2020-08-12 19:41:01 -070093 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070094
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070095 // Owning span to this message's data. Depending on the sender may either
96 // represent the data of just the flatbuffer, or max channel size.
97 RawSender::SharedSpan data;
Alex Perrycb7da4b2019-08-28 19:35:56 -070098
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070099 // Mutable view of above data. If empty, this message is not mutable.
100 absl::Span<uint8_t> mutable_data;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700101
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700102 // Determines whether this message is mutable. Used for Send where the user
103 // fills out a message stored internally then gives us the size of data used.
104 bool is_mutable() const { return data->size() == mutable_data.size(); }
105
106 // Note: this should be private but make_shared requires it to be public. Use
107 // Make() above to construct.
Brian Silverman661eb8d2020-08-12 19:41:01 -0700108 SimulatedMessage(SimulatedChannel *channel_in);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700109};
110
Brian Silverman661eb8d2020-08-12 19:41:01 -0700111} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -0800112
Brian Silverman661eb8d2020-08-12 19:41:01 -0700113// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
114// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -0800115class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -0800116 public:
Austin Schuh7d87b672019-12-01 20:23:49 -0800117 SimulatedWatcher(
118 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
119 const Channel *channel,
120 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -0800121
Austin Schuh7d87b672019-12-01 20:23:49 -0800122 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -0800123
Austin Schuh8fb315a2020-11-19 22:33:58 -0800124 bool has_run() const;
125
Austin Schuh39788ff2019-12-01 18:22:57 -0800126 void Startup(EventLoop * /*event_loop*/) override {}
127
Austin Schuh7d87b672019-12-01 20:23:49 -0800128 void Schedule(std::shared_ptr<SimulatedMessage> message);
129
130 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800131
132 void SetSimulatedChannel(SimulatedChannel *channel) {
133 simulated_channel_ = channel;
134 }
135
136 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800137 void DoSchedule(monotonic_clock::time_point event_time);
138
139 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
140
Brian Silverman4f4e0612020-08-12 19:54:41 -0700141 SimulatedEventLoop *const simulated_event_loop_;
142 const Channel *const channel_;
143 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800144 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800145 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800146 SimulatedChannel *simulated_channel_ = nullptr;
147};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700148
149class SimulatedChannel {
150 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800151 explicit SimulatedChannel(const Channel *channel,
Brian Silverman661eb8d2020-08-12 19:41:01 -0700152 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800153 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700154 channel_storage_duration_(channel_storage_duration),
155 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
156 available_buffer_indices_.reserve(number_buffers());
157 for (int i = 0; i < number_buffers(); ++i) {
158 available_buffer_indices_.push_back(i);
159 }
160 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700161
Brian Silverman661eb8d2020-08-12 19:41:01 -0700162 ~SimulatedChannel() {
163 latest_message_.reset();
164 CHECK_EQ(static_cast<size_t>(number_buffers()),
165 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800166 CHECK_EQ(0u, fetchers_.size())
167 << configuration::StrippedChannelToString(channel());
168 CHECK_EQ(0u, watchers_.size())
169 << configuration::StrippedChannelToString(channel());
170 CHECK_EQ(0, sender_count_)
171 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700172 }
173
174 // The number of messages we pretend to have in the queue.
175 int queue_size() const {
176 return channel()->frequency() *
177 std::chrono::duration_cast<std::chrono::duration<double>>(
178 channel_storage_duration_)
179 .count();
180 }
181
milind1f1dca32021-07-03 13:50:07 -0700182 std::chrono::nanoseconds channel_storage_duration() const {
183 return channel_storage_duration_;
184 }
185
Brian Silverman661eb8d2020-08-12 19:41:01 -0700186 // The number of extra buffers (beyond the queue) we pretend to have.
187 int number_scratch_buffers() const {
188 // We need to start creating messages before we know how many
189 // senders+readers we'll have, so we need to just pick something which is
190 // always big enough.
191 return 50;
192 }
193
194 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
195
196 int GetBufferIndex() {
197 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
198 const int result = available_buffer_indices_.back();
199 available_buffer_indices_.pop_back();
200 return result;
201 }
202
203 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700204 // This extra checking has a large performance hit with sanitizers that
205 // track memory accesses, so just skip it.
206#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700207 DCHECK(std::find(available_buffer_indices_.begin(),
208 available_buffer_indices_.end(),
209 i) == available_buffer_indices_.end())
210 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800211#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700212 available_buffer_indices_.push_back(i);
213 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700214
215 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800216 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217
218 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800219 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700220
221 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800222 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800223
Austin Schuh7d87b672019-12-01 20:23:49 -0800224 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800225 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
226 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700227
Austin Schuhad154822019-12-27 15:45:13 -0800228 // Sends the message to all the connected receivers and fetchers. Returns the
milind1f1dca32021-07-03 13:50:07 -0700229 // sent queue index, or std::nullopt if messages were sent too fast.
230 std::optional<uint32_t> Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700231
232 // Unregisters a fetcher.
233 void UnregisterFetcher(SimulatedFetcher *fetcher);
234
235 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
236
Austin Schuh39788ff2019-12-01 18:22:57 -0800237 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700238
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800239 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800240 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700241 }
242
Austin Schuh39788ff2019-12-01 18:22:57 -0800243 const Channel *channel() const { return channel_; }
244
Austin Schuhe516ab02020-05-06 21:37:04 -0700245 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700246 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700247 if (sender_count_ >= channel()->num_senders()) {
248 LOG(FATAL) << "Failed to create sender on "
249 << configuration::CleanedChannelToString(channel())
250 << ", too many senders.";
251 }
252 ++sender_count_;
253 }
Brian Silverman77162972020-08-12 19:52:40 -0700254
Austin Schuhe516ab02020-05-06 21:37:04 -0700255 void CountSenderDestroyed() {
256 --sender_count_;
257 CHECK_GE(sender_count_, 0);
258 }
259
Alex Perrycb7da4b2019-08-28 19:35:56 -0700260 private:
Brian Silverman77162972020-08-12 19:52:40 -0700261 void CheckBufferCount() {
262 int reader_count = 0;
263 if (channel()->read_method() == ReadMethod::PIN) {
264 reader_count = watchers_.size() + fetchers_.size();
265 }
266 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
267 }
268
269 void CheckReaderCount() {
270 if (channel()->read_method() != ReadMethod::PIN) {
271 return;
272 }
273 CheckBufferCount();
274 const int reader_count = watchers_.size() + fetchers_.size();
275 if (reader_count >= channel()->num_readers()) {
276 LOG(FATAL) << "Failed to create reader on "
277 << configuration::CleanedChannelToString(channel())
278 << ", too many readers.";
279 }
280 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700281
282 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700283 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284
285 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800286 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700287
288 // List of all fetchers.
289 ::std::vector<SimulatedFetcher *> fetchers_;
290 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291
292 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700293
294 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700295
296 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700297};
298
299namespace {
300
Brian Silverman661eb8d2020-08-12 19:41:01 -0700301std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700302 SimulatedChannel *channel, RawSender::SharedSpan data) {
Austin Schuh62288252020-11-18 23:26:04 -0800303 // The allocations in here are due to infrastructure and don't count in the no
304 // mallocs in RT code.
305 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700306
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700307 auto message = std::make_shared<SimulatedMessage>(channel);
308 message->context.size = data->size();
309 message->context.data = data->data();
310 message->data = std::move(data);
311
312 return message;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700313}
314
315SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
316 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700317 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700318}
319
320SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700321 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700322}
323
324class SimulatedSender : public RawSender {
325 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800326 SimulatedSender(SimulatedChannel *simulated_channel,
327 SimulatedEventLoop *event_loop);
328 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700329
330 void *data() override {
331 if (!message_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700332 auto [span, mutable_span] =
333 MakeSharedSpan(simulated_channel_->max_size());
334 message_ = SimulatedMessage::Make(simulated_channel_, span);
335 message_->mutable_data = mutable_span;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700336 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700337 CHECK(message_->is_mutable());
338 return message_->mutable_data.data();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700339 }
340
341 size_t size() override { return simulated_channel_->max_size(); }
342
milind1f1dca32021-07-03 13:50:07 -0700343 Error DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
344 realtime_clock::time_point realtime_remote_time,
345 uint32_t remote_queue_index,
346 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700347
milind1f1dca32021-07-03 13:50:07 -0700348 Error DoSend(const void *msg, size_t size,
349 monotonic_clock::time_point monotonic_remote_time,
350 realtime_clock::time_point realtime_remote_time,
351 uint32_t remote_queue_index,
352 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700353
milind1f1dca32021-07-03 13:50:07 -0700354 Error DoSend(const SharedSpan data,
355 aos::monotonic_clock::time_point monotonic_remote_time,
356 aos::realtime_clock::time_point realtime_remote_time,
357 uint32_t remote_queue_index,
358 const UUID &source_boot_uuid) override;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700359
Brian Silverman4f4e0612020-08-12 19:54:41 -0700360 int buffer_index() override {
361 // First, ensure message_ is allocated.
362 data();
363 return message_->context.buffer_index;
364 }
365
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366 private:
367 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700368 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700369
370 std::shared_ptr<SimulatedMessage> message_;
371};
372} // namespace
373
374class SimulatedFetcher : public RawFetcher {
375 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800376 explicit SimulatedFetcher(EventLoop *event_loop,
377 SimulatedChannel *simulated_channel)
378 : RawFetcher(event_loop, simulated_channel->channel()),
379 simulated_channel_(simulated_channel) {}
380 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700381
Austin Schuh39788ff2019-12-01 18:22:57 -0800382 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800383 // The allocations in here are due to infrastructure and don't count in the
384 // no mallocs in RT code.
385 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800386 if (msgs_.size() == 0) {
387 return std::make_pair(false, monotonic_clock::min_time);
388 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700389
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700390 CHECK(!fell_behind_) << ": Got behind on "
391 << configuration::StrippedChannelToString(
392 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700393
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394 SetMsg(msgs_.front());
395 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800396 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700397 }
398
Austin Schuh39788ff2019-12-01 18:22:57 -0800399 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800400 // The allocations in here are due to infrastructure and don't count in the
401 // no mallocs in RT code.
402 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800404 // TODO(austin): Can we just do this logic unconditionally? It is a lot
405 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800406 if (!msg_ && simulated_channel_->latest_message()) {
407 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800408 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800410 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411 }
412 }
413
414 // We've had a message enqueued, so we don't need to go looking for the
415 // latest message from before we started.
416 SetMsg(msgs_.back());
417 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700418 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800419 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420 }
421
422 private:
423 friend class SimulatedChannel;
424
425 // Updates the state inside RawFetcher to point to the data in msg_.
426 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
427 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700428 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700429 if (channel()->read_method() != ReadMethod::PIN) {
430 context_.buffer_index = -1;
431 }
Austin Schuhad154822019-12-27 15:45:13 -0800432 if (context_.remote_queue_index == 0xffffffffu) {
433 context_.remote_queue_index = context_.queue_index;
434 }
Austin Schuh58646e22021-08-23 23:51:46 -0700435 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800436 context_.monotonic_remote_time = context_.monotonic_event_time;
437 }
Austin Schuh58646e22021-08-23 23:51:46 -0700438 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800439 context_.realtime_remote_time = context_.realtime_event_time;
440 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700441 }
442
443 // Internal method for Simulation to add a message to the buffer.
444 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
445 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700446 if (fell_behind_ ||
447 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
448 fell_behind_ = true;
449 // Might as well empty out all the intermediate messages now.
450 while (msgs_.size() > 1) {
451 msgs_.pop_front();
452 }
453 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454 }
455
Austin Schuhac0771c2020-01-07 18:36:30 -0800456 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457 std::shared_ptr<SimulatedMessage> msg_;
458
459 // Messages queued up but not in use.
460 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700461
462 // Whether we're currently "behind", which means a FetchNext call will fail.
463 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700464};
465
466class SimulatedTimerHandler : public TimerHandler {
467 public:
468 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800469 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800470 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800471 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700472
473 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800474 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700475
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800476 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477
Austin Schuh7d87b672019-12-01 20:23:49 -0800478 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800481 SimulatedEventLoop *simulated_event_loop_;
482 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483 EventScheduler *scheduler_;
484 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800485
Alex Perrycb7da4b2019-08-28 19:35:56 -0700486 monotonic_clock::time_point base_;
487 monotonic_clock::duration repeat_offset_;
488};
489
490class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
491 public:
492 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800493 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 ::std::function<void(int)> fn,
495 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800496 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800497 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700498
Austin Schuh7d87b672019-12-01 20:23:49 -0800499 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500
Austin Schuh7d87b672019-12-01 20:23:49 -0800501 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700502
503 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800504 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800505 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700506
Austin Schuh39788ff2019-12-01 18:22:57 -0800507 EventScheduler *scheduler_;
508 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509};
510
511class SimulatedEventLoop : public EventLoop {
512 public:
513 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700514 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
516 *channels,
517 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700518 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
519 pid_t tid)
Austin Schuh83c7f702021-01-19 22:36:29 -0800520 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700521 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800522 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700523 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700524 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800525 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700526 tid_(tid),
527 startup_tracker_(std::make_shared<StartupTracker>()) {
528 startup_tracker_->loop = this;
529 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
530 if (startup_tracker->loop) {
531 startup_tracker->loop->Setup();
532 startup_tracker->has_setup = true;
533 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700534 });
535
536 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537 }
Austin Schuh58646e22021-08-23 23:51:46 -0700538
Alex Perrycb7da4b2019-08-28 19:35:56 -0700539 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800540 // Trigger any remaining senders or fetchers to be cleared before destroying
541 // the event loop so the book keeping matches.
542 timing_report_sender_.reset();
543
544 // Force everything with a registered fd with epoll to be destroyed now.
545 timers_.clear();
546 phased_loops_.clear();
547 watchers_.clear();
548
Austin Schuh58646e22021-08-23 23:51:46 -0700549 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700550 if (*it == this) {
551 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 break;
553 }
554 }
Austin Schuh58646e22021-08-23 23:51:46 -0700555 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
556 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
557 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558 }
559
Austin Schuh057d29f2021-08-21 23:05:15 -0700560 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700561 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
562 << monotonic_now() << " " << name_ << " set_is_running(" << running
563 << ")";
564 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700565
566 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700567 if (running) {
568 has_run_ = true;
569 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700570 }
571
Austin Schuh8fb315a2020-11-19 22:33:58 -0800572 bool has_run() const { return has_run_; }
573
Austin Schuh7d87b672019-12-01 20:23:49 -0800574 std::chrono::nanoseconds send_delay() const { return send_delay_; }
575 void set_send_delay(std::chrono::nanoseconds send_delay) {
576 send_delay_ = send_delay;
577 }
578
Austin Schuh58646e22021-08-23 23:51:46 -0700579 monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800580 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700581 }
582
Austin Schuh58646e22021-08-23 23:51:46 -0700583 realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800584 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700585 }
586
Austin Schuh58646e22021-08-23 23:51:46 -0700587 distributed_clock::time_point distributed_now() {
588 return scheduler_->distributed_now();
589 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590
Austin Schuh58646e22021-08-23 23:51:46 -0700591 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
592
593 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700594
595 void MakeRawWatcher(
596 const Channel *channel,
597 ::std::function<void(const Context &context, const void *message)>
598 watcher) override;
599
600 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800601 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800602 return NewTimer(::std::unique_ptr<TimerHandler>(
603 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700604 }
605
606 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
607 const monotonic_clock::duration interval,
608 const monotonic_clock::duration offset =
609 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800610 return NewPhasedLoop(
611 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
612 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700613 }
614
615 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800616 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700617 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800618 logging::ScopedLogRestorer prev_logger;
619 if (log_impl_) {
620 prev_logger.Swap(log_impl_);
621 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700622 ScopedMarkRealtimeRestorer rt(priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700623 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700624 on_run();
625 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700626 }
627
Austin Schuh217a9782019-12-21 23:02:50 -0800628 const Node *node() const override { return node_; }
629
James Kuszmaul3ae42262019-11-08 12:33:41 -0800630 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700631 name_ = std::string(name);
632 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800633 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634
635 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
636
Austin Schuh39788ff2019-12-01 18:22:57 -0800637 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700638 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800639 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700640 }
641
Austin Schuh39788ff2019-12-01 18:22:57 -0800642 int priority() const override { return priority_; }
643
Brian Silverman6a54ff32020-04-28 16:41:39 -0700644 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
645 CHECK(!is_running()) << ": Cannot set affinity while running.";
646 }
647
Tyler Chatow67ddb032020-01-12 14:30:04 -0800648 void Setup() {
649 MaybeScheduleTimingReports();
650 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800651 log_sender_.Initialize(&name_,
652 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700653 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800654 }
655 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800656
Brian Silverman4f4e0612020-08-12 19:54:41 -0700657 int NumberBuffers(const Channel *channel) override;
658
Austin Schuh83c7f702021-01-19 22:36:29 -0800659 const UUID &boot_uuid() const override {
660 return node_event_loop_factory_->boot_uuid();
661 }
662
Alex Perrycb7da4b2019-08-28 19:35:56 -0700663 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800664 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800665 friend class SimulatedPhasedLoopHandler;
666 friend class SimulatedWatcher;
667
Austin Schuh58646e22021-08-23 23:51:46 -0700668 // We have a condition where we register a startup handler, but then get shut
669 // down before it runs. This results in a segfault if we are lucky, and
670 // corruption otherwise. To handle that, allocate a small object which points
671 // back to us and can be freed when the function is freed. That object can
672 // then be updated when we get destroyed so setup is not called.
673 struct StartupTracker {
674 SimulatedEventLoop *loop = nullptr;
675 bool has_setup = false;
676 };
677
Austin Schuh7d87b672019-12-01 20:23:49 -0800678 void HandleEvent() {
679 while (true) {
680 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
681 break;
682 }
683
684 EventLoopEvent *event = PopEvent();
685 event->HandleEvent();
686 }
687 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800688
Austin Schuh39788ff2019-12-01 18:22:57 -0800689 pid_t GetTid() override { return tid_; }
690
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800692 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700693 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700694 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700695
696 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800697
698 int priority_ = 0;
699
Austin Schuh7d87b672019-12-01 20:23:49 -0800700 std::chrono::nanoseconds send_delay_;
701
Austin Schuh217a9782019-12-21 23:02:50 -0800702 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800703 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800704
705 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700706 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800707
708 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700709
710 std::shared_ptr<StartupTracker> startup_tracker_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700711};
712
Austin Schuh7d87b672019-12-01 20:23:49 -0800713void SimulatedEventLoopFactory::set_send_delay(
714 std::chrono::nanoseconds send_delay) {
715 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700716 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700717 if (node) {
718 for (SimulatedEventLoop *loop : node->event_loops_) {
719 loop->set_send_delay(send_delay_);
720 }
721 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800722 }
723}
724
Alex Perrycb7da4b2019-08-28 19:35:56 -0700725void SimulatedEventLoop::MakeRawWatcher(
726 const Channel *channel,
727 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800728 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800729
Austin Schuh057d29f2021-08-21 23:05:15 -0700730 std::unique_ptr<SimulatedWatcher> shm_watcher =
731 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
732 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800733
734 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700735
Austin Schuh39788ff2019-12-01 18:22:57 -0800736 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700737 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
738 << " " << name() << " MakeRawWatcher(\""
739 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800740
741 // Order of operations gets kinda wonky if we let people make watchers after
742 // running once. If someone has a valid use case, we can reconsider.
743 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700744}
745
746std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
747 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800748 TakeSender(channel);
749
Austin Schuh58646e22021-08-23 23:51:46 -0700750 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
751 << " " << name() << " MakeRawSender(\""
752 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700753 return GetSimulatedChannel(channel)->MakeRawSender(this);
754}
755
756std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
757 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800758 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800759
Austin Schuhca4828c2019-12-28 14:21:35 -0800760 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
761 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
762 << "\", \"type\": \"" << channel->type()->string_view()
763 << "\" } is not able to be fetched on this node. Check your "
764 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800765 }
766
Austin Schuh58646e22021-08-23 23:51:46 -0700767 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
768 << " " << name() << " MakeRawFetcher(\""
769 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800770 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700771}
772
773SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
774 const Channel *channel) {
775 auto it = channels_->find(SimpleChannel(channel));
776 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800777 it =
778 channels_
779 ->emplace(
780 SimpleChannel(channel),
781 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
782 channel, std::chrono::nanoseconds(
783 configuration()->channel_storage_duration()))))
784 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700785 }
786 return it->second.get();
787}
788
Brian Silverman4f4e0612020-08-12 19:54:41 -0700789int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
790 return GetSimulatedChannel(channel)->number_buffers();
791}
792
Austin Schuh7d87b672019-12-01 20:23:49 -0800793SimulatedWatcher::SimulatedWatcher(
794 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800795 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800796 std::function<void(const Context &context, const void *message)> fn)
797 : WatcherState(simulated_event_loop, channel, std::move(fn)),
798 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700799 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800800 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700801 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700802 token_(scheduler_->InvalidToken()) {
803 VLOG(1) << simulated_event_loop_->distributed_now() << " "
804 << NodeName(simulated_event_loop_->node())
805 << simulated_event_loop_->monotonic_now() << " "
806 << simulated_event_loop_->name() << " Watching "
807 << configuration::StrippedChannelToString(channel_);
808}
Austin Schuh7d87b672019-12-01 20:23:49 -0800809
810SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700811 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700812 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700813 << simulated_event_loop_->monotonic_now() << " "
814 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700815 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800816 simulated_event_loop_->RemoveEvent(&event_);
817 if (token_ != scheduler_->InvalidToken()) {
818 scheduler_->Deschedule(token_);
819 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700820 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800821}
822
Austin Schuh8fb315a2020-11-19 22:33:58 -0800823bool SimulatedWatcher::has_run() const {
824 return simulated_event_loop_->has_run();
825}
826
Austin Schuh7d87b672019-12-01 20:23:49 -0800827void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800828 monotonic_clock::time_point event_time =
829 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800830
831 // Messages are queued in order. If we are the first, add ourselves.
832 // Otherwise, don't.
833 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800834 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800835 simulated_event_loop_->AddEvent(&event_);
836
837 DoSchedule(event_time);
838 }
839
840 msgs_.emplace_back(message);
841}
842
843void SimulatedWatcher::HandleEvent() {
Austin Schuh7d87b672019-12-01 20:23:49 -0800844 const monotonic_clock::time_point monotonic_now =
845 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700846 VLOG(1) << simulated_event_loop_->distributed_now() << " "
847 << NodeName(simulated_event_loop_->node())
848 << simulated_event_loop_->monotonic_now() << " "
849 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700850 << configuration::StrippedChannelToString(channel_);
851 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
852
Tyler Chatow67ddb032020-01-12 14:30:04 -0800853 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700854 if (simulated_event_loop_->log_impl_) {
855 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800856 }
Austin Schuhad154822019-12-27 15:45:13 -0800857 Context context = msgs_.front()->context;
858
Brian Silverman4f4e0612020-08-12 19:54:41 -0700859 if (channel_->read_method() != ReadMethod::PIN) {
860 context.buffer_index = -1;
861 }
Austin Schuhad154822019-12-27 15:45:13 -0800862 if (context.remote_queue_index == 0xffffffffu) {
863 context.remote_queue_index = context.queue_index;
864 }
Austin Schuh58646e22021-08-23 23:51:46 -0700865 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800866 context.monotonic_remote_time = context.monotonic_event_time;
867 }
Austin Schuh58646e22021-08-23 23:51:46 -0700868 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800869 context.realtime_remote_time = context.realtime_event_time;
870 }
871
Austin Schuhcc6070c2020-10-10 20:25:56 -0700872 {
873 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
874 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
875 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800876
877 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700878 if (token_ != scheduler_->InvalidToken()) {
879 scheduler_->Deschedule(token_);
880 token_ = scheduler_->InvalidToken();
881 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800882 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800883 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800884 simulated_event_loop_->AddEvent(&event_);
885
886 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800887 }
888}
889
890void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700891 CHECK(token_ == scheduler_->InvalidToken())
892 << ": May not schedule multiple times";
893 token_ = scheduler_->Schedule(
894 event_time + simulated_event_loop_->send_delay(), [this]() {
895 DCHECK(token_ != scheduler_->InvalidToken());
896 token_ = scheduler_->InvalidToken();
897 simulated_event_loop_->HandleEvent();
898 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800899}
900
901void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700902 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800903 watcher->SetSimulatedChannel(this);
904 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700905}
906
907::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800908 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700909 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
910}
911
Austin Schuh39788ff2019-12-01 18:22:57 -0800912::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
913 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700914 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800915 ::std::unique_ptr<SimulatedFetcher> fetcher(
916 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700917 fetchers_.push_back(fetcher.get());
918 return ::std::move(fetcher);
919}
920
milind1f1dca32021-07-03 13:50:07 -0700921std::optional<uint32_t> SimulatedChannel::Send(
922 std::shared_ptr<SimulatedMessage> message) {
923 std::optional<uint32_t> queue_index = {next_queue_index_.index()};
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700924
milind1f1dca32021-07-03 13:50:07 -0700925 message->context.queue_index = *queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700926 // Points to the actual data depending on the size set in context. Data may
927 // allocate more than the actual size of the message, so offset from the back
928 // of that to get the actual start of the data.
929 message->context.data =
930 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -0700931
932 DCHECK(channel()->has_schema())
933 << ": Missing schema for channel "
934 << configuration::StrippedChannelToString(channel());
935 DCHECK(flatbuffers::Verify(
936 *channel()->schema(), *channel()->schema()->root_table(),
937 static_cast<const uint8_t *>(message->context.data),
938 message->context.size))
939 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
940 << channel()->type()->c_str();
941
Alex Perrycb7da4b2019-08-28 19:35:56 -0700942 next_queue_index_ = next_queue_index_.Increment();
943
944 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800945 for (SimulatedWatcher *watcher : watchers_) {
946 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800947 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700948 }
949 }
950 for (auto &fetcher : fetchers_) {
951 fetcher->Enqueue(message);
952 }
Austin Schuhad154822019-12-27 15:45:13 -0800953 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700954}
955
956void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
957 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
958}
959
Austin Schuh8fb315a2020-11-19 22:33:58 -0800960SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
961 SimulatedEventLoop *event_loop)
962 : RawSender(event_loop, simulated_channel->channel()),
963 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -0700964 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800965 simulated_channel_->CountSenderCreated();
966}
967
968SimulatedSender::~SimulatedSender() {
969 simulated_channel_->CountSenderDestroyed();
970}
971
milind1f1dca32021-07-03 13:50:07 -0700972RawSender::Error SimulatedSender::DoSend(
973 size_t length, monotonic_clock::time_point monotonic_remote_time,
974 realtime_clock::time_point realtime_remote_time,
975 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh58646e22021-08-23 23:51:46 -0700976 VLOG(1) << simulated_event_loop_->distributed_now() << " "
977 << NodeName(simulated_event_loop_->node())
978 << simulated_event_loop_->monotonic_now() << " "
979 << simulated_event_loop_->name() << " Send "
980 << configuration::StrippedChannelToString(channel());
981
Austin Schuh8fb315a2020-11-19 22:33:58 -0800982 // The allocations in here are due to infrastructure and don't count in the
983 // no mallocs in RT code.
984 ScopedNotRealtime nrt;
985 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -0700986 message_->context.monotonic_event_time =
987 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800988 message_->context.monotonic_remote_time = monotonic_remote_time;
989 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -0700990 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800991 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -0700992 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800993 CHECK_LE(length, message_->context.size);
994 message_->context.size = length;
995
milind1f1dca32021-07-03 13:50:07 -0700996 const std::optional<uint32_t> optional_queue_index =
997 simulated_channel_->Send(message_);
998
999 // Check that we are not sending messages too fast
1000 if (!optional_queue_index) {
1001 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1002 << NodeName(simulated_event_loop_->node())
1003 << simulated_event_loop_->monotonic_now() << " "
1004 << simulated_event_loop_->name()
1005 << "\nMessages were sent too fast:\n"
1006 << "For channel: "
1007 << configuration::CleanedChannelToString(
1008 simulated_channel_->channel())
1009 << '\n'
1010 << "Tried to send more than " << simulated_channel_->queue_size()
1011 << " (queue size) messages in the last "
1012 << std::chrono::duration<double>(
1013 simulated_channel_->channel_storage_duration())
1014 .count()
1015 << " seconds (channel storage duration)"
1016 << "\n\n";
1017 return Error::kMessagesSentTooFast;
1018 }
1019
1020 sent_queue_index_ = *optional_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -07001021 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
1022 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -08001023
1024 // Drop the reference to the message so that we allocate a new message for
1025 // next time. Otherwise we will continue to reuse the same memory for all
1026 // messages and corrupt it.
1027 message_.reset();
milind1f1dca32021-07-03 13:50:07 -07001028 return Error::kOk;
Austin Schuh8fb315a2020-11-19 22:33:58 -08001029}
1030
milind1f1dca32021-07-03 13:50:07 -07001031RawSender::Error SimulatedSender::DoSend(
1032 const void *msg, size_t size,
1033 monotonic_clock::time_point monotonic_remote_time,
1034 realtime_clock::time_point realtime_remote_time,
1035 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001036 CHECK_LE(size, this->size())
1037 << ": Attempting to send too big a message on "
1038 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001039
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001040 // Allocates an aligned buffer in which to copy unaligned msg.
1041 auto [span, mutable_span] = MakeSharedSpan(size);
1042 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001043
1044 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001045 // queue_index will be populated in simulated_channel_.
1046 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001047
1048 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001049 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001050}
1051
milind1f1dca32021-07-03 13:50:07 -07001052RawSender::Error SimulatedSender::DoSend(
1053 const RawSender::SharedSpan data,
1054 monotonic_clock::time_point monotonic_remote_time,
1055 realtime_clock::time_point realtime_remote_time,
1056 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001057 CHECK_LE(data->size(), this->size())
1058 << ": Attempting to send too big a message on "
1059 << configuration::CleanedChannelToString(simulated_channel_->channel());
1060
1061 // Constructs a message sharing the already allocated and aligned message
1062 // data.
1063 message_ = SimulatedMessage::Make(simulated_channel_, data);
1064
1065 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1066 remote_queue_index, source_boot_uuid);
1067}
1068
Austin Schuh39788ff2019-12-01 18:22:57 -08001069SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001070 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1071 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001072 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001073 simulated_event_loop_(simulated_event_loop),
1074 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001075 scheduler_(scheduler),
1076 token_(scheduler_->InvalidToken()) {}
1077
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001078void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
1079 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -08001080 // The allocations in here are due to infrastructure and don't count in the no
1081 // mallocs in RT code.
1082 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001083 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001084 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001085 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001086 base_ = base;
1087 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001088 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
1089 DCHECK(token_ != scheduler_->InvalidToken());
1090 token_ = scheduler_->InvalidToken();
1091 simulated_event_loop_->HandleEvent();
1092 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001093 event_.set_event_time(base_);
1094 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001095}
1096
1097void SimulatedTimerHandler::HandleEvent() {
Austin Schuh58646e22021-08-23 23:51:46 -07001098 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001099 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001100 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1101 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1102 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001103 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001104 if (simulated_event_loop_->log_impl_) {
1105 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001106 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001107 if (token_ != scheduler_->InvalidToken()) {
1108 scheduler_->Deschedule(token_);
1109 token_ = scheduler_->InvalidToken();
1110 }
Austin Schuh58646e22021-08-23 23:51:46 -07001111 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001112 // Reschedule.
1113 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001114 token_ = scheduler_->Schedule(base_, [this]() {
1115 DCHECK(token_ != scheduler_->InvalidToken());
1116 token_ = scheduler_->InvalidToken();
1117 simulated_event_loop_->HandleEvent();
1118 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001119 event_.set_event_time(base_);
1120 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001121 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001122
Austin Schuhcc6070c2020-10-10 20:25:56 -07001123 {
1124 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1125 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
1126 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001127}
1128
Austin Schuh7d87b672019-12-01 20:23:49 -08001129void SimulatedTimerHandler::Disable() {
1130 simulated_event_loop_->RemoveEvent(&event_);
1131 if (token_ != scheduler_->InvalidToken()) {
1132 scheduler_->Deschedule(token_);
1133 token_ = scheduler_->InvalidToken();
1134 }
1135}
1136
Austin Schuh39788ff2019-12-01 18:22:57 -08001137SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001138 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1139 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001140 const monotonic_clock::duration offset)
1141 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1142 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001143 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001144 scheduler_(scheduler),
1145 token_(scheduler_->InvalidToken()) {}
1146
Austin Schuh7d87b672019-12-01 20:23:49 -08001147SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1148 if (token_ != scheduler_->InvalidToken()) {
1149 scheduler_->Deschedule(token_);
1150 token_ = scheduler_->InvalidToken();
1151 }
1152 simulated_event_loop_->RemoveEvent(&event_);
1153}
1154
1155void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -08001156 monotonic_clock::time_point monotonic_now =
1157 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001158 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1159 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001160 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001161 if (simulated_event_loop_->log_impl_) {
1162 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001163 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001164
1165 {
1166 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1167 Call([monotonic_now]() { return monotonic_now; },
1168 [this](monotonic_clock::time_point sleep_time) {
1169 Schedule(sleep_time);
1170 });
1171 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001172}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001173
Austin Schuh7d87b672019-12-01 20:23:49 -08001174void SimulatedPhasedLoopHandler::Schedule(
1175 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001176 // The allocations in here are due to infrastructure and don't count in the no
1177 // mallocs in RT code.
1178 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001179 if (token_ != scheduler_->InvalidToken()) {
1180 scheduler_->Deschedule(token_);
1181 token_ = scheduler_->InvalidToken();
1182 }
1183 token_ = scheduler_->Schedule(sleep_time, [this]() {
1184 DCHECK(token_ != scheduler_->InvalidToken());
1185 token_ = scheduler_->InvalidToken();
1186 simulated_event_loop_->HandleEvent();
1187 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001188 event_.set_event_time(sleep_time);
1189 simulated_event_loop_->AddEvent(&event_);
1190}
1191
Alex Perrycb7da4b2019-08-28 19:35:56 -07001192SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1193 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001194 : configuration_(CHECK_NOTNULL(configuration)),
1195 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001196 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001197 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001198 node_factories_.emplace_back(
1199 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001200 }
Austin Schuh898f4972020-01-11 17:21:25 -08001201
1202 if (configuration::MultiNode(configuration)) {
1203 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1204 }
Austin Schuh15649d62019-12-28 16:36:38 -08001205}
1206
Alex Perrycb7da4b2019-08-28 19:35:56 -07001207SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1208
Austin Schuhac0771c2020-01-07 18:36:30 -08001209NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001210 std::string_view node) {
1211 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1212}
1213
1214NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001215 const Node *node) {
1216 auto result = std::find_if(
1217 node_factories_.begin(), node_factories_.end(),
1218 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1219 return node_factory->node() == node;
1220 });
1221
1222 CHECK(result != node_factories_.end())
1223 << ": Failed to find node " << FlatbufferToJson(node);
1224
1225 return result->get();
1226}
1227
Austin Schuh87dd3832021-01-01 23:07:31 -08001228void SimulatedEventLoopFactory::SetTimeConverter(
1229 TimeConverter *time_converter) {
1230 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1231 factory->SetTimeConverter(time_converter);
1232 }
Austin Schuh58646e22021-08-23 23:51:46 -07001233 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001234}
1235
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001236::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001237 std::string_view name, const Node *node) {
1238 if (node == nullptr) {
1239 CHECK(!configuration::MultiNode(configuration()))
1240 << ": Can't make a single node event loop in a multi-node world.";
1241 } else {
1242 CHECK(configuration::MultiNode(configuration()))
1243 << ": Can't make a multi-node event loop in a single-node world.";
1244 }
1245 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1246}
1247
Austin Schuh057d29f2021-08-21 23:05:15 -07001248NodeEventLoopFactory::NodeEventLoopFactory(
1249 EventSchedulerScheduler *scheduler_scheduler,
1250 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001251 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1252 factory_(factory),
1253 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001254 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001255 scheduler_.set_started([this]() {
1256 started_ = true;
1257 for (SimulatedEventLoop *event_loop : event_loops_) {
1258 event_loop->SetIsRunning(true);
1259 }
1260 });
1261 scheduler_.set_on_shutdown([this]() {
1262 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1263 << monotonic_now() << " Shutting down node.";
1264 Shutdown();
1265 ScheduleStartup();
1266 });
1267 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001268}
1269
1270NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001271 if (started_) {
1272 for (std::function<void()> &fn : on_shutdown_) {
1273 fn();
1274 }
1275
1276 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1277 << monotonic_now() << " Shutting down applications.";
1278 applications_.clear();
1279 started_ = false;
1280 }
1281
1282 if (event_loops_.size() != 0u) {
1283 for (SimulatedEventLoop *event_loop : event_loops_) {
1284 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1285 << monotonic_now() << " Event loop '" << event_loop->name()
1286 << "' failed to shut down";
1287 }
1288 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001289 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1290}
1291
Austin Schuh58646e22021-08-23 23:51:46 -07001292void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001293 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001294 << ": Can only register OnStartup handlers when not running.";
1295 on_startup_.emplace_back(std::move(fn));
1296 if (started_) {
1297 size_t on_startup_index = on_startup_.size() - 1;
1298 scheduler_.ScheduleOnStartup(
1299 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1300 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001301}
1302
Austin Schuh58646e22021-08-23 23:51:46 -07001303void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1304 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001305}
Austin Schuh057d29f2021-08-21 23:05:15 -07001306
Austin Schuh58646e22021-08-23 23:51:46 -07001307void NodeEventLoopFactory::ScheduleStartup() {
1308 scheduler_.ScheduleOnStartup([this]() {
1309 UUID next_uuid = scheduler_.boot_uuid();
1310 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001311 CHECK_EQ(boot_uuid_, UUID::Zero())
1312 << ": Boot UUID changed without restarting. Did TimeConverter "
1313 "change the boot UUID without signaling a restart, or did you "
1314 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001315 boot_uuid_ = next_uuid;
1316 }
1317 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1318 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1319 Startup();
1320 });
1321}
1322
1323void NodeEventLoopFactory::Startup() {
1324 CHECK(!started_);
1325 for (size_t i = 0; i < on_startup_.size(); ++i) {
1326 on_startup_[i]();
1327 }
1328}
1329
1330void NodeEventLoopFactory::Shutdown() {
1331 for (SimulatedEventLoop *event_loop : event_loops_) {
1332 event_loop->SetIsRunning(false);
1333 }
1334
1335 CHECK(started_);
1336 started_ = false;
1337 for (std::function<void()> &fn : on_shutdown_) {
1338 fn();
1339 }
1340
1341 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1342 << monotonic_now() << " Shutting down applications.";
1343 applications_.clear();
1344
1345 if (event_loops_.size() != 0u) {
1346 for (SimulatedEventLoop *event_loop : event_loops_) {
1347 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1348 << monotonic_now() << " Event loop '" << event_loop->name()
1349 << "' failed to shut down";
1350 }
1351 }
1352 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1353 boot_uuid_ = UUID::Zero();
1354
1355 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001356}
1357
Alex Perrycb7da4b2019-08-28 19:35:56 -07001358void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001359 // This sets running to true too.
Austin Schuh057d29f2021-08-21 23:05:15 -07001360 scheduler_scheduler_.RunOnStartup();
Austin Schuh8bd96322020-02-13 21:18:22 -08001361 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001362 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1363 if (node) {
1364 for (SimulatedEventLoop *loop : node->event_loops_) {
1365 loop->SetIsRunning(false);
1366 }
1367 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001368 }
1369}
1370
1371void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001372 // This sets running to true too.
Austin Schuh057d29f2021-08-21 23:05:15 -07001373 scheduler_scheduler_.RunOnStartup();
Austin Schuh8bd96322020-02-13 21:18:22 -08001374 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001375 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1376 if (node) {
1377 for (SimulatedEventLoop *loop : node->event_loops_) {
1378 loop->SetIsRunning(false);
1379 }
1380 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001381 }
1382}
1383
Austin Schuh87dd3832021-01-01 23:07:31 -08001384void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001385
Austin Schuh6f3babe2020-01-26 20:34:50 -08001386void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001387 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001388 bridge_->DisableForwarding(channel);
1389}
1390
Austin Schuh4c3b9702020-08-30 11:34:55 -07001391void SimulatedEventLoopFactory::DisableStatistics() {
1392 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1393 bridge_->DisableStatistics();
1394}
1395
Austin Schuh48205e62021-11-12 14:13:18 -08001396void SimulatedEventLoopFactory::EnableStatistics() {
1397 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1398 bridge_->EnableStatistics();
1399}
1400
Austin Schuh2928ebe2021-02-07 22:10:27 -08001401void SimulatedEventLoopFactory::SkipTimingReport() {
1402 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001403
1404 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1405 if (node) {
1406 node->SkipTimingReport();
1407 }
1408 }
1409}
1410
1411void NodeEventLoopFactory::SkipTimingReport() {
1412 for (SimulatedEventLoop *event_loop : event_loops_) {
1413 event_loop->SkipTimingReport();
1414 }
1415 skip_timing_report_ = true;
1416}
1417
1418void NodeEventLoopFactory::EnableStatistics() {
1419 CHECK(factory_->bridge_)
1420 << ": Can't enable statistics without a message bridge.";
1421 factory_->bridge_->EnableStatistics(node_);
1422}
1423
1424void NodeEventLoopFactory::DisableStatistics() {
1425 CHECK(factory_->bridge_)
1426 << ": Can't disable statistics without a message bridge.";
1427 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001428}
1429
Austin Schuh58646e22021-08-23 23:51:46 -07001430::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
1431 std::string_view name) {
1432 CHECK(!scheduler_.is_running() || !started_)
1433 << ": Can't create an event loop while running";
1434
1435 pid_t tid = tid_;
1436 ++tid_;
1437 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1438 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
1439 node_, tid));
1440 result->set_name(name);
1441 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001442 if (skip_timing_report_) {
1443 result->SkipTimingReport();
1444 }
Austin Schuh58646e22021-08-23 23:51:46 -07001445
1446 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1447 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
1448 return std::move(result);
1449}
1450
1451void NodeEventLoopFactory::Disconnect(const Node *other) {
1452 factory_->bridge_->Disconnect(node_, other);
1453}
1454
1455void NodeEventLoopFactory::Connect(const Node *other) {
1456 factory_->bridge_->Connect(node_, other);
1457}
1458
Alex Perrycb7da4b2019-08-28 19:35:56 -07001459} // namespace aos