blob: 9e1248165ef60632556fda80f8be56b791321675 [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>
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08005#include <string_view>
Brian Silverman661eb8d2020-08-12 19:41:01 -07006#include <vector>
Alex Perrycb7da4b2019-08-28 19:35:56 -07007
8#include "absl/container/btree_map.h"
Brian Silverman661eb8d2020-08-12 19:41:01 -07009#include "aos/events/aos_logging.h"
Austin Schuh898f4972020-01-11 17:21:25 -080010#include "aos/events/simulated_network_bridge.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080011#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070012#include "aos/json_to_flatbuffer.h"
Austin Schuhcc6070c2020-10-10 20:25:56 -070013#include "aos/realtime.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/util/phased_loop.h"
15
16namespace aos {
17
Brian Silverman661eb8d2020-08-12 19:41:01 -070018class SimulatedEventLoop;
19class SimulatedFetcher;
20class SimulatedChannel;
21
22namespace {
23
Austin Schuh057d29f2021-08-21 23:05:15 -070024std::string NodeName(const Node *node) {
25 if (node == nullptr) {
26 return "";
27 }
28
29 return absl::StrCat(node->name()->string_view(), " ");
30}
31
Austin Schuhcc6070c2020-10-10 20:25:56 -070032class ScopedMarkRealtimeRestorer {
33 public:
34 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
35 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
36
37 private:
38 const bool rt_;
39 const bool prior_;
40};
41
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070042// Holds storage for a span object and the data referenced by that span for
43// compatibility with RawSender::SharedSpan users. If constructed with
44// MakeSharedSpan, span points to only the aligned segment of the entire data.
45struct AlignedOwningSpan {
46 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
47 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
48 absl::Span<const uint8_t> span;
49 char data[];
50};
51
52// Constructs a span which owns its data through a shared_ptr. The owning span
53// points to a const view of the data; also returns a temporary mutable span
54// which is only valid while the const shared span is kept alive.
55std::pair<RawSender::SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(
56 size_t size) {
57 AlignedOwningSpan *const span = reinterpret_cast<AlignedOwningSpan *>(
58 malloc(sizeof(AlignedOwningSpan) + size + kChannelDataAlignment - 1));
59
60 absl::Span mutable_span(
61 reinterpret_cast<uint8_t *>(RoundChannelData(&span->data[0], size)),
62 size);
63 new (span) AlignedOwningSpan{.span = mutable_span};
64
65 return std::make_pair(
66 RawSender::SharedSpan(
67 std::shared_ptr<AlignedOwningSpan>(span,
68 [](AlignedOwningSpan *s) {
69 s->~AlignedOwningSpan();
70 free(s);
71 }),
72 &span->span),
73 mutable_span);
74}
75
Alex Perrycb7da4b2019-08-28 19:35:56 -070076// Container for both a message, and the context for it for simulation. This
77// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070078struct SimulatedMessage final {
79 SimulatedMessage(const SimulatedMessage &) = delete;
80 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070081 ~SimulatedMessage();
Brian Silverman661eb8d2020-08-12 19:41:01 -070082
83 // Creates a SimulatedMessage with size bytes of storage.
84 // This is a shared_ptr so we don't have to implement refcounting or copying.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070085 static std::shared_ptr<SimulatedMessage> Make(
86 SimulatedChannel *channel, const RawSender::SharedSpan data);
Brian Silverman661eb8d2020-08-12 19:41:01 -070087
Alex Perrycb7da4b2019-08-28 19:35:56 -070088 // Context for the data.
89 Context context;
90
Brian Silverman661eb8d2020-08-12 19:41:01 -070091 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070092
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070093 // Owning span to this message's data. Depending on the sender may either
94 // represent the data of just the flatbuffer, or max channel size.
95 RawSender::SharedSpan data;
Alex Perrycb7da4b2019-08-28 19:35:56 -070096
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070097 // Mutable view of above data. If empty, this message is not mutable.
98 absl::Span<uint8_t> mutable_data;
Brian Silverman661eb8d2020-08-12 19:41:01 -070099
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700100 // Determines whether this message is mutable. Used for Send where the user
101 // fills out a message stored internally then gives us the size of data used.
102 bool is_mutable() const { return data->size() == mutable_data.size(); }
103
104 // Note: this should be private but make_shared requires it to be public. Use
105 // Make() above to construct.
Brian Silverman661eb8d2020-08-12 19:41:01 -0700106 SimulatedMessage(SimulatedChannel *channel_in);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700107};
108
Brian Silverman661eb8d2020-08-12 19:41:01 -0700109} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -0800110
Brian Silverman661eb8d2020-08-12 19:41:01 -0700111// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
112// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -0800113class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -0800114 public:
Austin Schuh7d87b672019-12-01 20:23:49 -0800115 SimulatedWatcher(
116 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
117 const Channel *channel,
118 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -0800119
Austin Schuh7d87b672019-12-01 20:23:49 -0800120 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -0800121
Austin Schuh8fb315a2020-11-19 22:33:58 -0800122 bool has_run() const;
123
Austin Schuh39788ff2019-12-01 18:22:57 -0800124 void Startup(EventLoop * /*event_loop*/) override {}
125
Austin Schuh7d87b672019-12-01 20:23:49 -0800126 void Schedule(std::shared_ptr<SimulatedMessage> message);
127
128 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800129
130 void SetSimulatedChannel(SimulatedChannel *channel) {
131 simulated_channel_ = channel;
132 }
133
134 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800135 void DoSchedule(monotonic_clock::time_point event_time);
136
137 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
138
Brian Silverman4f4e0612020-08-12 19:54:41 -0700139 SimulatedEventLoop *const simulated_event_loop_;
140 const Channel *const channel_;
141 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800142 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800143 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800144 SimulatedChannel *simulated_channel_ = nullptr;
145};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700146
147class SimulatedChannel {
148 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800149 explicit SimulatedChannel(const Channel *channel,
Brian Silverman661eb8d2020-08-12 19:41:01 -0700150 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800151 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700152 channel_storage_duration_(channel_storage_duration),
153 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
154 available_buffer_indices_.reserve(number_buffers());
155 for (int i = 0; i < number_buffers(); ++i) {
156 available_buffer_indices_.push_back(i);
157 }
158 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159
Brian Silverman661eb8d2020-08-12 19:41:01 -0700160 ~SimulatedChannel() {
161 latest_message_.reset();
162 CHECK_EQ(static_cast<size_t>(number_buffers()),
163 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800164 CHECK_EQ(0u, fetchers_.size())
165 << configuration::StrippedChannelToString(channel());
166 CHECK_EQ(0u, watchers_.size())
167 << configuration::StrippedChannelToString(channel());
168 CHECK_EQ(0, sender_count_)
169 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700170 }
171
172 // The number of messages we pretend to have in the queue.
173 int queue_size() const {
174 return channel()->frequency() *
175 std::chrono::duration_cast<std::chrono::duration<double>>(
176 channel_storage_duration_)
177 .count();
178 }
179
180 // The number of extra buffers (beyond the queue) we pretend to have.
181 int number_scratch_buffers() const {
182 // We need to start creating messages before we know how many
183 // senders+readers we'll have, so we need to just pick something which is
184 // always big enough.
185 return 50;
186 }
187
188 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
189
190 int GetBufferIndex() {
191 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
192 const int result = available_buffer_indices_.back();
193 available_buffer_indices_.pop_back();
194 return result;
195 }
196
197 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700198 // This extra checking has a large performance hit with sanitizers that
199 // track memory accesses, so just skip it.
200#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700201 DCHECK(std::find(available_buffer_indices_.begin(),
202 available_buffer_indices_.end(),
203 i) == available_buffer_indices_.end())
204 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800205#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700206 available_buffer_indices_.push_back(i);
207 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700208
209 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800210 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700211
212 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800213 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700214
215 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800216 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800217
Austin Schuh7d87b672019-12-01 20:23:49 -0800218 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800219 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
220 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700221
Austin Schuhad154822019-12-27 15:45:13 -0800222 // Sends the message to all the connected receivers and fetchers. Returns the
223 // sent queue index.
224 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700225
226 // Unregisters a fetcher.
227 void UnregisterFetcher(SimulatedFetcher *fetcher);
228
229 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
230
Austin Schuh39788ff2019-12-01 18:22:57 -0800231 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700232
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800233 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800234 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700235 }
236
Austin Schuh39788ff2019-12-01 18:22:57 -0800237 const Channel *channel() const { return channel_; }
238
Austin Schuhe516ab02020-05-06 21:37:04 -0700239 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700240 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700241 if (sender_count_ >= channel()->num_senders()) {
242 LOG(FATAL) << "Failed to create sender on "
243 << configuration::CleanedChannelToString(channel())
244 << ", too many senders.";
245 }
246 ++sender_count_;
247 }
Brian Silverman77162972020-08-12 19:52:40 -0700248
Austin Schuhe516ab02020-05-06 21:37:04 -0700249 void CountSenderDestroyed() {
250 --sender_count_;
251 CHECK_GE(sender_count_, 0);
252 }
253
Alex Perrycb7da4b2019-08-28 19:35:56 -0700254 private:
Brian Silverman77162972020-08-12 19:52:40 -0700255 void CheckBufferCount() {
256 int reader_count = 0;
257 if (channel()->read_method() == ReadMethod::PIN) {
258 reader_count = watchers_.size() + fetchers_.size();
259 }
260 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
261 }
262
263 void CheckReaderCount() {
264 if (channel()->read_method() != ReadMethod::PIN) {
265 return;
266 }
267 CheckBufferCount();
268 const int reader_count = watchers_.size() + fetchers_.size();
269 if (reader_count >= channel()->num_readers()) {
270 LOG(FATAL) << "Failed to create reader on "
271 << configuration::CleanedChannelToString(channel())
272 << ", too many readers.";
273 }
274 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700275
276 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700277 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700278
279 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800280 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281
282 // List of all fetchers.
283 ::std::vector<SimulatedFetcher *> fetchers_;
284 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285
286 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700287
288 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700289
290 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291};
292
293namespace {
294
Brian Silverman661eb8d2020-08-12 19:41:01 -0700295std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700296 SimulatedChannel *channel, RawSender::SharedSpan data) {
Austin Schuh62288252020-11-18 23:26:04 -0800297 // The allocations in here are due to infrastructure and don't count in the no
298 // mallocs in RT code.
299 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700300
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700301 auto message = std::make_shared<SimulatedMessage>(channel);
302 message->context.size = data->size();
303 message->context.data = data->data();
304 message->data = std::move(data);
305
306 return message;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700307}
308
309SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
310 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700311 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700312}
313
314SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700315 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700316}
317
318class SimulatedSender : public RawSender {
319 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800320 SimulatedSender(SimulatedChannel *simulated_channel,
321 SimulatedEventLoop *event_loop);
322 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323
324 void *data() override {
325 if (!message_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700326 auto [span, mutable_span] =
327 MakeSharedSpan(simulated_channel_->max_size());
328 message_ = SimulatedMessage::Make(simulated_channel_, span);
329 message_->mutable_data = mutable_span;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700330 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700331 CHECK(message_->is_mutable());
332 return message_->mutable_data.data();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700333 }
334
335 size_t size() override { return simulated_channel_->max_size(); }
336
Austin Schuh58646e22021-08-23 23:51:46 -0700337 bool DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
338 realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700339 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700340 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700341
Austin Schuhad154822019-12-27 15:45:13 -0800342 bool DoSend(const void *msg, size_t size,
Austin Schuh58646e22021-08-23 23:51:46 -0700343 monotonic_clock::time_point monotonic_remote_time,
344 realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700345 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700346 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700347
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700348 bool DoSend(const SharedSpan data,
349 aos::monotonic_clock::time_point monotonic_remote_time,
350 aos::realtime_clock::time_point realtime_remote_time,
351 uint32_t remote_queue_index,
352 const UUID &source_boot_uuid) override;
353
Brian Silverman4f4e0612020-08-12 19:54:41 -0700354 int buffer_index() override {
355 // First, ensure message_ is allocated.
356 data();
357 return message_->context.buffer_index;
358 }
359
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360 private:
361 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700362 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700363
364 std::shared_ptr<SimulatedMessage> message_;
365};
366} // namespace
367
368class SimulatedFetcher : public RawFetcher {
369 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800370 explicit SimulatedFetcher(EventLoop *event_loop,
371 SimulatedChannel *simulated_channel)
372 : RawFetcher(event_loop, simulated_channel->channel()),
373 simulated_channel_(simulated_channel) {}
374 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375
Austin Schuh39788ff2019-12-01 18:22:57 -0800376 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800377 // The allocations in here are due to infrastructure and don't count in the
378 // no mallocs in RT code.
379 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800380 if (msgs_.size() == 0) {
381 return std::make_pair(false, monotonic_clock::min_time);
382 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700383
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700384 CHECK(!fell_behind_) << ": Got behind on "
385 << configuration::StrippedChannelToString(
386 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700387
Alex Perrycb7da4b2019-08-28 19:35:56 -0700388 SetMsg(msgs_.front());
389 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800390 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 }
392
Austin Schuh39788ff2019-12-01 18:22:57 -0800393 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800394 // The allocations in here are due to infrastructure and don't count in the
395 // no mallocs in RT code.
396 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700397 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800398 // TODO(austin): Can we just do this logic unconditionally? It is a lot
399 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800400 if (!msg_ && simulated_channel_->latest_message()) {
401 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800402 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800404 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700405 }
406 }
407
408 // We've had a message enqueued, so we don't need to go looking for the
409 // latest message from before we started.
410 SetMsg(msgs_.back());
411 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700412 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800413 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700414 }
415
416 private:
417 friend class SimulatedChannel;
418
419 // Updates the state inside RawFetcher to point to the data in msg_.
420 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
421 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700422 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700423 if (channel()->read_method() != ReadMethod::PIN) {
424 context_.buffer_index = -1;
425 }
Austin Schuhad154822019-12-27 15:45:13 -0800426 if (context_.remote_queue_index == 0xffffffffu) {
427 context_.remote_queue_index = context_.queue_index;
428 }
Austin Schuh58646e22021-08-23 23:51:46 -0700429 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800430 context_.monotonic_remote_time = context_.monotonic_event_time;
431 }
Austin Schuh58646e22021-08-23 23:51:46 -0700432 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800433 context_.realtime_remote_time = context_.realtime_event_time;
434 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435 }
436
437 // Internal method for Simulation to add a message to the buffer.
438 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
439 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700440 if (fell_behind_ ||
441 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
442 fell_behind_ = true;
443 // Might as well empty out all the intermediate messages now.
444 while (msgs_.size() > 1) {
445 msgs_.pop_front();
446 }
447 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 }
449
Austin Schuhac0771c2020-01-07 18:36:30 -0800450 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 std::shared_ptr<SimulatedMessage> msg_;
452
453 // Messages queued up but not in use.
454 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700455
456 // Whether we're currently "behind", which means a FetchNext call will fail.
457 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700458};
459
460class SimulatedTimerHandler : public TimerHandler {
461 public:
462 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800463 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800464 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800465 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700466
467 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800468 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800470 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700471
Austin Schuh7d87b672019-12-01 20:23:49 -0800472 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700473
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800475 SimulatedEventLoop *simulated_event_loop_;
476 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477 EventScheduler *scheduler_;
478 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800479
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 monotonic_clock::time_point base_;
481 monotonic_clock::duration repeat_offset_;
482};
483
484class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
485 public:
486 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800487 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700488 ::std::function<void(int)> fn,
489 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800490 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800491 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492
Austin Schuh7d87b672019-12-01 20:23:49 -0800493 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494
Austin Schuh7d87b672019-12-01 20:23:49 -0800495 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700496
497 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800498 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800499 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500
Austin Schuh39788ff2019-12-01 18:22:57 -0800501 EventScheduler *scheduler_;
502 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700503};
504
505class SimulatedEventLoop : public EventLoop {
506 public:
507 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700508 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
510 *channels,
511 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700512 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
513 pid_t tid)
Austin Schuh83c7f702021-01-19 22:36:29 -0800514 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800516 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700517 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700518 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800519 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700520 tid_(tid),
521 startup_tracker_(std::make_shared<StartupTracker>()) {
522 startup_tracker_->loop = this;
523 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
524 if (startup_tracker->loop) {
525 startup_tracker->loop->Setup();
526 startup_tracker->has_setup = true;
527 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700528 });
529
530 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531 }
Austin Schuh58646e22021-08-23 23:51:46 -0700532
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800534 // Trigger any remaining senders or fetchers to be cleared before destroying
535 // the event loop so the book keeping matches.
536 timing_report_sender_.reset();
537
538 // Force everything with a registered fd with epoll to be destroyed now.
539 timers_.clear();
540 phased_loops_.clear();
541 watchers_.clear();
542
Austin Schuh58646e22021-08-23 23:51:46 -0700543 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700544 if (*it == this) {
545 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546 break;
547 }
548 }
Austin Schuh58646e22021-08-23 23:51:46 -0700549 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
550 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
551 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 }
553
Austin Schuh057d29f2021-08-21 23:05:15 -0700554 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700555 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
556 << monotonic_now() << " " << name_ << " set_is_running(" << running
557 << ")";
558 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700559
560 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700561 if (running) {
562 has_run_ = true;
563 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700564 }
565
Austin Schuh8fb315a2020-11-19 22:33:58 -0800566 bool has_run() const { return has_run_; }
567
Austin Schuh7d87b672019-12-01 20:23:49 -0800568 std::chrono::nanoseconds send_delay() const { return send_delay_; }
569 void set_send_delay(std::chrono::nanoseconds send_delay) {
570 send_delay_ = send_delay;
571 }
572
Austin Schuh58646e22021-08-23 23:51:46 -0700573 monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800574 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700575 }
576
Austin Schuh58646e22021-08-23 23:51:46 -0700577 realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800578 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700579 }
580
Austin Schuh58646e22021-08-23 23:51:46 -0700581 distributed_clock::time_point distributed_now() {
582 return scheduler_->distributed_now();
583 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700584
Austin Schuh58646e22021-08-23 23:51:46 -0700585 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
586
587 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700588
589 void MakeRawWatcher(
590 const Channel *channel,
591 ::std::function<void(const Context &context, const void *message)>
592 watcher) override;
593
594 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800595 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800596 return NewTimer(::std::unique_ptr<TimerHandler>(
597 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598 }
599
600 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
601 const monotonic_clock::duration interval,
602 const monotonic_clock::duration offset =
603 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800604 return NewPhasedLoop(
605 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
606 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700607 }
608
609 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800610 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700611 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800612 logging::ScopedLogRestorer prev_logger;
613 if (log_impl_) {
614 prev_logger.Swap(log_impl_);
615 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700616 ScopedMarkRealtimeRestorer rt(priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700617 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700618 on_run();
619 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700620 }
621
Austin Schuh217a9782019-12-21 23:02:50 -0800622 const Node *node() const override { return node_; }
623
James Kuszmaul3ae42262019-11-08 12:33:41 -0800624 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700625 name_ = std::string(name);
626 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800627 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628
629 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
630
Austin Schuh39788ff2019-12-01 18:22:57 -0800631 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700632 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800633 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634 }
635
Austin Schuh39788ff2019-12-01 18:22:57 -0800636 int priority() const override { return priority_; }
637
Brian Silverman6a54ff32020-04-28 16:41:39 -0700638 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
639 CHECK(!is_running()) << ": Cannot set affinity while running.";
640 }
641
Tyler Chatow67ddb032020-01-12 14:30:04 -0800642 void Setup() {
643 MaybeScheduleTimingReports();
644 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800645 log_sender_.Initialize(&name_,
646 MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700647 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800648 }
649 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800650
Brian Silverman4f4e0612020-08-12 19:54:41 -0700651 int NumberBuffers(const Channel *channel) override;
652
Austin Schuh83c7f702021-01-19 22:36:29 -0800653 const UUID &boot_uuid() const override {
654 return node_event_loop_factory_->boot_uuid();
655 }
656
Alex Perrycb7da4b2019-08-28 19:35:56 -0700657 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800658 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800659 friend class SimulatedPhasedLoopHandler;
660 friend class SimulatedWatcher;
661
Austin Schuh58646e22021-08-23 23:51:46 -0700662 // We have a condition where we register a startup handler, but then get shut
663 // down before it runs. This results in a segfault if we are lucky, and
664 // corruption otherwise. To handle that, allocate a small object which points
665 // back to us and can be freed when the function is freed. That object can
666 // then be updated when we get destroyed so setup is not called.
667 struct StartupTracker {
668 SimulatedEventLoop *loop = nullptr;
669 bool has_setup = false;
670 };
671
Austin Schuh7d87b672019-12-01 20:23:49 -0800672 void HandleEvent() {
673 while (true) {
674 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
675 break;
676 }
677
678 EventLoopEvent *event = PopEvent();
679 event->HandleEvent();
680 }
681 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800682
Austin Schuh39788ff2019-12-01 18:22:57 -0800683 pid_t GetTid() override { return tid_; }
684
Alex Perrycb7da4b2019-08-28 19:35:56 -0700685 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800686 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700687 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700688 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700689
690 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800691
692 int priority_ = 0;
693
Austin Schuh7d87b672019-12-01 20:23:49 -0800694 std::chrono::nanoseconds send_delay_;
695
Austin Schuh217a9782019-12-21 23:02:50 -0800696 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800697 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800698
699 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700700 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800701
702 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700703
704 std::shared_ptr<StartupTracker> startup_tracker_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700705};
706
Austin Schuh7d87b672019-12-01 20:23:49 -0800707void SimulatedEventLoopFactory::set_send_delay(
708 std::chrono::nanoseconds send_delay) {
709 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700710 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700711 if (node) {
712 for (SimulatedEventLoop *loop : node->event_loops_) {
713 loop->set_send_delay(send_delay_);
714 }
715 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800716 }
717}
718
Alex Perrycb7da4b2019-08-28 19:35:56 -0700719void SimulatedEventLoop::MakeRawWatcher(
720 const Channel *channel,
721 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800722 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800723
Austin Schuh057d29f2021-08-21 23:05:15 -0700724 std::unique_ptr<SimulatedWatcher> shm_watcher =
725 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
726 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800727
728 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700729
Austin Schuh39788ff2019-12-01 18:22:57 -0800730 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700731 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
732 << " " << name() << " MakeRawWatcher(\""
733 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800734
735 // Order of operations gets kinda wonky if we let people make watchers after
736 // running once. If someone has a valid use case, we can reconsider.
737 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700738}
739
740std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
741 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800742 TakeSender(channel);
743
Austin Schuh58646e22021-08-23 23:51:46 -0700744 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
745 << " " << name() << " MakeRawSender(\""
746 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700747 return GetSimulatedChannel(channel)->MakeRawSender(this);
748}
749
750std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
751 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800752 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800753
Austin Schuhca4828c2019-12-28 14:21:35 -0800754 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
755 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
756 << "\", \"type\": \"" << channel->type()->string_view()
757 << "\" } is not able to be fetched on this node. Check your "
758 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800759 }
760
Austin Schuh58646e22021-08-23 23:51:46 -0700761 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
762 << " " << name() << " MakeRawFetcher(\""
763 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800764 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700765}
766
767SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
768 const Channel *channel) {
769 auto it = channels_->find(SimpleChannel(channel));
770 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800771 it =
772 channels_
773 ->emplace(
774 SimpleChannel(channel),
775 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
776 channel, std::chrono::nanoseconds(
777 configuration()->channel_storage_duration()))))
778 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700779 }
780 return it->second.get();
781}
782
Brian Silverman4f4e0612020-08-12 19:54:41 -0700783int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
784 return GetSimulatedChannel(channel)->number_buffers();
785}
786
Austin Schuh7d87b672019-12-01 20:23:49 -0800787SimulatedWatcher::SimulatedWatcher(
788 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800789 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800790 std::function<void(const Context &context, const void *message)> fn)
791 : WatcherState(simulated_event_loop, channel, std::move(fn)),
792 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700793 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800794 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700795 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700796 token_(scheduler_->InvalidToken()) {
797 VLOG(1) << simulated_event_loop_->distributed_now() << " "
798 << NodeName(simulated_event_loop_->node())
799 << simulated_event_loop_->monotonic_now() << " "
800 << simulated_event_loop_->name() << " Watching "
801 << configuration::StrippedChannelToString(channel_);
802}
Austin Schuh7d87b672019-12-01 20:23:49 -0800803
804SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700805 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700806 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700807 << simulated_event_loop_->monotonic_now() << " "
808 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700809 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800810 simulated_event_loop_->RemoveEvent(&event_);
811 if (token_ != scheduler_->InvalidToken()) {
812 scheduler_->Deschedule(token_);
813 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700814 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800815}
816
Austin Schuh8fb315a2020-11-19 22:33:58 -0800817bool SimulatedWatcher::has_run() const {
818 return simulated_event_loop_->has_run();
819}
820
Austin Schuh7d87b672019-12-01 20:23:49 -0800821void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800822 monotonic_clock::time_point event_time =
823 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800824
825 // Messages are queued in order. If we are the first, add ourselves.
826 // Otherwise, don't.
827 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800828 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800829 simulated_event_loop_->AddEvent(&event_);
830
831 DoSchedule(event_time);
832 }
833
834 msgs_.emplace_back(message);
835}
836
837void SimulatedWatcher::HandleEvent() {
Austin Schuh7d87b672019-12-01 20:23:49 -0800838 const monotonic_clock::time_point monotonic_now =
839 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700840 VLOG(1) << simulated_event_loop_->distributed_now() << " "
841 << NodeName(simulated_event_loop_->node())
842 << simulated_event_loop_->monotonic_now() << " "
843 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700844 << configuration::StrippedChannelToString(channel_);
845 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
846
Tyler Chatow67ddb032020-01-12 14:30:04 -0800847 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700848 if (simulated_event_loop_->log_impl_) {
849 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800850 }
Austin Schuhad154822019-12-27 15:45:13 -0800851 Context context = msgs_.front()->context;
852
Brian Silverman4f4e0612020-08-12 19:54:41 -0700853 if (channel_->read_method() != ReadMethod::PIN) {
854 context.buffer_index = -1;
855 }
Austin Schuhad154822019-12-27 15:45:13 -0800856 if (context.remote_queue_index == 0xffffffffu) {
857 context.remote_queue_index = context.queue_index;
858 }
Austin Schuh58646e22021-08-23 23:51:46 -0700859 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800860 context.monotonic_remote_time = context.monotonic_event_time;
861 }
Austin Schuh58646e22021-08-23 23:51:46 -0700862 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800863 context.realtime_remote_time = context.realtime_event_time;
864 }
865
Austin Schuhcc6070c2020-10-10 20:25:56 -0700866 {
867 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
868 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
869 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800870
871 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700872 if (token_ != scheduler_->InvalidToken()) {
873 scheduler_->Deschedule(token_);
874 token_ = scheduler_->InvalidToken();
875 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800876 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800877 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800878 simulated_event_loop_->AddEvent(&event_);
879
880 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800881 }
882}
883
884void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700885 CHECK(token_ == scheduler_->InvalidToken())
886 << ": May not schedule multiple times";
887 token_ = scheduler_->Schedule(
888 event_time + simulated_event_loop_->send_delay(), [this]() {
889 DCHECK(token_ != scheduler_->InvalidToken());
890 token_ = scheduler_->InvalidToken();
891 simulated_event_loop_->HandleEvent();
892 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800893}
894
895void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700896 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800897 watcher->SetSimulatedChannel(this);
898 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700899}
900
901::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800902 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700903 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
904}
905
Austin Schuh39788ff2019-12-01 18:22:57 -0800906::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
907 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700908 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800909 ::std::unique_ptr<SimulatedFetcher> fetcher(
910 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700911 fetchers_.push_back(fetcher.get());
912 return ::std::move(fetcher);
913}
914
Austin Schuhad154822019-12-27 15:45:13 -0800915uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
916 const uint32_t queue_index = next_queue_index_.index();
917 message->context.queue_index = queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700918
919 // Points to the actual data depending on the size set in context. Data may
920 // allocate more than the actual size of the message, so offset from the back
921 // of that to get the actual start of the data.
922 message->context.data =
923 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -0700924
925 DCHECK(channel()->has_schema())
926 << ": Missing schema for channel "
927 << configuration::StrippedChannelToString(channel());
928 DCHECK(flatbuffers::Verify(
929 *channel()->schema(), *channel()->schema()->root_table(),
930 static_cast<const uint8_t *>(message->context.data),
931 message->context.size))
932 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
933 << channel()->type()->c_str();
934
Alex Perrycb7da4b2019-08-28 19:35:56 -0700935 next_queue_index_ = next_queue_index_.Increment();
936
937 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800938 for (SimulatedWatcher *watcher : watchers_) {
939 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800940 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700941 }
942 }
943 for (auto &fetcher : fetchers_) {
944 fetcher->Enqueue(message);
945 }
Austin Schuhad154822019-12-27 15:45:13 -0800946
947 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700948}
949
950void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
951 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
952}
953
Austin Schuh8fb315a2020-11-19 22:33:58 -0800954SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
955 SimulatedEventLoop *event_loop)
956 : RawSender(event_loop, simulated_channel->channel()),
957 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -0700958 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800959 simulated_channel_->CountSenderCreated();
960}
961
962SimulatedSender::~SimulatedSender() {
963 simulated_channel_->CountSenderDestroyed();
964}
965
Austin Schuh8902fa52021-03-14 22:39:24 -0700966bool SimulatedSender::DoSend(size_t length,
967 monotonic_clock::time_point monotonic_remote_time,
968 realtime_clock::time_point realtime_remote_time,
969 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700970 const UUID &source_boot_uuid) {
Austin Schuh58646e22021-08-23 23:51:46 -0700971 VLOG(1) << simulated_event_loop_->distributed_now() << " "
972 << NodeName(simulated_event_loop_->node())
973 << simulated_event_loop_->monotonic_now() << " "
974 << simulated_event_loop_->name() << " Send "
975 << configuration::StrippedChannelToString(channel());
976
Austin Schuh8fb315a2020-11-19 22:33:58 -0800977 // The allocations in here are due to infrastructure and don't count in the
978 // no mallocs in RT code.
979 ScopedNotRealtime nrt;
980 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -0700981 message_->context.monotonic_event_time =
982 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800983 message_->context.monotonic_remote_time = monotonic_remote_time;
984 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -0700985 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800986 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -0700987 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800988 CHECK_LE(length, message_->context.size);
989 message_->context.size = length;
990
991 // TODO(austin): Track sending too fast.
992 sent_queue_index_ = simulated_channel_->Send(message_);
Austin Schuh58646e22021-08-23 23:51:46 -0700993 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
994 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800995
996 // Drop the reference to the message so that we allocate a new message for
997 // next time. Otherwise we will continue to reuse the same memory for all
998 // messages and corrupt it.
999 message_.reset();
1000 return true;
1001}
1002
Austin Schuh8902fa52021-03-14 22:39:24 -07001003bool SimulatedSender::DoSend(const void *msg, size_t size,
1004 monotonic_clock::time_point monotonic_remote_time,
1005 realtime_clock::time_point realtime_remote_time,
1006 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -07001007 const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001008 CHECK_LE(size, this->size())
1009 << ": Attempting to send too big a message on "
1010 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001011
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001012 // Allocates an aligned buffer in which to copy unaligned msg.
1013 auto [span, mutable_span] = MakeSharedSpan(size);
1014 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001015
1016 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001017 // queue_index will be populated in simulated_channel_.
1018 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001019
1020 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001021 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001022}
1023
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001024bool SimulatedSender::DoSend(const RawSender::SharedSpan data,
1025 monotonic_clock::time_point monotonic_remote_time,
1026 realtime_clock::time_point realtime_remote_time,
1027 uint32_t remote_queue_index,
1028 const UUID &source_boot_uuid) {
1029 CHECK_LE(data->size(), this->size())
1030 << ": Attempting to send too big a message on "
1031 << configuration::CleanedChannelToString(simulated_channel_->channel());
1032
1033 // Constructs a message sharing the already allocated and aligned message
1034 // data.
1035 message_ = SimulatedMessage::Make(simulated_channel_, data);
1036
1037 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1038 remote_queue_index, source_boot_uuid);
1039}
1040
Austin Schuh39788ff2019-12-01 18:22:57 -08001041SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001042 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1043 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001044 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001045 simulated_event_loop_(simulated_event_loop),
1046 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001047 scheduler_(scheduler),
1048 token_(scheduler_->InvalidToken()) {}
1049
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001050void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
1051 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -08001052 // The allocations in here are due to infrastructure and don't count in the no
1053 // mallocs in RT code.
1054 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001055 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001056 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001057 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001058 base_ = base;
1059 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001060 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
1061 DCHECK(token_ != scheduler_->InvalidToken());
1062 token_ = scheduler_->InvalidToken();
1063 simulated_event_loop_->HandleEvent();
1064 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001065 event_.set_event_time(base_);
1066 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001067}
1068
1069void SimulatedTimerHandler::HandleEvent() {
Austin Schuh58646e22021-08-23 23:51:46 -07001070 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001071 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001072 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1073 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1074 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001075 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001076 if (simulated_event_loop_->log_impl_) {
1077 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001078 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001079 if (token_ != scheduler_->InvalidToken()) {
1080 scheduler_->Deschedule(token_);
1081 token_ = scheduler_->InvalidToken();
1082 }
Austin Schuh58646e22021-08-23 23:51:46 -07001083 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001084 // Reschedule.
1085 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001086 token_ = scheduler_->Schedule(base_, [this]() {
1087 DCHECK(token_ != scheduler_->InvalidToken());
1088 token_ = scheduler_->InvalidToken();
1089 simulated_event_loop_->HandleEvent();
1090 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001091 event_.set_event_time(base_);
1092 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001093 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001094
Austin Schuhcc6070c2020-10-10 20:25:56 -07001095 {
1096 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1097 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
1098 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001099}
1100
Austin Schuh7d87b672019-12-01 20:23:49 -08001101void SimulatedTimerHandler::Disable() {
1102 simulated_event_loop_->RemoveEvent(&event_);
1103 if (token_ != scheduler_->InvalidToken()) {
1104 scheduler_->Deschedule(token_);
1105 token_ = scheduler_->InvalidToken();
1106 }
1107}
1108
Austin Schuh39788ff2019-12-01 18:22:57 -08001109SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001110 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1111 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001112 const monotonic_clock::duration offset)
1113 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1114 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001115 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001116 scheduler_(scheduler),
1117 token_(scheduler_->InvalidToken()) {}
1118
Austin Schuh7d87b672019-12-01 20:23:49 -08001119SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1120 if (token_ != scheduler_->InvalidToken()) {
1121 scheduler_->Deschedule(token_);
1122 token_ = scheduler_->InvalidToken();
1123 }
1124 simulated_event_loop_->RemoveEvent(&event_);
1125}
1126
1127void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -08001128 monotonic_clock::time_point monotonic_now =
1129 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001130 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1131 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001132 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001133 if (simulated_event_loop_->log_impl_) {
1134 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001135 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001136
1137 {
1138 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1139 Call([monotonic_now]() { return monotonic_now; },
1140 [this](monotonic_clock::time_point sleep_time) {
1141 Schedule(sleep_time);
1142 });
1143 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001144}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001145
Austin Schuh7d87b672019-12-01 20:23:49 -08001146void SimulatedPhasedLoopHandler::Schedule(
1147 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001148 // The allocations in here are due to infrastructure and don't count in the no
1149 // mallocs in RT code.
1150 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001151 if (token_ != scheduler_->InvalidToken()) {
1152 scheduler_->Deschedule(token_);
1153 token_ = scheduler_->InvalidToken();
1154 }
1155 token_ = scheduler_->Schedule(sleep_time, [this]() {
1156 DCHECK(token_ != scheduler_->InvalidToken());
1157 token_ = scheduler_->InvalidToken();
1158 simulated_event_loop_->HandleEvent();
1159 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001160 event_.set_event_time(sleep_time);
1161 simulated_event_loop_->AddEvent(&event_);
1162}
1163
Alex Perrycb7da4b2019-08-28 19:35:56 -07001164SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1165 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001166 : configuration_(CHECK_NOTNULL(configuration)),
1167 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001168 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001169 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001170 node_factories_.emplace_back(
1171 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001172 }
Austin Schuh898f4972020-01-11 17:21:25 -08001173
1174 if (configuration::MultiNode(configuration)) {
1175 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1176 }
Austin Schuh15649d62019-12-28 16:36:38 -08001177}
1178
Alex Perrycb7da4b2019-08-28 19:35:56 -07001179SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1180
Austin Schuhac0771c2020-01-07 18:36:30 -08001181NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001182 std::string_view node) {
1183 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1184}
1185
1186NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001187 const Node *node) {
1188 auto result = std::find_if(
1189 node_factories_.begin(), node_factories_.end(),
1190 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1191 return node_factory->node() == node;
1192 });
1193
1194 CHECK(result != node_factories_.end())
1195 << ": Failed to find node " << FlatbufferToJson(node);
1196
1197 return result->get();
1198}
1199
Austin Schuh87dd3832021-01-01 23:07:31 -08001200void SimulatedEventLoopFactory::SetTimeConverter(
1201 TimeConverter *time_converter) {
1202 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1203 factory->SetTimeConverter(time_converter);
1204 }
Austin Schuh58646e22021-08-23 23:51:46 -07001205 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001206}
1207
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001208::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001209 std::string_view name, const Node *node) {
1210 if (node == nullptr) {
1211 CHECK(!configuration::MultiNode(configuration()))
1212 << ": Can't make a single node event loop in a multi-node world.";
1213 } else {
1214 CHECK(configuration::MultiNode(configuration()))
1215 << ": Can't make a multi-node event loop in a single-node world.";
1216 }
1217 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1218}
1219
Austin Schuh057d29f2021-08-21 23:05:15 -07001220NodeEventLoopFactory::NodeEventLoopFactory(
1221 EventSchedulerScheduler *scheduler_scheduler,
1222 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001223 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1224 factory_(factory),
1225 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001226 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001227 scheduler_.set_started([this]() {
1228 started_ = true;
1229 for (SimulatedEventLoop *event_loop : event_loops_) {
1230 event_loop->SetIsRunning(true);
1231 }
1232 });
1233 scheduler_.set_on_shutdown([this]() {
1234 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1235 << monotonic_now() << " Shutting down node.";
1236 Shutdown();
1237 ScheduleStartup();
1238 });
1239 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001240}
1241
1242NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001243 if (started_) {
1244 for (std::function<void()> &fn : on_shutdown_) {
1245 fn();
1246 }
1247
1248 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1249 << monotonic_now() << " Shutting down applications.";
1250 applications_.clear();
1251 started_ = false;
1252 }
1253
1254 if (event_loops_.size() != 0u) {
1255 for (SimulatedEventLoop *event_loop : event_loops_) {
1256 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1257 << monotonic_now() << " Event loop '" << event_loop->name()
1258 << "' failed to shut down";
1259 }
1260 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001261 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1262}
1263
Austin Schuh58646e22021-08-23 23:51:46 -07001264void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001265 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001266 << ": Can only register OnStartup handlers when not running.";
1267 on_startup_.emplace_back(std::move(fn));
1268 if (started_) {
1269 size_t on_startup_index = on_startup_.size() - 1;
1270 scheduler_.ScheduleOnStartup(
1271 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1272 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001273}
1274
Austin Schuh58646e22021-08-23 23:51:46 -07001275void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1276 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001277}
Austin Schuh057d29f2021-08-21 23:05:15 -07001278
Austin Schuh58646e22021-08-23 23:51:46 -07001279void NodeEventLoopFactory::ScheduleStartup() {
1280 scheduler_.ScheduleOnStartup([this]() {
1281 UUID next_uuid = scheduler_.boot_uuid();
1282 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001283 CHECK_EQ(boot_uuid_, UUID::Zero())
1284 << ": Boot UUID changed without restarting. Did TimeConverter "
1285 "change the boot UUID without signaling a restart, or did you "
1286 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001287 boot_uuid_ = next_uuid;
1288 }
1289 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1290 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1291 Startup();
1292 });
1293}
1294
1295void NodeEventLoopFactory::Startup() {
1296 CHECK(!started_);
1297 for (size_t i = 0; i < on_startup_.size(); ++i) {
1298 on_startup_[i]();
1299 }
1300}
1301
1302void NodeEventLoopFactory::Shutdown() {
1303 for (SimulatedEventLoop *event_loop : event_loops_) {
1304 event_loop->SetIsRunning(false);
1305 }
1306
1307 CHECK(started_);
1308 started_ = false;
1309 for (std::function<void()> &fn : on_shutdown_) {
1310 fn();
1311 }
1312
1313 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1314 << monotonic_now() << " Shutting down applications.";
1315 applications_.clear();
1316
1317 if (event_loops_.size() != 0u) {
1318 for (SimulatedEventLoop *event_loop : event_loops_) {
1319 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1320 << monotonic_now() << " Event loop '" << event_loop->name()
1321 << "' failed to shut down";
1322 }
1323 }
1324 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1325 boot_uuid_ = UUID::Zero();
1326
1327 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001328}
1329
Alex Perrycb7da4b2019-08-28 19:35:56 -07001330void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001331 // This sets running to true too.
Austin Schuh057d29f2021-08-21 23:05:15 -07001332 scheduler_scheduler_.RunOnStartup();
Austin Schuh8bd96322020-02-13 21:18:22 -08001333 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001334 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1335 if (node) {
1336 for (SimulatedEventLoop *loop : node->event_loops_) {
1337 loop->SetIsRunning(false);
1338 }
1339 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001340 }
1341}
1342
1343void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001344 // This sets running to true too.
Austin Schuh057d29f2021-08-21 23:05:15 -07001345 scheduler_scheduler_.RunOnStartup();
Austin Schuh8bd96322020-02-13 21:18:22 -08001346 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001347 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1348 if (node) {
1349 for (SimulatedEventLoop *loop : node->event_loops_) {
1350 loop->SetIsRunning(false);
1351 }
1352 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001353 }
1354}
1355
Austin Schuh87dd3832021-01-01 23:07:31 -08001356void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001357
Austin Schuh6f3babe2020-01-26 20:34:50 -08001358void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001359 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001360 bridge_->DisableForwarding(channel);
1361}
1362
Austin Schuh4c3b9702020-08-30 11:34:55 -07001363void SimulatedEventLoopFactory::DisableStatistics() {
1364 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1365 bridge_->DisableStatistics();
1366}
1367
Austin Schuh48205e62021-11-12 14:13:18 -08001368void SimulatedEventLoopFactory::EnableStatistics() {
1369 CHECK(bridge_) << ": Can't enable statistics without a message bridge.";
1370 bridge_->EnableStatistics();
1371}
1372
Austin Schuh2928ebe2021-02-07 22:10:27 -08001373void SimulatedEventLoopFactory::SkipTimingReport() {
1374 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh48205e62021-11-12 14:13:18 -08001375
1376 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1377 if (node) {
1378 node->SkipTimingReport();
1379 }
1380 }
1381}
1382
1383void NodeEventLoopFactory::SkipTimingReport() {
1384 for (SimulatedEventLoop *event_loop : event_loops_) {
1385 event_loop->SkipTimingReport();
1386 }
1387 skip_timing_report_ = true;
1388}
1389
1390void NodeEventLoopFactory::EnableStatistics() {
1391 CHECK(factory_->bridge_)
1392 << ": Can't enable statistics without a message bridge.";
1393 factory_->bridge_->EnableStatistics(node_);
1394}
1395
1396void NodeEventLoopFactory::DisableStatistics() {
1397 CHECK(factory_->bridge_)
1398 << ": Can't disable statistics without a message bridge.";
1399 factory_->bridge_->DisableStatistics(node_);
Austin Schuh2928ebe2021-02-07 22:10:27 -08001400}
1401
Austin Schuh58646e22021-08-23 23:51:46 -07001402::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
1403 std::string_view name) {
1404 CHECK(!scheduler_.is_running() || !started_)
1405 << ": Can't create an event loop while running";
1406
1407 pid_t tid = tid_;
1408 ++tid_;
1409 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1410 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
1411 node_, tid));
1412 result->set_name(name);
1413 result->set_send_delay(factory_->send_delay());
Austin Schuh48205e62021-11-12 14:13:18 -08001414 if (skip_timing_report_) {
1415 result->SkipTimingReport();
1416 }
Austin Schuh58646e22021-08-23 23:51:46 -07001417
1418 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1419 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
1420 return std::move(result);
1421}
1422
1423void NodeEventLoopFactory::Disconnect(const Node *other) {
1424 factory_->bridge_->Disconnect(node_, other);
1425}
1426
1427void NodeEventLoopFactory::Connect(const Node *other) {
1428 factory_->bridge_->Connect(node_, other);
1429}
1430
Alex Perrycb7da4b2019-08-28 19:35:56 -07001431} // namespace aos