blob: df0390c54792ef4aa7a3811decbc2569bbc0c1d7 [file] [log] [blame]
Austin Schuh54cf95f2019-11-29 13:14:18 -08001#include "aos/events/event_loop.h"
2
3#include "aos/configuration.h"
4#include "aos/configuration_generated.h"
Tyler Chatow67ddb032020-01-12 14:30:04 -08005#include "aos/logging/implementations.h"
Austin Schuh54cf95f2019-11-29 13:14:18 -08006#include "glog/logging.h"
7
Austin Schuh39788ff2019-12-01 18:22:57 -08008DEFINE_bool(timing_reports, true, "Publish timing reports.");
9DEFINE_int32(timing_report_ms, 1000,
10 "Period in milliseconds to publish timing reports at.");
11
Austin Schuh54cf95f2019-11-29 13:14:18 -080012namespace aos {
Austin Schuhd54780b2020-10-03 16:26:02 -070013namespace {
14void CheckAlignment(const Channel *channel) {
15 if (channel->max_size() % alignof(flatbuffers::largest_scalar_t) != 0) {
16 LOG(FATAL) << "max_size() (" << channel->max_size()
17 << ") is not a multiple of alignment ("
18 << alignof(flatbuffers::largest_scalar_t) << ") for channel "
19 << configuration::CleanedChannelToString(channel) << ".";
20 }
21}
milind1f1dca32021-07-03 13:50:07 -070022
23std::string_view ErrorToString(const RawSender::Error err) {
24 switch (err) {
25 case RawSender::Error::kOk:
26 return "RawSender::Error::kOk";
27 case RawSender::Error::kMessagesSentTooFast:
28 return "RawSender::Error::kMessagesSentTooFast";
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -070029 case RawSender::Error::kInvalidRedzone:
30 return "RawSender::Error::kInvalidRedzone";
milind1f1dca32021-07-03 13:50:07 -070031 }
32 LOG(FATAL) << "Unknown error given with code " << static_cast<int>(err);
33}
Austin Schuhd54780b2020-10-03 16:26:02 -070034} // namespace
Austin Schuh54cf95f2019-11-29 13:14:18 -080035
milind1f1dca32021-07-03 13:50:07 -070036std::ostream &operator<<(std::ostream &os, const RawSender::Error err) {
37 os << ErrorToString(err);
38 return os;
39}
40
41void RawSender::CheckOk(const RawSender::Error err) {
42 CHECK_EQ(err, Error::kOk) << "Messages were sent too fast on channel: "
43 << configuration::CleanedChannelToString(channel_);
44}
45
Austin Schuh39788ff2019-12-01 18:22:57 -080046RawSender::RawSender(EventLoop *event_loop, const Channel *channel)
47 : event_loop_(event_loop),
48 channel_(channel),
Brian Silverman79ec7fc2020-06-08 20:11:22 -050049 ftrace_prefix_(configuration::StrippedChannelToString(channel)),
Austin Schuh39788ff2019-12-01 18:22:57 -080050 timing_(event_loop_->ChannelIndex(channel)) {
51 event_loop_->NewSender(this);
52}
53
54RawSender::~RawSender() { event_loop_->DeleteSender(this); }
55
milind1f1dca32021-07-03 13:50:07 -070056RawSender::Error RawSender::DoSend(
57 const SharedSpan data, monotonic_clock::time_point monotonic_remote_time,
58 realtime_clock::time_point realtime_remote_time,
59 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070060 return DoSend(data->data(), data->size(), monotonic_remote_time,
61 realtime_remote_time, remote_queue_index, source_boot_uuid);
62}
63
James Kuszmaul93abac12022-04-14 15:05:10 -070064void RawSender::RecordSendResult(const Error error, size_t message_size) {
65 switch (error) {
66 case Error::kOk: {
67 if (timing_.sender) {
68 timing_.size.Add(message_size);
69 timing_.sender->mutate_count(timing_.sender->count() + 1);
70 }
71 break;
72 }
73 case Error::kMessagesSentTooFast:
74 timing_.IncrementError(timing::SendError::MESSAGE_SENT_TOO_FAST);
75 break;
76 case Error::kInvalidRedzone:
77 timing_.IncrementError(timing::SendError::INVALID_REDZONE);
78 break;
79 }
80}
81
Austin Schuh39788ff2019-12-01 18:22:57 -080082RawFetcher::RawFetcher(EventLoop *event_loop, const Channel *channel)
83 : event_loop_(event_loop),
84 channel_(channel),
Brian Silverman79ec7fc2020-06-08 20:11:22 -050085 ftrace_prefix_(configuration::StrippedChannelToString(channel)),
Austin Schuh39788ff2019-12-01 18:22:57 -080086 timing_(event_loop_->ChannelIndex(channel)) {
Austin Schuhad154822019-12-27 15:45:13 -080087 context_.monotonic_event_time = monotonic_clock::min_time;
88 context_.monotonic_remote_time = monotonic_clock::min_time;
89 context_.realtime_event_time = realtime_clock::min_time;
90 context_.realtime_remote_time = realtime_clock::min_time;
Austin Schuh39788ff2019-12-01 18:22:57 -080091 context_.queue_index = 0xffffffff;
92 context_.size = 0;
93 context_.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -070094 context_.buffer_index = -1;
Austin Schuh39788ff2019-12-01 18:22:57 -080095 event_loop_->NewFetcher(this);
96}
97
98RawFetcher::~RawFetcher() { event_loop_->DeleteFetcher(this); }
99
100TimerHandler::TimerHandler(EventLoop *event_loop, std::function<void()> fn)
101 : event_loop_(event_loop), fn_(std::move(fn)) {}
102
103TimerHandler::~TimerHandler() {}
104
105PhasedLoopHandler::PhasedLoopHandler(EventLoop *event_loop,
106 std::function<void(int)> fn,
107 const monotonic_clock::duration interval,
108 const monotonic_clock::duration offset)
109 : event_loop_(event_loop),
110 fn_(std::move(fn)),
111 phased_loop_(interval, event_loop_->monotonic_now(), offset) {
112 event_loop_->OnRun([this]() {
113 const monotonic_clock::time_point monotonic_now =
114 event_loop_->monotonic_now();
115 phased_loop_.Reset(monotonic_now);
116 Reschedule(
117 [this](monotonic_clock::time_point sleep_time) {
118 Schedule(sleep_time);
119 },
120 monotonic_now);
Milind Upadhyay42589bb2021-05-19 20:05:16 -0700121 // Reschedule here will count cycles elapsed before now, and then the
122 // reschedule before running the handler will count the time that elapsed
123 // then. So clear the count here.
Austin Schuh39788ff2019-12-01 18:22:57 -0800124 cycles_elapsed_ = 0;
125 });
126}
127
128PhasedLoopHandler::~PhasedLoopHandler() {}
129
Austin Schuh83c7f702021-01-19 22:36:29 -0800130EventLoop::EventLoop(const Configuration *configuration)
131 : timing_report_(flatbuffers::DetachedBuffer()),
Austin Schuh56196432020-10-24 20:15:21 -0700132 configuration_(configuration) {}
Tyler Chatow67ddb032020-01-12 14:30:04 -0800133
Austin Schuh39788ff2019-12-01 18:22:57 -0800134EventLoop::~EventLoop() {
Brian Silvermanbf889922021-11-10 12:41:57 -0800135 if (!senders_.empty()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700136 for (const RawSender *sender : senders_) {
137 LOG(ERROR) << " Sender "
138 << configuration::StrippedChannelToString(sender->channel())
139 << " still open";
140 }
141 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800142 CHECK_EQ(senders_.size(), 0u) << ": Not all senders destroyed";
Austin Schuh7d87b672019-12-01 20:23:49 -0800143 CHECK_EQ(events_.size(), 0u) << ": Not all events unregistered";
Austin Schuh39788ff2019-12-01 18:22:57 -0800144}
145
Brian Silvermanbf889922021-11-10 12:41:57 -0800146void EventLoop::SkipTimingReport() {
147 skip_timing_report_ = true;
148 timing_report_ = flatbuffers::DetachedBuffer();
149
150 for (size_t i = 0; i < timers_.size(); ++i) {
151 timers_[i]->timing_.set_timing_report(nullptr);
152 }
153
154 for (size_t i = 0; i < phased_loops_.size(); ++i) {
155 phased_loops_[i]->timing_.set_timing_report(nullptr);
156 }
157
158 for (size_t i = 0; i < watchers_.size(); ++i) {
159 watchers_[i]->set_timing_report(nullptr);
160 }
161
162 for (size_t i = 0; i < senders_.size(); ++i) {
163 senders_[i]->timing_.set_timing_report(nullptr);
164 }
165
166 for (size_t i = 0; i < fetchers_.size(); ++i) {
167 fetchers_[i]->timing_.set_timing_report(nullptr);
168 }
169}
170
Austin Schuh39788ff2019-12-01 18:22:57 -0800171int EventLoop::ChannelIndex(const Channel *channel) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800172 return configuration::ChannelIndex(configuration_, channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800173}
174
Brian Silverman5120afb2020-01-31 17:44:35 -0800175WatcherState *EventLoop::GetWatcherState(const Channel *channel) {
176 const int channel_index = ChannelIndex(channel);
177 for (const std::unique_ptr<WatcherState> &watcher : watchers_) {
178 if (watcher->channel_index() == channel_index) {
179 return watcher.get();
180 }
181 }
182 LOG(FATAL) << "No watcher found for channel";
183}
184
Austin Schuh39788ff2019-12-01 18:22:57 -0800185void EventLoop::NewSender(RawSender *sender) {
186 senders_.emplace_back(sender);
187 UpdateTimingReport();
188}
189void EventLoop::DeleteSender(RawSender *sender) {
190 CHECK(!is_running());
191 auto s = std::find(senders_.begin(), senders_.end(), sender);
192 CHECK(s != senders_.end()) << ": Sender not in senders list";
193 senders_.erase(s);
194 UpdateTimingReport();
195}
196
197TimerHandler *EventLoop::NewTimer(std::unique_ptr<TimerHandler> timer) {
198 timers_.emplace_back(std::move(timer));
199 UpdateTimingReport();
200 return timers_.back().get();
201}
202
203PhasedLoopHandler *EventLoop::NewPhasedLoop(
204 std::unique_ptr<PhasedLoopHandler> phased_loop) {
205 phased_loops_.emplace_back(std::move(phased_loop));
206 UpdateTimingReport();
207 return phased_loops_.back().get();
208}
209
210void EventLoop::NewFetcher(RawFetcher *fetcher) {
Austin Schuhd54780b2020-10-03 16:26:02 -0700211 CheckAlignment(fetcher->channel());
212
Austin Schuh39788ff2019-12-01 18:22:57 -0800213 fetchers_.emplace_back(fetcher);
214 UpdateTimingReport();
215}
216
217void EventLoop::DeleteFetcher(RawFetcher *fetcher) {
218 CHECK(!is_running());
219 auto f = std::find(fetchers_.begin(), fetchers_.end(), fetcher);
220 CHECK(f != fetchers_.end()) << ": Fetcher not in fetchers list";
221 fetchers_.erase(f);
222 UpdateTimingReport();
223}
224
225WatcherState *EventLoop::NewWatcher(std::unique_ptr<WatcherState> watcher) {
226 watchers_.emplace_back(std::move(watcher));
227
228 UpdateTimingReport();
229
230 return watchers_.back().get();
231}
232
Brian Silverman0fc69932020-01-24 21:54:02 -0800233void EventLoop::TakeWatcher(const Channel *channel) {
234 CHECK(!is_running()) << ": Cannot add new objects while running.";
235 ChannelIndex(channel);
236
Austin Schuhd54780b2020-10-03 16:26:02 -0700237 CheckAlignment(channel);
238
Brian Silverman0fc69932020-01-24 21:54:02 -0800239 CHECK(taken_senders_.find(channel) == taken_senders_.end())
Austin Schuh8072f922020-02-16 21:51:47 -0800240 << ": " << configuration::CleanedChannelToString(channel)
241 << " is already being used.";
Brian Silverman0fc69932020-01-24 21:54:02 -0800242
243 auto result = taken_watchers_.insert(channel);
Austin Schuh8072f922020-02-16 21:51:47 -0800244 CHECK(result.second) << ": " << configuration::CleanedChannelToString(channel)
Brian Silverman0fc69932020-01-24 21:54:02 -0800245 << " is already being used.";
246
247 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
Austin Schuh8072f922020-02-16 21:51:47 -0800248 LOG(FATAL) << ": " << configuration::CleanedChannelToString(channel)
Brian Silverman0fc69932020-01-24 21:54:02 -0800249 << " is not able to be watched on this node. Check your "
250 "configuration.";
251 }
252}
253
254void EventLoop::TakeSender(const Channel *channel) {
255 CHECK(!is_running()) << ": Cannot add new objects while running.";
256 ChannelIndex(channel);
257
Austin Schuhd54780b2020-10-03 16:26:02 -0700258 CheckAlignment(channel);
259
Brian Silverman0fc69932020-01-24 21:54:02 -0800260 CHECK(taken_watchers_.find(channel) == taken_watchers_.end())
Austin Schuh8072f922020-02-16 21:51:47 -0800261 << ": Channel " << configuration::CleanedChannelToString(channel)
262 << " is already being used.";
Brian Silverman0fc69932020-01-24 21:54:02 -0800263
264 // We don't care if this is a duplicate.
265 taken_senders_.insert(channel);
266}
267
Austin Schuh39788ff2019-12-01 18:22:57 -0800268void EventLoop::SendTimingReport() {
Brian Silvermance418d02021-11-03 11:25:52 -0700269 if (!timing_report_sender_) {
270 // Timing reports are disabled, so nothing for us to do.
271 return;
272 }
273
Austin Schuh39788ff2019-12-01 18:22:57 -0800274 // We need to do a fancy dance here to get all the accounting to work right.
275 // We want to copy the memory here, but then send after resetting. Otherwise
276 // the send for the timing report won't be counted in the timing report.
277 //
278 // Also, flatbuffers build from the back end. So place this at the back end
279 // of the buffer. We only have to care because we are using this in a very
280 // raw fashion.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800281 CHECK_LE(timing_report_.span().size(), timing_report_sender_->size())
Austin Schuh39788ff2019-12-01 18:22:57 -0800282 << ": Timing report bigger than the sender size.";
Austin Schuhadd6eb32020-11-09 21:24:26 -0800283 std::copy(timing_report_.span().data(),
284 timing_report_.span().data() + timing_report_.span().size(),
Austin Schuh39788ff2019-12-01 18:22:57 -0800285 reinterpret_cast<uint8_t *>(timing_report_sender_->data()) +
Austin Schuhadd6eb32020-11-09 21:24:26 -0800286 timing_report_sender_->size() - timing_report_.span().size());
Austin Schuh39788ff2019-12-01 18:22:57 -0800287
288 for (const std::unique_ptr<TimerHandler> &timer : timers_) {
289 timer->timing_.ResetTimingReport();
290 }
291 for (const std::unique_ptr<WatcherState> &watcher : watchers_) {
292 watcher->ResetReport();
293 }
294 for (const std::unique_ptr<PhasedLoopHandler> &phased_loop : phased_loops_) {
295 phased_loop->timing_.ResetTimingReport();
296 }
297 for (RawSender *sender : senders_) {
298 sender->timing_.ResetTimingReport();
299 }
300 for (RawFetcher *fetcher : fetchers_) {
301 fetcher->timing_.ResetTimingReport();
302 }
milind1f1dca32021-07-03 13:50:07 -0700303 // TODO(milind): If we fail to send, we don't want to reset the timing report.
304 // We would need to move the reset after the send, and then find the correct
305 // timing report and set the reports with it instead of letting the sender do
306 // this. If we failed to send, we wouldn't reset or set the reports, so they
307 // can accumalate until the next send.
308 timing_report_failure_counter_.Count(
309 timing_report_sender_->Send(timing_report_.span().size()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800310}
311
312void EventLoop::UpdateTimingReport() {
Brian Silvermanbf889922021-11-10 12:41:57 -0800313 if (skip_timing_report_) {
314 return;
315 }
316
Austin Schuh39788ff2019-12-01 18:22:57 -0800317 // We need to support senders and fetchers changing while we are setting up
318 // the event loop. Otherwise we can't fetch or send until the loop runs. This
319 // means that on each change, we need to redo all this work. This makes setup
320 // more expensive, but not by all that much on a modern processor.
321
322 // Now, build up a report with everything pre-filled out.
323 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800324 fbb.ForceDefaults(true);
Austin Schuh39788ff2019-12-01 18:22:57 -0800325
326 // Pre-fill in the defaults for timers.
327 std::vector<flatbuffers::Offset<timing::Timer>> timer_offsets;
328 for (const std::unique_ptr<TimerHandler> &timer : timers_) {
329 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
330 timing::CreateStatistic(fbb);
331 flatbuffers::Offset<timing::Statistic> handler_time_offset =
332 timing::CreateStatistic(fbb);
333 flatbuffers::Offset<flatbuffers::String> name_offset;
334 if (timer->name().size() != 0) {
335 name_offset = fbb.CreateString(timer->name());
336 }
337
338 timing::Timer::Builder timer_builder(fbb);
339
340 if (timer->name().size() != 0) {
341 timer_builder.add_name(name_offset);
342 }
343 timer_builder.add_wakeup_latency(wakeup_latency_offset);
344 timer_builder.add_handler_time(handler_time_offset);
345 timer_builder.add_count(0);
346 timer_offsets.emplace_back(timer_builder.Finish());
347 }
348
349 // Pre-fill in the defaults for phased_loops.
350 std::vector<flatbuffers::Offset<timing::Timer>> phased_loop_offsets;
351 for (const std::unique_ptr<PhasedLoopHandler> &phased_loop : phased_loops_) {
352 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
353 timing::CreateStatistic(fbb);
354 flatbuffers::Offset<timing::Statistic> handler_time_offset =
355 timing::CreateStatistic(fbb);
356 flatbuffers::Offset<flatbuffers::String> name_offset;
357 if (phased_loop->name().size() != 0) {
358 name_offset = fbb.CreateString(phased_loop->name());
359 }
360
361 timing::Timer::Builder timer_builder(fbb);
362
363 if (phased_loop->name().size() != 0) {
364 timer_builder.add_name(name_offset);
365 }
366 timer_builder.add_wakeup_latency(wakeup_latency_offset);
367 timer_builder.add_handler_time(handler_time_offset);
368 timer_builder.add_count(0);
369 phased_loop_offsets.emplace_back(timer_builder.Finish());
370 }
371
372 // Pre-fill in the defaults for watchers.
373 std::vector<flatbuffers::Offset<timing::Watcher>> watcher_offsets;
374 for (const std::unique_ptr<WatcherState> &watcher : watchers_) {
375 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
376 timing::CreateStatistic(fbb);
377 flatbuffers::Offset<timing::Statistic> handler_time_offset =
378 timing::CreateStatistic(fbb);
379
380 timing::Watcher::Builder watcher_builder(fbb);
381
382 watcher_builder.add_channel_index(watcher->channel_index());
383 watcher_builder.add_wakeup_latency(wakeup_latency_offset);
384 watcher_builder.add_handler_time(handler_time_offset);
385 watcher_builder.add_count(0);
386 watcher_offsets.emplace_back(watcher_builder.Finish());
387 }
388
389 // Pre-fill in the defaults for senders.
390 std::vector<flatbuffers::Offset<timing::Sender>> sender_offsets;
391 for (const RawSender *sender : senders_) {
392 flatbuffers::Offset<timing::Statistic> size_offset =
393 timing::CreateStatistic(fbb);
394
James Kuszmaul78514332022-04-06 15:08:34 -0700395 std::vector<flatbuffers::Offset<timing::SendErrorCount>>
396 error_count_offsets;
397 for (size_t ii = 0; ii < internal::RawSenderTiming::kNumErrors; ++ii) {
398 error_count_offsets.push_back(timing::CreateSendErrorCount(
399 fbb, timing::EnumValuesSendError()[ii], 0));
400 }
401 const flatbuffers::Offset<
402 flatbuffers::Vector<flatbuffers::Offset<timing::SendErrorCount>>>
403 error_counts_offset = fbb.CreateVector(error_count_offsets);
404
Austin Schuh39788ff2019-12-01 18:22:57 -0800405 timing::Sender::Builder sender_builder(fbb);
406
407 sender_builder.add_channel_index(sender->timing_.channel_index);
408 sender_builder.add_size(size_offset);
James Kuszmaul78514332022-04-06 15:08:34 -0700409 sender_builder.add_error_counts(error_counts_offset);
Austin Schuh39788ff2019-12-01 18:22:57 -0800410 sender_builder.add_count(0);
411 sender_offsets.emplace_back(sender_builder.Finish());
412 }
413
414 // Pre-fill in the defaults for fetchers.
415 std::vector<flatbuffers::Offset<timing::Fetcher>> fetcher_offsets;
416 for (RawFetcher *fetcher : fetchers_) {
417 flatbuffers::Offset<timing::Statistic> latency_offset =
418 timing::CreateStatistic(fbb);
419
420 timing::Fetcher::Builder fetcher_builder(fbb);
421
422 fetcher_builder.add_channel_index(fetcher->timing_.channel_index);
423 fetcher_builder.add_count(0);
424 fetcher_builder.add_latency(latency_offset);
425 fetcher_offsets.emplace_back(fetcher_builder.Finish());
426 }
427
428 // Then build the final report.
429 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Timer>>>
430 timers_offset;
431 if (timer_offsets.size() > 0) {
432 timers_offset = fbb.CreateVector(timer_offsets);
433 }
434
435 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Timer>>>
436 phased_loops_offset;
437 if (phased_loop_offsets.size() > 0) {
438 phased_loops_offset = fbb.CreateVector(phased_loop_offsets);
439 }
440
441 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Watcher>>>
442 watchers_offset;
443 if (watcher_offsets.size() > 0) {
444 watchers_offset = fbb.CreateVector(watcher_offsets);
445 }
446
447 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Sender>>>
448 senders_offset;
449 if (sender_offsets.size() > 0) {
450 senders_offset = fbb.CreateVector(sender_offsets);
451 }
452
453 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Fetcher>>>
454 fetchers_offset;
455 if (fetcher_offsets.size() > 0) {
456 fetchers_offset = fbb.CreateVector(fetcher_offsets);
457 }
458
459 flatbuffers::Offset<flatbuffers::String> name_offset =
460 fbb.CreateString(name());
461
462 timing::Report::Builder report_builder(fbb);
463 report_builder.add_name(name_offset);
464 report_builder.add_pid(GetTid());
465 if (timer_offsets.size() > 0) {
466 report_builder.add_timers(timers_offset);
467 }
468 if (phased_loop_offsets.size() > 0) {
469 report_builder.add_phased_loops(phased_loops_offset);
470 }
471 if (watcher_offsets.size() > 0) {
472 report_builder.add_watchers(watchers_offset);
473 }
474 if (sender_offsets.size() > 0) {
475 report_builder.add_senders(senders_offset);
476 }
477 if (fetcher_offsets.size() > 0) {
478 report_builder.add_fetchers(fetchers_offset);
479 }
milind1f1dca32021-07-03 13:50:07 -0700480 report_builder.add_send_failures(timing_report_failure_counter_.failures());
Austin Schuh39788ff2019-12-01 18:22:57 -0800481 fbb.Finish(report_builder.Finish());
482
483 timing_report_ = FlatbufferDetachedBuffer<timing::Report>(fbb.Release());
484
485 // Now that the pointers are stable, pass them to the timers and watchers to
486 // be updated.
487 for (size_t i = 0; i < timers_.size(); ++i) {
488 timers_[i]->timing_.set_timing_report(
489 timing_report_.mutable_message()->mutable_timers()->GetMutableObject(
490 i));
491 }
492
493 for (size_t i = 0; i < phased_loops_.size(); ++i) {
494 phased_loops_[i]->timing_.set_timing_report(
495 timing_report_.mutable_message()
496 ->mutable_phased_loops()
497 ->GetMutableObject(i));
498 }
499
500 for (size_t i = 0; i < watchers_.size(); ++i) {
501 watchers_[i]->set_timing_report(
502 timing_report_.mutable_message()->mutable_watchers()->GetMutableObject(
503 i));
504 }
505
506 for (size_t i = 0; i < senders_.size(); ++i) {
507 senders_[i]->timing_.set_timing_report(
508 timing_report_.mutable_message()->mutable_senders()->GetMutableObject(
509 i));
510 }
511
512 for (size_t i = 0; i < fetchers_.size(); ++i) {
513 fetchers_[i]->timing_.set_timing_report(
514 timing_report_.mutable_message()->mutable_fetchers()->GetMutableObject(
515 i));
516 }
517}
518
519void EventLoop::MaybeScheduleTimingReports() {
520 if (FLAGS_timing_reports && !skip_timing_report_) {
521 CHECK(!timing_report_sender_) << ": Timing reports already scheduled.";
522 // Make a raw sender for the report.
523 const Channel *channel = configuration::GetChannel(
524 configuration(), "/aos", timing::Report::GetFullyQualifiedName(),
Austin Schuhbca6cf02019-12-22 17:28:34 -0800525 name(), node());
Austin Schuh196a4452020-03-15 23:12:03 -0700526 CHECK(channel != nullptr) << ": Failed to look up {\"name\": \"/aos\", "
527 "\"type\": \"aos.timing.Report\"} on node "
528 << FlatbufferToJson(node());
Austin Schuhbca6cf02019-12-22 17:28:34 -0800529
530 // Since we are using a RawSender, validity isn't checked. So check it
531 // ourselves.
Austin Schuhca4828c2019-12-28 14:21:35 -0800532 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
533 LOG(FATAL) << "Channel { \"name\": \"/aos"
534 << channel->name()->string_view() << "\", \"type\": \""
535 << channel->type()->string_view()
536 << "\" } is not able to be sent on this node. Check your "
537 "configuration.";
Austin Schuhbca6cf02019-12-22 17:28:34 -0800538 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800539 CHECK(channel != nullptr) << ": Channel { \"name\": \"/aos\", \"type\": \""
540 << timing::Report::GetFullyQualifiedName()
541 << "\" } not found in config.";
542 timing_report_sender_ = MakeRawSender(channel);
543
544 // Register a handler which sends the report out by copying the raw data
545 // from the prebuilt and subsequently modified report.
546 TimerHandler *timing_reports_timer =
547 AddTimer([this]() { SendTimingReport(); });
548
549 // Set it up to send once per second.
550 timing_reports_timer->set_name("timing_reports");
551 OnRun([this, timing_reports_timer]() {
552 timing_reports_timer->Setup(
553 monotonic_now() + std::chrono::milliseconds(FLAGS_timing_report_ms),
554 std::chrono::milliseconds(FLAGS_timing_report_ms));
555 });
556
557 UpdateTimingReport();
558 }
559}
560
Austin Schuh7d87b672019-12-01 20:23:49 -0800561void EventLoop::ReserveEvents() {
562 events_.reserve(timers_.size() + phased_loops_.size() + watchers_.size());
563}
564
565namespace {
566bool CompareEvents(const EventLoopEvent *first, const EventLoopEvent *second) {
Brian Silvermanbd405c02020-06-23 16:25:23 -0700567 if (first->event_time() > second->event_time()) {
568 return true;
569 }
570 if (first->event_time() < second->event_time()) {
571 return false;
572 }
573 return first->generation() > second->generation();
Austin Schuh7d87b672019-12-01 20:23:49 -0800574}
575} // namespace
576
577void EventLoop::AddEvent(EventLoopEvent *event) {
578 DCHECK(std::find(events_.begin(), events_.end(), event) == events_.end());
Brian Silvermanbd405c02020-06-23 16:25:23 -0700579 DCHECK(event->generation() == 0);
580 event->set_generation(++event_generation_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800581 events_.push_back(event);
582 std::push_heap(events_.begin(), events_.end(), CompareEvents);
583}
584
585void EventLoop::RemoveEvent(EventLoopEvent *event) {
586 auto e = std::find(events_.begin(), events_.end(), event);
587 if (e != events_.end()) {
Brian Silvermanbd405c02020-06-23 16:25:23 -0700588 DCHECK(event->generation() != 0);
Austin Schuh7d87b672019-12-01 20:23:49 -0800589 events_.erase(e);
590 std::make_heap(events_.begin(), events_.end(), CompareEvents);
591 event->Invalidate();
592 }
593}
594
595EventLoopEvent *EventLoop::PopEvent() {
596 EventLoopEvent *result = events_.front();
597 std::pop_heap(events_.begin(), events_.end(), CompareEvents);
598 events_.pop_back();
599 result->Invalidate();
600 return result;
601}
602
Austin Schuha9012be2021-07-21 15:19:11 -0700603void EventLoop::SetTimerContext(
604 monotonic_clock::time_point monotonic_event_time) {
605 context_.monotonic_event_time = monotonic_event_time;
606 context_.monotonic_remote_time = monotonic_clock::min_time;
607 context_.realtime_event_time = realtime_clock::min_time;
608 context_.realtime_remote_time = realtime_clock::min_time;
609 context_.queue_index = 0xffffffffu;
610 context_.size = 0u;
611 context_.data = nullptr;
612 context_.buffer_index = -1;
613 context_.source_boot_uuid = boot_uuid();
614}
615
Austin Schuh39788ff2019-12-01 18:22:57 -0800616void WatcherState::set_timing_report(timing::Watcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800617 watcher_ = watcher;
Brian Silvermanbf889922021-11-10 12:41:57 -0800618 if (!watcher) {
619 wakeup_latency_.set_statistic(nullptr);
620 handler_time_.set_statistic(nullptr);
621 } else {
622 wakeup_latency_.set_statistic(watcher->mutable_wakeup_latency());
623 handler_time_.set_statistic(watcher->mutable_handler_time());
624 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800625}
626
627void WatcherState::ResetReport() {
Brian Silvermanbf889922021-11-10 12:41:57 -0800628 if (!watcher_) {
629 return;
630 }
631
Austin Schuh39788ff2019-12-01 18:22:57 -0800632 wakeup_latency_.Reset();
633 handler_time_.Reset();
634 watcher_->mutate_count(0);
Austin Schuh54cf95f2019-11-29 13:14:18 -0800635}
636
637} // namespace aos