blob: 11e10a6c8d4075c95c4a93198206d20df6ccbd09 [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)]() {
612 ScopedMarkRealtimeRestorer rt(priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700613 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700614 on_run();
615 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700616 }
617
Austin Schuh217a9782019-12-21 23:02:50 -0800618 const Node *node() const override { return node_; }
619
James Kuszmaul3ae42262019-11-08 12:33:41 -0800620 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700621 name_ = std::string(name);
622 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800623 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700624
625 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
626
Austin Schuh39788ff2019-12-01 18:22:57 -0800627 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800629 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630 }
631
Austin Schuh39788ff2019-12-01 18:22:57 -0800632 int priority() const override { return priority_; }
633
Brian Silverman6a54ff32020-04-28 16:41:39 -0700634 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
635 CHECK(!is_running()) << ": Cannot set affinity while running.";
636 }
637
Tyler Chatow67ddb032020-01-12 14:30:04 -0800638 void Setup() {
639 MaybeScheduleTimingReports();
640 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800641 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700642 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800643 }
644 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800645
Brian Silverman4f4e0612020-08-12 19:54:41 -0700646 int NumberBuffers(const Channel *channel) override;
647
Austin Schuh83c7f702021-01-19 22:36:29 -0800648 const UUID &boot_uuid() const override {
649 return node_event_loop_factory_->boot_uuid();
650 }
651
Alex Perrycb7da4b2019-08-28 19:35:56 -0700652 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800653 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800654 friend class SimulatedPhasedLoopHandler;
655 friend class SimulatedWatcher;
656
Austin Schuh58646e22021-08-23 23:51:46 -0700657 // We have a condition where we register a startup handler, but then get shut
658 // down before it runs. This results in a segfault if we are lucky, and
659 // corruption otherwise. To handle that, allocate a small object which points
660 // back to us and can be freed when the function is freed. That object can
661 // then be updated when we get destroyed so setup is not called.
662 struct StartupTracker {
663 SimulatedEventLoop *loop = nullptr;
664 bool has_setup = false;
665 };
666
Austin Schuh7d87b672019-12-01 20:23:49 -0800667 void HandleEvent() {
668 while (true) {
669 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
670 break;
671 }
672
673 EventLoopEvent *event = PopEvent();
674 event->HandleEvent();
675 }
676 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800677
Austin Schuh39788ff2019-12-01 18:22:57 -0800678 pid_t GetTid() override { return tid_; }
679
Alex Perrycb7da4b2019-08-28 19:35:56 -0700680 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800681 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700682 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700683 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700684
685 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800686
687 int priority_ = 0;
688
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 std::chrono::nanoseconds send_delay_;
690
Austin Schuh217a9782019-12-21 23:02:50 -0800691 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800692 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800693
694 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700695 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800696
697 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700698
699 std::shared_ptr<StartupTracker> startup_tracker_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700700};
701
Austin Schuh7d87b672019-12-01 20:23:49 -0800702void SimulatedEventLoopFactory::set_send_delay(
703 std::chrono::nanoseconds send_delay) {
704 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700705 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700706 if (node) {
707 for (SimulatedEventLoop *loop : node->event_loops_) {
708 loop->set_send_delay(send_delay_);
709 }
710 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800711 }
712}
713
Alex Perrycb7da4b2019-08-28 19:35:56 -0700714void SimulatedEventLoop::MakeRawWatcher(
715 const Channel *channel,
716 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800717 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800718
Austin Schuh057d29f2021-08-21 23:05:15 -0700719 std::unique_ptr<SimulatedWatcher> shm_watcher =
720 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
721 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800722
723 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700724
Austin Schuh39788ff2019-12-01 18:22:57 -0800725 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700726 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
727 << " " << name() << " MakeRawWatcher(\""
728 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800729
730 // Order of operations gets kinda wonky if we let people make watchers after
731 // running once. If someone has a valid use case, we can reconsider.
732 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700733}
734
735std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
736 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800737 TakeSender(channel);
738
Austin Schuh58646e22021-08-23 23:51:46 -0700739 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
740 << " " << name() << " MakeRawSender(\""
741 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700742 return GetSimulatedChannel(channel)->MakeRawSender(this);
743}
744
745std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
746 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800747 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800748
Austin Schuhca4828c2019-12-28 14:21:35 -0800749 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
750 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
751 << "\", \"type\": \"" << channel->type()->string_view()
752 << "\" } is not able to be fetched on this node. Check your "
753 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800754 }
755
Austin Schuh58646e22021-08-23 23:51:46 -0700756 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
757 << " " << name() << " MakeRawFetcher(\""
758 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800759 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700760}
761
762SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
763 const Channel *channel) {
764 auto it = channels_->find(SimpleChannel(channel));
765 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800766 it =
767 channels_
768 ->emplace(
769 SimpleChannel(channel),
770 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
771 channel, std::chrono::nanoseconds(
772 configuration()->channel_storage_duration()))))
773 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700774 }
775 return it->second.get();
776}
777
Brian Silverman4f4e0612020-08-12 19:54:41 -0700778int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
779 return GetSimulatedChannel(channel)->number_buffers();
780}
781
Austin Schuh7d87b672019-12-01 20:23:49 -0800782SimulatedWatcher::SimulatedWatcher(
783 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800784 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800785 std::function<void(const Context &context, const void *message)> fn)
786 : WatcherState(simulated_event_loop, channel, std::move(fn)),
787 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700788 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800789 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700790 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700791 token_(scheduler_->InvalidToken()) {
792 VLOG(1) << simulated_event_loop_->distributed_now() << " "
793 << NodeName(simulated_event_loop_->node())
794 << simulated_event_loop_->monotonic_now() << " "
795 << simulated_event_loop_->name() << " Watching "
796 << configuration::StrippedChannelToString(channel_);
797}
Austin Schuh7d87b672019-12-01 20:23:49 -0800798
799SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700800 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700801 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700802 << simulated_event_loop_->monotonic_now() << " "
803 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700804 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800805 simulated_event_loop_->RemoveEvent(&event_);
806 if (token_ != scheduler_->InvalidToken()) {
807 scheduler_->Deschedule(token_);
808 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700809 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800810}
811
Austin Schuh8fb315a2020-11-19 22:33:58 -0800812bool SimulatedWatcher::has_run() const {
813 return simulated_event_loop_->has_run();
814}
815
Austin Schuh7d87b672019-12-01 20:23:49 -0800816void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800817 monotonic_clock::time_point event_time =
818 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800819
820 // Messages are queued in order. If we are the first, add ourselves.
821 // Otherwise, don't.
822 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800823 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800824 simulated_event_loop_->AddEvent(&event_);
825
826 DoSchedule(event_time);
827 }
828
829 msgs_.emplace_back(message);
830}
831
832void SimulatedWatcher::HandleEvent() {
Austin Schuh7d87b672019-12-01 20:23:49 -0800833 const monotonic_clock::time_point monotonic_now =
834 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700835 VLOG(1) << simulated_event_loop_->distributed_now() << " "
836 << NodeName(simulated_event_loop_->node())
837 << simulated_event_loop_->monotonic_now() << " "
838 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700839 << configuration::StrippedChannelToString(channel_);
840 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
841
Tyler Chatow67ddb032020-01-12 14:30:04 -0800842 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700843 if (simulated_event_loop_->log_impl_) {
844 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800845 }
Austin Schuhad154822019-12-27 15:45:13 -0800846 Context context = msgs_.front()->context;
847
Brian Silverman4f4e0612020-08-12 19:54:41 -0700848 if (channel_->read_method() != ReadMethod::PIN) {
849 context.buffer_index = -1;
850 }
Austin Schuhad154822019-12-27 15:45:13 -0800851 if (context.remote_queue_index == 0xffffffffu) {
852 context.remote_queue_index = context.queue_index;
853 }
Austin Schuh58646e22021-08-23 23:51:46 -0700854 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800855 context.monotonic_remote_time = context.monotonic_event_time;
856 }
Austin Schuh58646e22021-08-23 23:51:46 -0700857 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800858 context.realtime_remote_time = context.realtime_event_time;
859 }
860
Austin Schuhcc6070c2020-10-10 20:25:56 -0700861 {
862 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
863 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
864 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800865
866 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700867 if (token_ != scheduler_->InvalidToken()) {
868 scheduler_->Deschedule(token_);
869 token_ = scheduler_->InvalidToken();
870 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800871 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800872 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800873 simulated_event_loop_->AddEvent(&event_);
874
875 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800876 }
877}
878
879void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700880 CHECK(token_ == scheduler_->InvalidToken())
881 << ": May not schedule multiple times";
882 token_ = scheduler_->Schedule(
883 event_time + simulated_event_loop_->send_delay(), [this]() {
884 DCHECK(token_ != scheduler_->InvalidToken());
885 token_ = scheduler_->InvalidToken();
886 simulated_event_loop_->HandleEvent();
887 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800888}
889
890void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700891 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800892 watcher->SetSimulatedChannel(this);
893 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700894}
895
896::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800897 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700898 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
899}
900
Austin Schuh39788ff2019-12-01 18:22:57 -0800901::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
902 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700903 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800904 ::std::unique_ptr<SimulatedFetcher> fetcher(
905 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700906 fetchers_.push_back(fetcher.get());
907 return ::std::move(fetcher);
908}
909
Austin Schuhad154822019-12-27 15:45:13 -0800910uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
911 const uint32_t queue_index = next_queue_index_.index();
912 message->context.queue_index = queue_index;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700913
914 // Points to the actual data depending on the size set in context. Data may
915 // allocate more than the actual size of the message, so offset from the back
916 // of that to get the actual start of the data.
917 message->context.data =
918 message->data->data() + message->data->size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -0700919
920 DCHECK(channel()->has_schema())
921 << ": Missing schema for channel "
922 << configuration::StrippedChannelToString(channel());
923 DCHECK(flatbuffers::Verify(
924 *channel()->schema(), *channel()->schema()->root_table(),
925 static_cast<const uint8_t *>(message->context.data),
926 message->context.size))
927 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
928 << channel()->type()->c_str();
929
Alex Perrycb7da4b2019-08-28 19:35:56 -0700930 next_queue_index_ = next_queue_index_.Increment();
931
932 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800933 for (SimulatedWatcher *watcher : watchers_) {
934 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800935 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700936 }
937 }
938 for (auto &fetcher : fetchers_) {
939 fetcher->Enqueue(message);
940 }
Austin Schuhad154822019-12-27 15:45:13 -0800941
942 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700943}
944
945void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
946 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
947}
948
Austin Schuh8fb315a2020-11-19 22:33:58 -0800949SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
950 SimulatedEventLoop *event_loop)
951 : RawSender(event_loop, simulated_channel->channel()),
952 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -0700953 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800954 simulated_channel_->CountSenderCreated();
955}
956
957SimulatedSender::~SimulatedSender() {
958 simulated_channel_->CountSenderDestroyed();
959}
960
Austin Schuh8902fa52021-03-14 22:39:24 -0700961bool SimulatedSender::DoSend(size_t length,
962 monotonic_clock::time_point monotonic_remote_time,
963 realtime_clock::time_point realtime_remote_time,
964 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700965 const UUID &source_boot_uuid) {
Austin Schuh58646e22021-08-23 23:51:46 -0700966 VLOG(1) << simulated_event_loop_->distributed_now() << " "
967 << NodeName(simulated_event_loop_->node())
968 << simulated_event_loop_->monotonic_now() << " "
969 << simulated_event_loop_->name() << " Send "
970 << configuration::StrippedChannelToString(channel());
971
Austin Schuh8fb315a2020-11-19 22:33:58 -0800972 // The allocations in here are due to infrastructure and don't count in the
973 // no mallocs in RT code.
974 ScopedNotRealtime nrt;
975 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -0700976 message_->context.monotonic_event_time =
977 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800978 message_->context.monotonic_remote_time = monotonic_remote_time;
979 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -0700980 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800981 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -0700982 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800983 CHECK_LE(length, message_->context.size);
984 message_->context.size = length;
985
986 // TODO(austin): Track sending too fast.
987 sent_queue_index_ = simulated_channel_->Send(message_);
Austin Schuh58646e22021-08-23 23:51:46 -0700988 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
989 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800990
991 // Drop the reference to the message so that we allocate a new message for
992 // next time. Otherwise we will continue to reuse the same memory for all
993 // messages and corrupt it.
994 message_.reset();
995 return true;
996}
997
Austin Schuh8902fa52021-03-14 22:39:24 -0700998bool SimulatedSender::DoSend(const void *msg, size_t size,
999 monotonic_clock::time_point monotonic_remote_time,
1000 realtime_clock::time_point realtime_remote_time,
1001 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -07001002 const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -08001003 CHECK_LE(size, this->size())
1004 << ": Attempting to send too big a message on "
1005 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -08001006
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001007 // Allocates an aligned buffer in which to copy unaligned msg.
1008 auto [span, mutable_span] = MakeSharedSpan(size);
1009 message_ = SimulatedMessage::Make(simulated_channel_, span);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001010
1011 // Now fill in the message. size is already populated above, and
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001012 // queue_index will be populated in simulated_channel_.
1013 memcpy(mutable_span.data(), msg, size);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001014
1015 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001016 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -08001017}
1018
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001019bool SimulatedSender::DoSend(const RawSender::SharedSpan data,
1020 monotonic_clock::time_point monotonic_remote_time,
1021 realtime_clock::time_point realtime_remote_time,
1022 uint32_t remote_queue_index,
1023 const UUID &source_boot_uuid) {
1024 CHECK_LE(data->size(), this->size())
1025 << ": Attempting to send too big a message on "
1026 << configuration::CleanedChannelToString(simulated_channel_->channel());
1027
1028 // Constructs a message sharing the already allocated and aligned message
1029 // data.
1030 message_ = SimulatedMessage::Make(simulated_channel_, data);
1031
1032 return DoSend(data->size(), monotonic_remote_time, realtime_remote_time,
1033 remote_queue_index, source_boot_uuid);
1034}
1035
Austin Schuh39788ff2019-12-01 18:22:57 -08001036SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001037 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1038 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -08001039 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -08001040 simulated_event_loop_(simulated_event_loop),
1041 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001042 scheduler_(scheduler),
1043 token_(scheduler_->InvalidToken()) {}
1044
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001045void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
1046 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -08001047 // The allocations in here are due to infrastructure and don't count in the no
1048 // mallocs in RT code.
1049 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001050 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -07001051 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001052 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001053 base_ = base;
1054 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001055 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
1056 DCHECK(token_ != scheduler_->InvalidToken());
1057 token_ = scheduler_->InvalidToken();
1058 simulated_event_loop_->HandleEvent();
1059 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001060 event_.set_event_time(base_);
1061 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001062}
1063
1064void SimulatedTimerHandler::HandleEvent() {
Austin Schuh58646e22021-08-23 23:51:46 -07001065 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001066 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001067 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1068 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1069 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001070 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001071 if (simulated_event_loop_->log_impl_) {
1072 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001073 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001074 if (token_ != scheduler_->InvalidToken()) {
1075 scheduler_->Deschedule(token_);
1076 token_ = scheduler_->InvalidToken();
1077 }
Austin Schuh58646e22021-08-23 23:51:46 -07001078 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001079 // Reschedule.
1080 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001081 token_ = scheduler_->Schedule(base_, [this]() {
1082 DCHECK(token_ != scheduler_->InvalidToken());
1083 token_ = scheduler_->InvalidToken();
1084 simulated_event_loop_->HandleEvent();
1085 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001086 event_.set_event_time(base_);
1087 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001088 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001089
Austin Schuhcc6070c2020-10-10 20:25:56 -07001090 {
1091 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1092 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
1093 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001094}
1095
Austin Schuh7d87b672019-12-01 20:23:49 -08001096void SimulatedTimerHandler::Disable() {
1097 simulated_event_loop_->RemoveEvent(&event_);
1098 if (token_ != scheduler_->InvalidToken()) {
1099 scheduler_->Deschedule(token_);
1100 token_ = scheduler_->InvalidToken();
1101 }
1102}
1103
Austin Schuh39788ff2019-12-01 18:22:57 -08001104SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001105 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1106 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001107 const monotonic_clock::duration offset)
1108 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1109 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001110 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001111 scheduler_(scheduler),
1112 token_(scheduler_->InvalidToken()) {}
1113
Austin Schuh7d87b672019-12-01 20:23:49 -08001114SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1115 if (token_ != scheduler_->InvalidToken()) {
1116 scheduler_->Deschedule(token_);
1117 token_ = scheduler_->InvalidToken();
1118 }
1119 simulated_event_loop_->RemoveEvent(&event_);
1120}
1121
1122void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -08001123 monotonic_clock::time_point monotonic_now =
1124 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001125 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1126 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001127 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001128 if (simulated_event_loop_->log_impl_) {
1129 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001130 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001131
1132 {
1133 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1134 Call([monotonic_now]() { return monotonic_now; },
1135 [this](monotonic_clock::time_point sleep_time) {
1136 Schedule(sleep_time);
1137 });
1138 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001139}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001140
Austin Schuh7d87b672019-12-01 20:23:49 -08001141void SimulatedPhasedLoopHandler::Schedule(
1142 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001143 // The allocations in here are due to infrastructure and don't count in the no
1144 // mallocs in RT code.
1145 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001146 if (token_ != scheduler_->InvalidToken()) {
1147 scheduler_->Deschedule(token_);
1148 token_ = scheduler_->InvalidToken();
1149 }
1150 token_ = scheduler_->Schedule(sleep_time, [this]() {
1151 DCHECK(token_ != scheduler_->InvalidToken());
1152 token_ = scheduler_->InvalidToken();
1153 simulated_event_loop_->HandleEvent();
1154 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001155 event_.set_event_time(sleep_time);
1156 simulated_event_loop_->AddEvent(&event_);
1157}
1158
Alex Perrycb7da4b2019-08-28 19:35:56 -07001159SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1160 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001161 : configuration_(CHECK_NOTNULL(configuration)),
1162 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001163 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001164 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001165 node_factories_.emplace_back(
1166 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001167 }
Austin Schuh898f4972020-01-11 17:21:25 -08001168
1169 if (configuration::MultiNode(configuration)) {
1170 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1171 }
Austin Schuh15649d62019-12-28 16:36:38 -08001172}
1173
Alex Perrycb7da4b2019-08-28 19:35:56 -07001174SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1175
Austin Schuhac0771c2020-01-07 18:36:30 -08001176NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001177 std::string_view node) {
1178 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1179}
1180
1181NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001182 const Node *node) {
1183 auto result = std::find_if(
1184 node_factories_.begin(), node_factories_.end(),
1185 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1186 return node_factory->node() == node;
1187 });
1188
1189 CHECK(result != node_factories_.end())
1190 << ": Failed to find node " << FlatbufferToJson(node);
1191
1192 return result->get();
1193}
1194
Austin Schuh87dd3832021-01-01 23:07:31 -08001195void SimulatedEventLoopFactory::SetTimeConverter(
1196 TimeConverter *time_converter) {
1197 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1198 factory->SetTimeConverter(time_converter);
1199 }
Austin Schuh58646e22021-08-23 23:51:46 -07001200 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001201}
1202
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001203::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001204 std::string_view name, const Node *node) {
1205 if (node == nullptr) {
1206 CHECK(!configuration::MultiNode(configuration()))
1207 << ": Can't make a single node event loop in a multi-node world.";
1208 } else {
1209 CHECK(configuration::MultiNode(configuration()))
1210 << ": Can't make a multi-node event loop in a single-node world.";
1211 }
1212 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1213}
1214
Austin Schuh057d29f2021-08-21 23:05:15 -07001215NodeEventLoopFactory::NodeEventLoopFactory(
1216 EventSchedulerScheduler *scheduler_scheduler,
1217 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001218 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1219 factory_(factory),
1220 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001221 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001222 scheduler_.set_started([this]() {
1223 started_ = true;
1224 for (SimulatedEventLoop *event_loop : event_loops_) {
1225 event_loop->SetIsRunning(true);
1226 }
1227 });
1228 scheduler_.set_on_shutdown([this]() {
1229 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1230 << monotonic_now() << " Shutting down node.";
1231 Shutdown();
1232 ScheduleStartup();
1233 });
1234 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001235}
1236
1237NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001238 if (started_) {
1239 for (std::function<void()> &fn : on_shutdown_) {
1240 fn();
1241 }
1242
1243 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1244 << monotonic_now() << " Shutting down applications.";
1245 applications_.clear();
1246 started_ = false;
1247 }
1248
1249 if (event_loops_.size() != 0u) {
1250 for (SimulatedEventLoop *event_loop : event_loops_) {
1251 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1252 << monotonic_now() << " Event loop '" << event_loop->name()
1253 << "' failed to shut down";
1254 }
1255 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001256 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1257}
1258
Austin Schuh58646e22021-08-23 23:51:46 -07001259void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001260 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001261 << ": Can only register OnStartup handlers when not running.";
1262 on_startup_.emplace_back(std::move(fn));
1263 if (started_) {
1264 size_t on_startup_index = on_startup_.size() - 1;
1265 scheduler_.ScheduleOnStartup(
1266 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1267 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001268}
1269
Austin Schuh58646e22021-08-23 23:51:46 -07001270void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1271 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001272}
Austin Schuh057d29f2021-08-21 23:05:15 -07001273
Austin Schuh58646e22021-08-23 23:51:46 -07001274void NodeEventLoopFactory::ScheduleStartup() {
1275 scheduler_.ScheduleOnStartup([this]() {
1276 UUID next_uuid = scheduler_.boot_uuid();
1277 if (boot_uuid_ != next_uuid) {
Austin Schuh188a2f62021-11-08 10:45:54 -08001278 CHECK_EQ(boot_uuid_, UUID::Zero())
1279 << ": Boot UUID changed without restarting. Did TimeConverter "
1280 "change the boot UUID without signaling a restart, or did you "
1281 "change TimeConverter?";
Austin Schuh58646e22021-08-23 23:51:46 -07001282 boot_uuid_ = next_uuid;
1283 }
1284 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1285 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1286 Startup();
1287 });
1288}
1289
1290void NodeEventLoopFactory::Startup() {
1291 CHECK(!started_);
1292 for (size_t i = 0; i < on_startup_.size(); ++i) {
1293 on_startup_[i]();
1294 }
1295}
1296
1297void NodeEventLoopFactory::Shutdown() {
1298 for (SimulatedEventLoop *event_loop : event_loops_) {
1299 event_loop->SetIsRunning(false);
1300 }
1301
1302 CHECK(started_);
1303 started_ = false;
1304 for (std::function<void()> &fn : on_shutdown_) {
1305 fn();
1306 }
1307
1308 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1309 << monotonic_now() << " Shutting down applications.";
1310 applications_.clear();
1311
1312 if (event_loops_.size() != 0u) {
1313 for (SimulatedEventLoop *event_loop : event_loops_) {
1314 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1315 << monotonic_now() << " Event loop '" << event_loop->name()
1316 << "' failed to shut down";
1317 }
1318 }
1319 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1320 boot_uuid_ = UUID::Zero();
1321
1322 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001323}
1324
Alex Perrycb7da4b2019-08-28 19:35:56 -07001325void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001326 // This sets running to true too.
Austin Schuh057d29f2021-08-21 23:05:15 -07001327 scheduler_scheduler_.RunOnStartup();
Austin Schuh8bd96322020-02-13 21:18:22 -08001328 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001329 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1330 if (node) {
1331 for (SimulatedEventLoop *loop : node->event_loops_) {
1332 loop->SetIsRunning(false);
1333 }
1334 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001335 }
1336}
1337
1338void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001339 // This sets running to true too.
Austin Schuh057d29f2021-08-21 23:05:15 -07001340 scheduler_scheduler_.RunOnStartup();
Austin Schuh8bd96322020-02-13 21:18:22 -08001341 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001342 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1343 if (node) {
1344 for (SimulatedEventLoop *loop : node->event_loops_) {
1345 loop->SetIsRunning(false);
1346 }
1347 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001348 }
1349}
1350
Austin Schuh87dd3832021-01-01 23:07:31 -08001351void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001352
Austin Schuh6f3babe2020-01-26 20:34:50 -08001353void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001354 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001355 bridge_->DisableForwarding(channel);
1356}
1357
Austin Schuh4c3b9702020-08-30 11:34:55 -07001358void SimulatedEventLoopFactory::DisableStatistics() {
1359 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1360 bridge_->DisableStatistics();
1361}
1362
Austin Schuh2928ebe2021-02-07 22:10:27 -08001363void SimulatedEventLoopFactory::SkipTimingReport() {
1364 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
Austin Schuh2928ebe2021-02-07 22:10:27 -08001365}
1366
Austin Schuh58646e22021-08-23 23:51:46 -07001367::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
1368 std::string_view name) {
1369 CHECK(!scheduler_.is_running() || !started_)
1370 << ": Can't create an event loop while running";
1371
1372 pid_t tid = tid_;
1373 ++tid_;
1374 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1375 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
1376 node_, tid));
1377 result->set_name(name);
1378 result->set_send_delay(factory_->send_delay());
1379
1380 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1381 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
1382 return std::move(result);
1383}
1384
1385void NodeEventLoopFactory::Disconnect(const Node *other) {
1386 factory_->bridge_->Disconnect(node_, other);
1387}
1388
1389void NodeEventLoopFactory::Connect(const Node *other) {
1390 factory_->bridge_->Connect(node_, other);
1391}
1392
Alex Perrycb7da4b2019-08-28 19:35:56 -07001393} // namespace aos