blob: 15375e828531e7dc1a6bc101ae80d38dc240f447 [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
Alex Perrycb7da4b2019-08-28 19:35:56 -070042// Container for both a message, and the context for it for simulation. This
43// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070044struct SimulatedMessage final {
45 SimulatedMessage(const SimulatedMessage &) = delete;
46 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
47
48 // Creates a SimulatedMessage with size bytes of storage.
49 // This is a shared_ptr so we don't have to implement refcounting or copying.
50 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel);
51
Alex Perrycb7da4b2019-08-28 19:35:56 -070052 // Context for the data.
53 Context context;
54
Brian Silverman661eb8d2020-08-12 19:41:01 -070055 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070056
Alex Perrycb7da4b2019-08-28 19:35:56 -070057 // The data.
Brian Silvermana1652f32020-01-29 20:41:44 -080058 char *data(size_t buffer_size) {
59 return RoundChannelData(&actual_data[0], buffer_size);
60 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070061
Brian Silvermana1652f32020-01-29 20:41:44 -080062 // Then the data, including padding on the end so we can align the buffer we
63 // actually return from data().
64 char actual_data[];
Brian Silverman661eb8d2020-08-12 19:41:01 -070065
66 private:
67 SimulatedMessage(SimulatedChannel *channel_in);
68 ~SimulatedMessage();
69
70 static void DestroyAndFree(SimulatedMessage *p) {
71 p->~SimulatedMessage();
72 free(p);
73 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070074};
75
Brian Silverman661eb8d2020-08-12 19:41:01 -070076} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080077
Brian Silverman661eb8d2020-08-12 19:41:01 -070078// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
79// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -080080class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080081 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080082 SimulatedWatcher(
83 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
84 const Channel *channel,
85 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080086
Austin Schuh7d87b672019-12-01 20:23:49 -080087 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080088
Austin Schuh8fb315a2020-11-19 22:33:58 -080089 bool has_run() const;
90
Austin Schuh39788ff2019-12-01 18:22:57 -080091 void Startup(EventLoop * /*event_loop*/) override {}
92
Austin Schuh7d87b672019-12-01 20:23:49 -080093 void Schedule(std::shared_ptr<SimulatedMessage> message);
94
95 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080096
97 void SetSimulatedChannel(SimulatedChannel *channel) {
98 simulated_channel_ = channel;
99 }
100
101 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800102 void DoSchedule(monotonic_clock::time_point event_time);
103
104 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
105
Brian Silverman4f4e0612020-08-12 19:54:41 -0700106 SimulatedEventLoop *const simulated_event_loop_;
107 const Channel *const channel_;
108 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800109 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800110 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800111 SimulatedChannel *simulated_channel_ = nullptr;
112};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700113
114class SimulatedChannel {
115 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800116 explicit SimulatedChannel(const Channel *channel,
Brian Silverman661eb8d2020-08-12 19:41:01 -0700117 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800118 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700119 channel_storage_duration_(channel_storage_duration),
120 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
121 available_buffer_indices_.reserve(number_buffers());
122 for (int i = 0; i < number_buffers(); ++i) {
123 available_buffer_indices_.push_back(i);
124 }
125 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700126
Brian Silverman661eb8d2020-08-12 19:41:01 -0700127 ~SimulatedChannel() {
128 latest_message_.reset();
129 CHECK_EQ(static_cast<size_t>(number_buffers()),
130 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800131 CHECK_EQ(0u, fetchers_.size())
132 << configuration::StrippedChannelToString(channel());
133 CHECK_EQ(0u, watchers_.size())
134 << configuration::StrippedChannelToString(channel());
135 CHECK_EQ(0, sender_count_)
136 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700137 }
138
139 // The number of messages we pretend to have in the queue.
140 int queue_size() const {
141 return channel()->frequency() *
142 std::chrono::duration_cast<std::chrono::duration<double>>(
143 channel_storage_duration_)
144 .count();
145 }
146
147 // The number of extra buffers (beyond the queue) we pretend to have.
148 int number_scratch_buffers() const {
149 // We need to start creating messages before we know how many
150 // senders+readers we'll have, so we need to just pick something which is
151 // always big enough.
152 return 50;
153 }
154
155 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
156
157 int GetBufferIndex() {
158 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
159 const int result = available_buffer_indices_.back();
160 available_buffer_indices_.pop_back();
161 return result;
162 }
163
164 void FreeBufferIndex(int i) {
Austin Schuhc5047ea2021-03-20 22:00:21 -0700165 // This extra checking has a large performance hit with sanitizers that
166 // track memory accesses, so just skip it.
167#if !__has_feature(memory_sanitizer) && !__has_feature(address_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700168 DCHECK(std::find(available_buffer_indices_.begin(),
169 available_buffer_indices_.end(),
170 i) == available_buffer_indices_.end())
171 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800172#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700173 available_buffer_indices_.push_back(i);
174 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700175
176 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800177 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700178
179 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800180 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700181
182 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800183 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800184
Austin Schuh7d87b672019-12-01 20:23:49 -0800185 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800186 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
187 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700188
Austin Schuhad154822019-12-27 15:45:13 -0800189 // Sends the message to all the connected receivers and fetchers. Returns the
190 // sent queue index.
191 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700192
193 // Unregisters a fetcher.
194 void UnregisterFetcher(SimulatedFetcher *fetcher);
195
196 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
197
Austin Schuh39788ff2019-12-01 18:22:57 -0800198 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700199
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800200 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800201 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700202 }
203
Austin Schuh39788ff2019-12-01 18:22:57 -0800204 const Channel *channel() const { return channel_; }
205
Austin Schuhe516ab02020-05-06 21:37:04 -0700206 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700207 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700208 if (sender_count_ >= channel()->num_senders()) {
209 LOG(FATAL) << "Failed to create sender on "
210 << configuration::CleanedChannelToString(channel())
211 << ", too many senders.";
212 }
213 ++sender_count_;
214 }
Brian Silverman77162972020-08-12 19:52:40 -0700215
Austin Schuhe516ab02020-05-06 21:37:04 -0700216 void CountSenderDestroyed() {
217 --sender_count_;
218 CHECK_GE(sender_count_, 0);
219 }
220
Alex Perrycb7da4b2019-08-28 19:35:56 -0700221 private:
Brian Silverman77162972020-08-12 19:52:40 -0700222 void CheckBufferCount() {
223 int reader_count = 0;
224 if (channel()->read_method() == ReadMethod::PIN) {
225 reader_count = watchers_.size() + fetchers_.size();
226 }
227 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
228 }
229
230 void CheckReaderCount() {
231 if (channel()->read_method() != ReadMethod::PIN) {
232 return;
233 }
234 CheckBufferCount();
235 const int reader_count = watchers_.size() + fetchers_.size();
236 if (reader_count >= channel()->num_readers()) {
237 LOG(FATAL) << "Failed to create reader on "
238 << configuration::CleanedChannelToString(channel())
239 << ", too many readers.";
240 }
241 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700242
243 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700244 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700245
246 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800247 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700248
249 // List of all fetchers.
250 ::std::vector<SimulatedFetcher *> fetchers_;
251 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700252
253 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700254
255 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700256
257 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700258};
259
260namespace {
261
Brian Silverman661eb8d2020-08-12 19:41:01 -0700262std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
263 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800264 // The allocations in here are due to infrastructure and don't count in the no
265 // mallocs in RT code.
266 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700267 const size_t size = channel->max_size();
268 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800269 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700270 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700271 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800272 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700273
Brian Silverman661eb8d2020-08-12 19:41:01 -0700274 return std::shared_ptr<SimulatedMessage>(message,
275 &SimulatedMessage::DestroyAndFree);
276}
277
278SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
279 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700280 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700281}
282
283SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700284 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285}
286
287class SimulatedSender : public RawSender {
288 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800289 SimulatedSender(SimulatedChannel *simulated_channel,
290 SimulatedEventLoop *event_loop);
291 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700292
293 void *data() override {
294 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700295 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800297 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700298 }
299
300 size_t size() override { return simulated_channel_->max_size(); }
301
Austin Schuh58646e22021-08-23 23:51:46 -0700302 bool DoSend(size_t length, monotonic_clock::time_point monotonic_remote_time,
303 realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700304 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700305 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700306
Austin Schuhad154822019-12-27 15:45:13 -0800307 bool DoSend(const void *msg, size_t size,
Austin Schuh58646e22021-08-23 23:51:46 -0700308 monotonic_clock::time_point monotonic_remote_time,
309 realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700310 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700311 const UUID &source_boot_uuid) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700312
Brian Silverman4f4e0612020-08-12 19:54:41 -0700313 int buffer_index() override {
314 // First, ensure message_ is allocated.
315 data();
316 return message_->context.buffer_index;
317 }
318
Alex Perrycb7da4b2019-08-28 19:35:56 -0700319 private:
320 SimulatedChannel *simulated_channel_;
Austin Schuh58646e22021-08-23 23:51:46 -0700321 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700322
323 std::shared_ptr<SimulatedMessage> message_;
324};
325} // namespace
326
327class SimulatedFetcher : public RawFetcher {
328 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800329 explicit SimulatedFetcher(EventLoop *event_loop,
330 SimulatedChannel *simulated_channel)
331 : RawFetcher(event_loop, simulated_channel->channel()),
332 simulated_channel_(simulated_channel) {}
333 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334
Austin Schuh39788ff2019-12-01 18:22:57 -0800335 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800336 // The allocations in here are due to infrastructure and don't count in the
337 // no mallocs in RT code.
338 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800339 if (msgs_.size() == 0) {
340 return std::make_pair(false, monotonic_clock::min_time);
341 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700342
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700343 CHECK(!fell_behind_) << ": Got behind on "
344 << configuration::StrippedChannelToString(
345 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700346
Alex Perrycb7da4b2019-08-28 19:35:56 -0700347 SetMsg(msgs_.front());
348 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800349 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700350 }
351
Austin Schuh39788ff2019-12-01 18:22:57 -0800352 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800353 // The allocations in here are due to infrastructure and don't count in the
354 // no mallocs in RT code.
355 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700356 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800357 // TODO(austin): Can we just do this logic unconditionally? It is a lot
358 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800359 if (!msg_ && simulated_channel_->latest_message()) {
360 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800361 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700362 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800363 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700364 }
365 }
366
367 // We've had a message enqueued, so we don't need to go looking for the
368 // latest message from before we started.
369 SetMsg(msgs_.back());
370 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700371 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800372 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700373 }
374
375 private:
376 friend class SimulatedChannel;
377
378 // Updates the state inside RawFetcher to point to the data in msg_.
379 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
380 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700381 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700382 if (channel()->read_method() != ReadMethod::PIN) {
383 context_.buffer_index = -1;
384 }
Austin Schuhad154822019-12-27 15:45:13 -0800385 if (context_.remote_queue_index == 0xffffffffu) {
386 context_.remote_queue_index = context_.queue_index;
387 }
Austin Schuh58646e22021-08-23 23:51:46 -0700388 if (context_.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800389 context_.monotonic_remote_time = context_.monotonic_event_time;
390 }
Austin Schuh58646e22021-08-23 23:51:46 -0700391 if (context_.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800392 context_.realtime_remote_time = context_.realtime_event_time;
393 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394 }
395
396 // Internal method for Simulation to add a message to the buffer.
397 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
398 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700399 if (fell_behind_ ||
400 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
401 fell_behind_ = true;
402 // Might as well empty out all the intermediate messages now.
403 while (msgs_.size() > 1) {
404 msgs_.pop_front();
405 }
406 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407 }
408
Austin Schuhac0771c2020-01-07 18:36:30 -0800409 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700410 std::shared_ptr<SimulatedMessage> msg_;
411
412 // Messages queued up but not in use.
413 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700414
415 // Whether we're currently "behind", which means a FetchNext call will fail.
416 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417};
418
419class SimulatedTimerHandler : public TimerHandler {
420 public:
421 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800422 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800423 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800424 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700425
426 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800427 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700428
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800429 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700430
Austin Schuh7d87b672019-12-01 20:23:49 -0800431 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700432
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800434 SimulatedEventLoop *simulated_event_loop_;
435 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700436 EventScheduler *scheduler_;
437 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800438
Alex Perrycb7da4b2019-08-28 19:35:56 -0700439 monotonic_clock::time_point base_;
440 monotonic_clock::duration repeat_offset_;
441};
442
443class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
444 public:
445 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800446 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700447 ::std::function<void(int)> fn,
448 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800449 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800450 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451
Austin Schuh7d87b672019-12-01 20:23:49 -0800452 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700453
Austin Schuh7d87b672019-12-01 20:23:49 -0800454 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700455
456 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800457 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800458 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459
Austin Schuh39788ff2019-12-01 18:22:57 -0800460 EventScheduler *scheduler_;
461 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700462};
463
464class SimulatedEventLoop : public EventLoop {
465 public:
466 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700467 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
469 *channels,
470 const Configuration *configuration,
Austin Schuh057d29f2021-08-21 23:05:15 -0700471 std::vector<SimulatedEventLoop *> *event_loops_, const Node *node,
472 pid_t tid)
Austin Schuh83c7f702021-01-19 22:36:29 -0800473 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800475 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700476 channels_(channels),
Austin Schuh057d29f2021-08-21 23:05:15 -0700477 event_loops_(event_loops_),
Austin Schuh217a9782019-12-21 23:02:50 -0800478 node_(node),
Austin Schuh58646e22021-08-23 23:51:46 -0700479 tid_(tid),
480 startup_tracker_(std::make_shared<StartupTracker>()) {
481 startup_tracker_->loop = this;
482 scheduler_->ScheduleOnStartup([startup_tracker = startup_tracker_]() {
483 if (startup_tracker->loop) {
484 startup_tracker->loop->Setup();
485 startup_tracker->has_setup = true;
486 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700487 });
488
489 event_loops_->push_back(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700490 }
Austin Schuh58646e22021-08-23 23:51:46 -0700491
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800493 // Trigger any remaining senders or fetchers to be cleared before destroying
494 // the event loop so the book keeping matches.
495 timing_report_sender_.reset();
496
497 // Force everything with a registered fd with epoll to be destroyed now.
498 timers_.clear();
499 phased_loops_.clear();
500 watchers_.clear();
501
Austin Schuh58646e22021-08-23 23:51:46 -0700502 for (auto it = event_loops_->begin(); it != event_loops_->end(); ++it) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700503 if (*it == this) {
504 event_loops_->erase(it);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700505 break;
506 }
507 }
Austin Schuh58646e22021-08-23 23:51:46 -0700508 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
509 << monotonic_now() << " ~SimulatedEventLoop(\"" << name_ << "\")";
510 startup_tracker_->loop = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511 }
512
Austin Schuh057d29f2021-08-21 23:05:15 -0700513 void SetIsRunning(bool running) {
Austin Schuh58646e22021-08-23 23:51:46 -0700514 VLOG(1) << scheduler_->distributed_now() << " " << NodeName(node())
515 << monotonic_now() << " " << name_ << " set_is_running(" << running
516 << ")";
517 CHECK(startup_tracker_->has_setup);
Austin Schuh057d29f2021-08-21 23:05:15 -0700518
519 set_is_running(running);
Austin Schuh58646e22021-08-23 23:51:46 -0700520 if (running) {
521 has_run_ = true;
522 }
Austin Schuh057d29f2021-08-21 23:05:15 -0700523 }
524
Austin Schuh8fb315a2020-11-19 22:33:58 -0800525 bool has_run() const { return has_run_; }
526
Austin Schuh7d87b672019-12-01 20:23:49 -0800527 std::chrono::nanoseconds send_delay() const { return send_delay_; }
528 void set_send_delay(std::chrono::nanoseconds send_delay) {
529 send_delay_ = send_delay;
530 }
531
Austin Schuh58646e22021-08-23 23:51:46 -0700532 monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800533 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700534 }
535
Austin Schuh58646e22021-08-23 23:51:46 -0700536 realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800537 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538 }
539
Austin Schuh58646e22021-08-23 23:51:46 -0700540 distributed_clock::time_point distributed_now() {
541 return scheduler_->distributed_now();
542 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700543
Austin Schuh58646e22021-08-23 23:51:46 -0700544 std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
545
546 std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547
548 void MakeRawWatcher(
549 const Channel *channel,
550 ::std::function<void(const Context &context, const void *message)>
551 watcher) override;
552
553 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800554 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800555 return NewTimer(::std::unique_ptr<TimerHandler>(
556 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557 }
558
559 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
560 const monotonic_clock::duration interval,
561 const monotonic_clock::duration offset =
562 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800563 return NewPhasedLoop(
564 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
565 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700566 }
567
568 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800569 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700570 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
571 ScopedMarkRealtimeRestorer rt(priority() > 0);
Austin Schuha9012be2021-07-21 15:19:11 -0700572 SetTimerContext(monotonic_now());
Austin Schuhcc6070c2020-10-10 20:25:56 -0700573 on_run();
574 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700575 }
576
Austin Schuh217a9782019-12-21 23:02:50 -0800577 const Node *node() const override { return node_; }
578
James Kuszmaul3ae42262019-11-08 12:33:41 -0800579 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580 name_ = std::string(name);
581 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800582 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700583
584 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
585
Austin Schuh39788ff2019-12-01 18:22:57 -0800586 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700587 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800588 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700589 }
590
Austin Schuh39788ff2019-12-01 18:22:57 -0800591 int priority() const override { return priority_; }
592
Brian Silverman6a54ff32020-04-28 16:41:39 -0700593 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
594 CHECK(!is_running()) << ": Cannot set affinity while running.";
595 }
596
Tyler Chatow67ddb032020-01-12 14:30:04 -0800597 void Setup() {
598 MaybeScheduleTimingReports();
599 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800600 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700601 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800602 }
603 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800604
Brian Silverman4f4e0612020-08-12 19:54:41 -0700605 int NumberBuffers(const Channel *channel) override;
606
Austin Schuh83c7f702021-01-19 22:36:29 -0800607 const UUID &boot_uuid() const override {
608 return node_event_loop_factory_->boot_uuid();
609 }
610
Alex Perrycb7da4b2019-08-28 19:35:56 -0700611 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800612 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800613 friend class SimulatedPhasedLoopHandler;
614 friend class SimulatedWatcher;
615
Austin Schuh58646e22021-08-23 23:51:46 -0700616 // We have a condition where we register a startup handler, but then get shut
617 // down before it runs. This results in a segfault if we are lucky, and
618 // corruption otherwise. To handle that, allocate a small object which points
619 // back to us and can be freed when the function is freed. That object can
620 // then be updated when we get destroyed so setup is not called.
621 struct StartupTracker {
622 SimulatedEventLoop *loop = nullptr;
623 bool has_setup = false;
624 };
625
Austin Schuh7d87b672019-12-01 20:23:49 -0800626 void HandleEvent() {
627 while (true) {
628 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
629 break;
630 }
631
632 EventLoopEvent *event = PopEvent();
633 event->HandleEvent();
634 }
635 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800636
Austin Schuh39788ff2019-12-01 18:22:57 -0800637 pid_t GetTid() override { return tid_; }
638
Alex Perrycb7da4b2019-08-28 19:35:56 -0700639 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800640 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700641 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
Austin Schuh057d29f2021-08-21 23:05:15 -0700642 std::vector<SimulatedEventLoop *> *event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700643
644 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800645
646 int priority_ = 0;
647
Austin Schuh7d87b672019-12-01 20:23:49 -0800648 std::chrono::nanoseconds send_delay_;
649
Austin Schuh217a9782019-12-21 23:02:50 -0800650 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800651 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800652
653 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700654 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800655
656 bool has_run_ = false;
Austin Schuh58646e22021-08-23 23:51:46 -0700657
658 std::shared_ptr<StartupTracker> startup_tracker_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700659};
660
Austin Schuh7d87b672019-12-01 20:23:49 -0800661void SimulatedEventLoopFactory::set_send_delay(
662 std::chrono::nanoseconds send_delay) {
663 send_delay_ = send_delay;
Austin Schuh58646e22021-08-23 23:51:46 -0700664 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
Austin Schuh057d29f2021-08-21 23:05:15 -0700665 if (node) {
666 for (SimulatedEventLoop *loop : node->event_loops_) {
667 loop->set_send_delay(send_delay_);
668 }
669 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800670 }
671}
672
Alex Perrycb7da4b2019-08-28 19:35:56 -0700673void SimulatedEventLoop::MakeRawWatcher(
674 const Channel *channel,
675 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800676 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800677
Austin Schuh057d29f2021-08-21 23:05:15 -0700678 std::unique_ptr<SimulatedWatcher> shm_watcher =
679 std::make_unique<SimulatedWatcher>(this, scheduler_, channel,
680 std::move(watcher));
Austin Schuh39788ff2019-12-01 18:22:57 -0800681
682 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
Austin Schuh057d29f2021-08-21 23:05:15 -0700683
Austin Schuh39788ff2019-12-01 18:22:57 -0800684 NewWatcher(std::move(shm_watcher));
Austin Schuh58646e22021-08-23 23:51:46 -0700685 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
686 << " " << name() << " MakeRawWatcher(\""
687 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh8fb315a2020-11-19 22:33:58 -0800688
689 // Order of operations gets kinda wonky if we let people make watchers after
690 // running once. If someone has a valid use case, we can reconsider.
691 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700692}
693
694std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
695 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800696 TakeSender(channel);
697
Austin Schuh58646e22021-08-23 23:51:46 -0700698 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
699 << " " << name() << " MakeRawSender(\""
700 << configuration::StrippedChannelToString(channel) << "\")";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700701 return GetSimulatedChannel(channel)->MakeRawSender(this);
702}
703
704std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
705 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800706 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800707
Austin Schuhca4828c2019-12-28 14:21:35 -0800708 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
709 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
710 << "\", \"type\": \"" << channel->type()->string_view()
711 << "\" } is not able to be fetched on this node. Check your "
712 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800713 }
714
Austin Schuh58646e22021-08-23 23:51:46 -0700715 VLOG(1) << distributed_now() << " " << NodeName(node()) << monotonic_now()
716 << " " << name() << " MakeRawFetcher(\""
717 << configuration::StrippedChannelToString(channel) << "\")";
Austin Schuh39788ff2019-12-01 18:22:57 -0800718 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700719}
720
721SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
722 const Channel *channel) {
723 auto it = channels_->find(SimpleChannel(channel));
724 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800725 it =
726 channels_
727 ->emplace(
728 SimpleChannel(channel),
729 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
730 channel, std::chrono::nanoseconds(
731 configuration()->channel_storage_duration()))))
732 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700733 }
734 return it->second.get();
735}
736
Brian Silverman4f4e0612020-08-12 19:54:41 -0700737int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
738 return GetSimulatedChannel(channel)->number_buffers();
739}
740
Austin Schuh7d87b672019-12-01 20:23:49 -0800741SimulatedWatcher::SimulatedWatcher(
742 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800743 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800744 std::function<void(const Context &context, const void *message)> fn)
745 : WatcherState(simulated_event_loop, channel, std::move(fn)),
746 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700747 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800748 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700749 event_(this),
Austin Schuh58646e22021-08-23 23:51:46 -0700750 token_(scheduler_->InvalidToken()) {
751 VLOG(1) << simulated_event_loop_->distributed_now() << " "
752 << NodeName(simulated_event_loop_->node())
753 << simulated_event_loop_->monotonic_now() << " "
754 << simulated_event_loop_->name() << " Watching "
755 << configuration::StrippedChannelToString(channel_);
756}
Austin Schuh7d87b672019-12-01 20:23:49 -0800757
758SimulatedWatcher::~SimulatedWatcher() {
Austin Schuh58646e22021-08-23 23:51:46 -0700759 VLOG(1) << simulated_event_loop_->distributed_now() << " "
Austin Schuh057d29f2021-08-21 23:05:15 -0700760 << NodeName(simulated_event_loop_->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700761 << simulated_event_loop_->monotonic_now() << " "
762 << simulated_event_loop_->name() << " ~Watching "
Austin Schuh057d29f2021-08-21 23:05:15 -0700763 << configuration::StrippedChannelToString(channel_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800764 simulated_event_loop_->RemoveEvent(&event_);
765 if (token_ != scheduler_->InvalidToken()) {
766 scheduler_->Deschedule(token_);
767 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700768 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800769}
770
Austin Schuh8fb315a2020-11-19 22:33:58 -0800771bool SimulatedWatcher::has_run() const {
772 return simulated_event_loop_->has_run();
773}
774
Austin Schuh7d87b672019-12-01 20:23:49 -0800775void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800776 monotonic_clock::time_point event_time =
777 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800778
779 // Messages are queued in order. If we are the first, add ourselves.
780 // Otherwise, don't.
781 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800782 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800783 simulated_event_loop_->AddEvent(&event_);
784
785 DoSchedule(event_time);
786 }
787
788 msgs_.emplace_back(message);
789}
790
791void SimulatedWatcher::HandleEvent() {
Austin Schuh7d87b672019-12-01 20:23:49 -0800792 const monotonic_clock::time_point monotonic_now =
793 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700794 VLOG(1) << simulated_event_loop_->distributed_now() << " "
795 << NodeName(simulated_event_loop_->node())
796 << simulated_event_loop_->monotonic_now() << " "
797 << simulated_event_loop_->name() << " Watcher "
Austin Schuh057d29f2021-08-21 23:05:15 -0700798 << configuration::StrippedChannelToString(channel_);
799 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
800
Tyler Chatow67ddb032020-01-12 14:30:04 -0800801 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700802 if (simulated_event_loop_->log_impl_) {
803 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800804 }
Austin Schuhad154822019-12-27 15:45:13 -0800805 Context context = msgs_.front()->context;
806
Brian Silverman4f4e0612020-08-12 19:54:41 -0700807 if (channel_->read_method() != ReadMethod::PIN) {
808 context.buffer_index = -1;
809 }
Austin Schuhad154822019-12-27 15:45:13 -0800810 if (context.remote_queue_index == 0xffffffffu) {
811 context.remote_queue_index = context.queue_index;
812 }
Austin Schuh58646e22021-08-23 23:51:46 -0700813 if (context.monotonic_remote_time == monotonic_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800814 context.monotonic_remote_time = context.monotonic_event_time;
815 }
Austin Schuh58646e22021-08-23 23:51:46 -0700816 if (context.realtime_remote_time == realtime_clock::min_time) {
Austin Schuhad154822019-12-27 15:45:13 -0800817 context.realtime_remote_time = context.realtime_event_time;
818 }
819
Austin Schuhcc6070c2020-10-10 20:25:56 -0700820 {
821 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
822 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
823 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800824
825 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700826 if (token_ != scheduler_->InvalidToken()) {
827 scheduler_->Deschedule(token_);
828 token_ = scheduler_->InvalidToken();
829 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800830 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800831 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800832 simulated_event_loop_->AddEvent(&event_);
833
834 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800835 }
836}
837
838void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700839 CHECK(token_ == scheduler_->InvalidToken())
840 << ": May not schedule multiple times";
841 token_ = scheduler_->Schedule(
842 event_time + simulated_event_loop_->send_delay(), [this]() {
843 DCHECK(token_ != scheduler_->InvalidToken());
844 token_ = scheduler_->InvalidToken();
845 simulated_event_loop_->HandleEvent();
846 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800847}
848
849void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700850 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800851 watcher->SetSimulatedChannel(this);
852 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700853}
854
855::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800856 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700857 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
858}
859
Austin Schuh39788ff2019-12-01 18:22:57 -0800860::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
861 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700862 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800863 ::std::unique_ptr<SimulatedFetcher> fetcher(
864 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700865 fetchers_.push_back(fetcher.get());
866 return ::std::move(fetcher);
867}
868
Austin Schuhad154822019-12-27 15:45:13 -0800869uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
870 const uint32_t queue_index = next_queue_index_.index();
871 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800872 message->context.data = message->data(channel()->max_size()) +
873 channel()->max_size() - message->context.size;
Austin Schuha9df9ad2021-06-16 14:49:39 -0700874
875 DCHECK(channel()->has_schema())
876 << ": Missing schema for channel "
877 << configuration::StrippedChannelToString(channel());
878 DCHECK(flatbuffers::Verify(
879 *channel()->schema(), *channel()->schema()->root_table(),
880 static_cast<const uint8_t *>(message->context.data),
881 message->context.size))
882 << ": Corrupted flatbuffer on " << channel()->name()->c_str() << " "
883 << channel()->type()->c_str();
884
Alex Perrycb7da4b2019-08-28 19:35:56 -0700885 next_queue_index_ = next_queue_index_.Increment();
886
887 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800888 for (SimulatedWatcher *watcher : watchers_) {
889 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800890 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700891 }
892 }
893 for (auto &fetcher : fetchers_) {
894 fetcher->Enqueue(message);
895 }
Austin Schuhad154822019-12-27 15:45:13 -0800896
897 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700898}
899
900void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
901 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
902}
903
Austin Schuh8fb315a2020-11-19 22:33:58 -0800904SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
905 SimulatedEventLoop *event_loop)
906 : RawSender(event_loop, simulated_channel->channel()),
907 simulated_channel_(simulated_channel),
Austin Schuh58646e22021-08-23 23:51:46 -0700908 simulated_event_loop_(event_loop) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800909 simulated_channel_->CountSenderCreated();
910}
911
912SimulatedSender::~SimulatedSender() {
913 simulated_channel_->CountSenderDestroyed();
914}
915
Austin Schuh8902fa52021-03-14 22:39:24 -0700916bool SimulatedSender::DoSend(size_t length,
917 monotonic_clock::time_point monotonic_remote_time,
918 realtime_clock::time_point realtime_remote_time,
919 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700920 const UUID &source_boot_uuid) {
Austin Schuh58646e22021-08-23 23:51:46 -0700921 VLOG(1) << simulated_event_loop_->distributed_now() << " "
922 << NodeName(simulated_event_loop_->node())
923 << simulated_event_loop_->monotonic_now() << " "
924 << simulated_event_loop_->name() << " Send "
925 << configuration::StrippedChannelToString(channel());
926
Austin Schuh8fb315a2020-11-19 22:33:58 -0800927 // The allocations in here are due to infrastructure and don't count in the
928 // no mallocs in RT code.
929 ScopedNotRealtime nrt;
930 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuh58646e22021-08-23 23:51:46 -0700931 message_->context.monotonic_event_time =
932 simulated_event_loop_->monotonic_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800933 message_->context.monotonic_remote_time = monotonic_remote_time;
934 message_->context.remote_queue_index = remote_queue_index;
Austin Schuh58646e22021-08-23 23:51:46 -0700935 message_->context.realtime_event_time = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800936 message_->context.realtime_remote_time = realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -0700937 message_->context.source_boot_uuid = source_boot_uuid;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800938 CHECK_LE(length, message_->context.size);
939 message_->context.size = length;
940
941 // TODO(austin): Track sending too fast.
942 sent_queue_index_ = simulated_channel_->Send(message_);
Austin Schuh58646e22021-08-23 23:51:46 -0700943 monotonic_sent_time_ = simulated_event_loop_->monotonic_now();
944 realtime_sent_time_ = simulated_event_loop_->realtime_now();
Austin Schuh8fb315a2020-11-19 22:33:58 -0800945
946 // Drop the reference to the message so that we allocate a new message for
947 // next time. Otherwise we will continue to reuse the same memory for all
948 // messages and corrupt it.
949 message_.reset();
950 return true;
951}
952
Austin Schuh8902fa52021-03-14 22:39:24 -0700953bool SimulatedSender::DoSend(const void *msg, size_t size,
954 monotonic_clock::time_point monotonic_remote_time,
955 realtime_clock::time_point realtime_remote_time,
956 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700957 const UUID &source_boot_uuid) {
Austin Schuh102667e2020-12-11 20:13:28 -0800958 CHECK_LE(size, this->size())
959 << ": Attempting to send too big a message on "
960 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -0800961
962 // This is wasteful, but since flatbuffers fill from the back end of the
963 // queue, we need it to be full sized.
964 message_ = SimulatedMessage::Make(simulated_channel_);
965
966 // Now fill in the message. size is already populated above, and
967 // queue_index will be populated in simulated_channel_. Put this at the
968 // back of the data segment.
969 memcpy(message_->data(simulated_channel_->max_size()) +
970 simulated_channel_->max_size() - size,
971 msg, size);
972
973 return DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700974 remote_queue_index, source_boot_uuid);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800975}
976
Austin Schuh39788ff2019-12-01 18:22:57 -0800977SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800978 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
979 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800980 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800981 simulated_event_loop_(simulated_event_loop),
982 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800983 scheduler_(scheduler),
984 token_(scheduler_->InvalidToken()) {}
985
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800986void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
987 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800988 // The allocations in here are due to infrastructure and don't count in the no
989 // mallocs in RT code.
990 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800991 Disable();
Austin Schuh58646e22021-08-23 23:51:46 -0700992 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800993 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800994 base_ = base;
995 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700996 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
997 DCHECK(token_ != scheduler_->InvalidToken());
998 token_ = scheduler_->InvalidToken();
999 simulated_event_loop_->HandleEvent();
1000 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001001 event_.set_event_time(base_);
1002 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001003}
1004
1005void SimulatedTimerHandler::HandleEvent() {
Austin Schuh58646e22021-08-23 23:51:46 -07001006 const monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -08001007 simulated_event_loop_->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001008 VLOG(1) << simulated_event_loop_->distributed_now() << " "
1009 << NodeName(simulated_event_loop_->node()) << monotonic_now << " "
1010 << simulated_event_loop_->name() << " Timer '" << name() << "'";
Tyler Chatow67ddb032020-01-12 14:30:04 -08001011 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001012 if (simulated_event_loop_->log_impl_) {
1013 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001014 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001015 if (token_ != scheduler_->InvalidToken()) {
1016 scheduler_->Deschedule(token_);
1017 token_ = scheduler_->InvalidToken();
1018 }
Austin Schuh58646e22021-08-23 23:51:46 -07001019 if (repeat_offset_ != monotonic_clock::zero()) {
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001020 // Reschedule.
1021 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001022 token_ = scheduler_->Schedule(base_, [this]() {
1023 DCHECK(token_ != scheduler_->InvalidToken());
1024 token_ = scheduler_->InvalidToken();
1025 simulated_event_loop_->HandleEvent();
1026 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001027 event_.set_event_time(base_);
1028 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001029 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001030
Austin Schuhcc6070c2020-10-10 20:25:56 -07001031 {
1032 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1033 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
1034 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001035}
1036
Austin Schuh7d87b672019-12-01 20:23:49 -08001037void SimulatedTimerHandler::Disable() {
1038 simulated_event_loop_->RemoveEvent(&event_);
1039 if (token_ != scheduler_->InvalidToken()) {
1040 scheduler_->Deschedule(token_);
1041 token_ = scheduler_->InvalidToken();
1042 }
1043}
1044
Austin Schuh39788ff2019-12-01 18:22:57 -08001045SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -08001046 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
1047 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -08001048 const monotonic_clock::duration offset)
1049 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
1050 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -08001051 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -08001052 scheduler_(scheduler),
1053 token_(scheduler_->InvalidToken()) {}
1054
Austin Schuh7d87b672019-12-01 20:23:49 -08001055SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
1056 if (token_ != scheduler_->InvalidToken()) {
1057 scheduler_->Deschedule(token_);
1058 token_ = scheduler_->InvalidToken();
1059 }
1060 simulated_event_loop_->RemoveEvent(&event_);
1061}
1062
1063void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -08001064 monotonic_clock::time_point monotonic_now =
1065 simulated_event_loop_->monotonic_now();
Austin Schuh057d29f2021-08-21 23:05:15 -07001066 VLOG(1) << monotonic_now << " Phased loop " << simulated_event_loop_->name()
1067 << ", " << name();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001068 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -07001069 if (simulated_event_loop_->log_impl_) {
1070 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -08001071 }
Austin Schuhcc6070c2020-10-10 20:25:56 -07001072
1073 {
1074 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
1075 Call([monotonic_now]() { return monotonic_now; },
1076 [this](monotonic_clock::time_point sleep_time) {
1077 Schedule(sleep_time);
1078 });
1079 }
Austin Schuh39788ff2019-12-01 18:22:57 -08001080}
Austin Schuhde8a8ff2019-11-30 15:25:36 -08001081
Austin Schuh7d87b672019-12-01 20:23:49 -08001082void SimulatedPhasedLoopHandler::Schedule(
1083 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -08001084 // The allocations in here are due to infrastructure and don't count in the no
1085 // mallocs in RT code.
1086 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -07001087 if (token_ != scheduler_->InvalidToken()) {
1088 scheduler_->Deschedule(token_);
1089 token_ = scheduler_->InvalidToken();
1090 }
1091 token_ = scheduler_->Schedule(sleep_time, [this]() {
1092 DCHECK(token_ != scheduler_->InvalidToken());
1093 token_ = scheduler_->InvalidToken();
1094 simulated_event_loop_->HandleEvent();
1095 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001096 event_.set_event_time(sleep_time);
1097 simulated_event_loop_->AddEvent(&event_);
1098}
1099
Alex Perrycb7da4b2019-08-28 19:35:56 -07001100SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1101 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001102 : configuration_(CHECK_NOTNULL(configuration)),
1103 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001104 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001105 for (const Node *node : nodes_) {
Austin Schuh58646e22021-08-23 23:51:46 -07001106 node_factories_.emplace_back(
1107 new NodeEventLoopFactory(&scheduler_scheduler_, this, node));
Austin Schuh15649d62019-12-28 16:36:38 -08001108 }
Austin Schuh898f4972020-01-11 17:21:25 -08001109
1110 if (configuration::MultiNode(configuration)) {
1111 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1112 }
Austin Schuh15649d62019-12-28 16:36:38 -08001113}
1114
Alex Perrycb7da4b2019-08-28 19:35:56 -07001115SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1116
Austin Schuhac0771c2020-01-07 18:36:30 -08001117NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuh057d29f2021-08-21 23:05:15 -07001118 std::string_view node) {
1119 return GetNodeEventLoopFactory(configuration::GetNode(configuration(), node));
1120}
1121
1122NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
Austin Schuhac0771c2020-01-07 18:36:30 -08001123 const Node *node) {
1124 auto result = std::find_if(
1125 node_factories_.begin(), node_factories_.end(),
1126 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1127 return node_factory->node() == node;
1128 });
1129
1130 CHECK(result != node_factories_.end())
1131 << ": Failed to find node " << FlatbufferToJson(node);
1132
1133 return result->get();
1134}
1135
Austin Schuh87dd3832021-01-01 23:07:31 -08001136void SimulatedEventLoopFactory::SetTimeConverter(
1137 TimeConverter *time_converter) {
1138 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1139 factory->SetTimeConverter(time_converter);
1140 }
Austin Schuh58646e22021-08-23 23:51:46 -07001141 scheduler_scheduler_.SetTimeConverter(time_converter);
Austin Schuh87dd3832021-01-01 23:07:31 -08001142}
1143
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001144::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001145 std::string_view name, const Node *node) {
1146 if (node == nullptr) {
1147 CHECK(!configuration::MultiNode(configuration()))
1148 << ": Can't make a single node event loop in a multi-node world.";
1149 } else {
1150 CHECK(configuration::MultiNode(configuration()))
1151 << ": Can't make a multi-node event loop in a single-node world.";
1152 }
1153 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1154}
1155
Austin Schuh057d29f2021-08-21 23:05:15 -07001156NodeEventLoopFactory::NodeEventLoopFactory(
1157 EventSchedulerScheduler *scheduler_scheduler,
1158 SimulatedEventLoopFactory *factory, const Node *node)
Austin Schuh58646e22021-08-23 23:51:46 -07001159 : scheduler_(configuration::GetNodeIndex(factory->configuration(), node)),
1160 factory_(factory),
1161 node_(node) {
Austin Schuh057d29f2021-08-21 23:05:15 -07001162 scheduler_scheduler->AddEventScheduler(&scheduler_);
Austin Schuh58646e22021-08-23 23:51:46 -07001163 scheduler_.set_started([this]() {
1164 started_ = true;
1165 for (SimulatedEventLoop *event_loop : event_loops_) {
1166 event_loop->SetIsRunning(true);
1167 }
1168 });
1169 scheduler_.set_on_shutdown([this]() {
1170 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1171 << monotonic_now() << " Shutting down node.";
1172 Shutdown();
1173 ScheduleStartup();
1174 });
1175 ScheduleStartup();
Austin Schuh057d29f2021-08-21 23:05:15 -07001176}
1177
1178NodeEventLoopFactory::~NodeEventLoopFactory() {
Austin Schuh58646e22021-08-23 23:51:46 -07001179 if (started_) {
1180 for (std::function<void()> &fn : on_shutdown_) {
1181 fn();
1182 }
1183
1184 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1185 << monotonic_now() << " Shutting down applications.";
1186 applications_.clear();
1187 started_ = false;
1188 }
1189
1190 if (event_loops_.size() != 0u) {
1191 for (SimulatedEventLoop *event_loop : event_loops_) {
1192 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1193 << monotonic_now() << " Event loop '" << event_loop->name()
1194 << "' failed to shut down";
1195 }
1196 }
Austin Schuh057d29f2021-08-21 23:05:15 -07001197 CHECK_EQ(event_loops_.size(), 0u) << "Event loop didn't exit";
1198}
1199
Austin Schuh58646e22021-08-23 23:51:46 -07001200void NodeEventLoopFactory::OnStartup(std::function<void()> &&fn) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001201 CHECK(!scheduler_.is_running())
Austin Schuh58646e22021-08-23 23:51:46 -07001202 << ": Can only register OnStartup handlers when not running.";
1203 on_startup_.emplace_back(std::move(fn));
1204 if (started_) {
1205 size_t on_startup_index = on_startup_.size() - 1;
1206 scheduler_.ScheduleOnStartup(
1207 [this, on_startup_index]() { on_startup_[on_startup_index](); });
1208 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001209}
1210
Austin Schuh58646e22021-08-23 23:51:46 -07001211void NodeEventLoopFactory::OnShutdown(std::function<void()> &&fn) {
1212 on_shutdown_.emplace_back(std::move(fn));
Austin Schuhc0b0f722020-12-12 18:36:06 -08001213}
Austin Schuh057d29f2021-08-21 23:05:15 -07001214
Austin Schuh58646e22021-08-23 23:51:46 -07001215void NodeEventLoopFactory::ScheduleStartup() {
1216 scheduler_.ScheduleOnStartup([this]() {
1217 UUID next_uuid = scheduler_.boot_uuid();
1218 if (boot_uuid_ != next_uuid) {
1219 CHECK_EQ(boot_uuid_, UUID::Zero());
1220 boot_uuid_ = next_uuid;
1221 }
1222 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(this->node())
1223 << monotonic_now() << " Starting up node on boot " << boot_uuid_;
1224 Startup();
1225 });
1226}
1227
1228void NodeEventLoopFactory::Startup() {
1229 CHECK(!started_);
1230 for (size_t i = 0; i < on_startup_.size(); ++i) {
1231 on_startup_[i]();
1232 }
1233}
1234
1235void NodeEventLoopFactory::Shutdown() {
1236 for (SimulatedEventLoop *event_loop : event_loops_) {
1237 event_loop->SetIsRunning(false);
1238 }
1239
1240 CHECK(started_);
1241 started_ = false;
1242 for (std::function<void()> &fn : on_shutdown_) {
1243 fn();
1244 }
1245
1246 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1247 << monotonic_now() << " Shutting down applications.";
1248 applications_.clear();
1249
1250 if (event_loops_.size() != 0u) {
1251 for (SimulatedEventLoop *event_loop : event_loops_) {
1252 LOG(ERROR) << scheduler_.distributed_now() << " " << NodeName(node())
1253 << monotonic_now() << " Event loop '" << event_loop->name()
1254 << "' failed to shut down";
1255 }
1256 }
1257 CHECK_EQ(event_loops_.size(), 0u) << "Not all event loops shut down";
1258 boot_uuid_ = UUID::Zero();
1259
1260 channels_.clear();
Austin Schuhc0b0f722020-12-12 18:36:06 -08001261}
1262
Alex Perrycb7da4b2019-08-28 19:35:56 -07001263void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
Austin Schuh58646e22021-08-23 23:51:46 -07001264 // This sets running to true too.
Austin Schuh057d29f2021-08-21 23:05:15 -07001265 scheduler_scheduler_.RunOnStartup();
Austin Schuh8bd96322020-02-13 21:18:22 -08001266 scheduler_scheduler_.RunFor(duration);
Austin Schuh057d29f2021-08-21 23:05:15 -07001267 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1268 if (node) {
1269 for (SimulatedEventLoop *loop : node->event_loops_) {
1270 loop->SetIsRunning(false);
1271 }
1272 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001273 }
1274}
1275
1276void SimulatedEventLoopFactory::Run() {
Austin Schuh58646e22021-08-23 23:51:46 -07001277 // This sets running to true too.
Austin Schuh057d29f2021-08-21 23:05:15 -07001278 scheduler_scheduler_.RunOnStartup();
Austin Schuh8bd96322020-02-13 21:18:22 -08001279 scheduler_scheduler_.Run();
Austin Schuh057d29f2021-08-21 23:05:15 -07001280 for (std::unique_ptr<NodeEventLoopFactory> &node : node_factories_) {
1281 if (node) {
1282 for (SimulatedEventLoop *loop : node->event_loops_) {
1283 loop->SetIsRunning(false);
1284 }
1285 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001286 }
1287}
1288
Austin Schuh87dd3832021-01-01 23:07:31 -08001289void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001290
Austin Schuh6f3babe2020-01-26 20:34:50 -08001291void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001292 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001293 bridge_->DisableForwarding(channel);
1294}
1295
Austin Schuh4c3b9702020-08-30 11:34:55 -07001296void SimulatedEventLoopFactory::DisableStatistics() {
1297 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1298 bridge_->DisableStatistics();
1299}
1300
Austin Schuh2928ebe2021-02-07 22:10:27 -08001301void SimulatedEventLoopFactory::SkipTimingReport() {
1302 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
1303 bridge_->SkipTimingReport();
1304}
1305
Austin Schuh58646e22021-08-23 23:51:46 -07001306::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
1307 std::string_view name) {
1308 CHECK(!scheduler_.is_running() || !started_)
1309 << ": Can't create an event loop while running";
1310
1311 pid_t tid = tid_;
1312 ++tid_;
1313 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
1314 &scheduler_, this, &channels_, factory_->configuration(), &event_loops_,
1315 node_, tid));
1316 result->set_name(name);
1317 result->set_send_delay(factory_->send_delay());
1318
1319 VLOG(1) << scheduler_.distributed_now() << " " << NodeName(node())
1320 << monotonic_now() << " MakeEventLoop(\"" << result->name() << "\")";
1321 return std::move(result);
1322}
1323
1324void NodeEventLoopFactory::Disconnect(const Node *other) {
1325 factory_->bridge_->Disconnect(node_, other);
1326}
1327
1328void NodeEventLoopFactory::Connect(const Node *other) {
1329 factory_->bridge_->Connect(node_, other);
1330}
1331
Alex Perrycb7da4b2019-08-28 19:35:56 -07001332} // namespace aos