blob: c6d37551d04df4eed7f43cd06cb5cc460c88e8f5 [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"
5#include "glog/logging.h"
6
Austin Schuh39788ff2019-12-01 18:22:57 -08007DEFINE_bool(timing_reports, true, "Publish timing reports.");
8DEFINE_int32(timing_report_ms, 1000,
9 "Period in milliseconds to publish timing reports at.");
10
Austin Schuh54cf95f2019-11-29 13:14:18 -080011namespace aos {
12
Austin Schuh39788ff2019-12-01 18:22:57 -080013RawSender::RawSender(EventLoop *event_loop, const Channel *channel)
14 : event_loop_(event_loop),
15 channel_(channel),
16 timing_(event_loop_->ChannelIndex(channel)) {
17 event_loop_->NewSender(this);
18}
19
20RawSender::~RawSender() { event_loop_->DeleteSender(this); }
21
22RawFetcher::RawFetcher(EventLoop *event_loop, const Channel *channel)
23 : event_loop_(event_loop),
24 channel_(channel),
25 timing_(event_loop_->ChannelIndex(channel)) {
Austin Schuhad154822019-12-27 15:45:13 -080026 context_.monotonic_event_time = monotonic_clock::min_time;
27 context_.monotonic_remote_time = monotonic_clock::min_time;
28 context_.realtime_event_time = realtime_clock::min_time;
29 context_.realtime_remote_time = realtime_clock::min_time;
Austin Schuh39788ff2019-12-01 18:22:57 -080030 context_.queue_index = 0xffffffff;
31 context_.size = 0;
32 context_.data = nullptr;
33 event_loop_->NewFetcher(this);
34}
35
36RawFetcher::~RawFetcher() { event_loop_->DeleteFetcher(this); }
37
38TimerHandler::TimerHandler(EventLoop *event_loop, std::function<void()> fn)
39 : event_loop_(event_loop), fn_(std::move(fn)) {}
40
41TimerHandler::~TimerHandler() {}
42
43PhasedLoopHandler::PhasedLoopHandler(EventLoop *event_loop,
44 std::function<void(int)> fn,
45 const monotonic_clock::duration interval,
46 const monotonic_clock::duration offset)
47 : event_loop_(event_loop),
48 fn_(std::move(fn)),
49 phased_loop_(interval, event_loop_->monotonic_now(), offset) {
50 event_loop_->OnRun([this]() {
51 const monotonic_clock::time_point monotonic_now =
52 event_loop_->monotonic_now();
53 phased_loop_.Reset(monotonic_now);
54 Reschedule(
55 [this](monotonic_clock::time_point sleep_time) {
56 Schedule(sleep_time);
57 },
58 monotonic_now);
59 // The first time, we'll double count. Reschedule here will count cycles
60 // elapsed before now, and then the reschedule before runing the handler
61 // will count the time that elapsed then. So clear the count here.
62 cycles_elapsed_ = 0;
63 });
64}
65
66PhasedLoopHandler::~PhasedLoopHandler() {}
67
68EventLoop::~EventLoop() {
69 CHECK_EQ(senders_.size(), 0u) << ": Not all senders destroyed";
Austin Schuh7d87b672019-12-01 20:23:49 -080070 CHECK_EQ(events_.size(), 0u) << ": Not all events unregistered";
Austin Schuh39788ff2019-12-01 18:22:57 -080071}
72
73int EventLoop::ChannelIndex(const Channel *channel) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -080074 return configuration::ChannelIndex(configuration_, channel);
Austin Schuh39788ff2019-12-01 18:22:57 -080075}
76
77void EventLoop::NewSender(RawSender *sender) {
78 senders_.emplace_back(sender);
79 UpdateTimingReport();
80}
81void EventLoop::DeleteSender(RawSender *sender) {
82 CHECK(!is_running());
83 auto s = std::find(senders_.begin(), senders_.end(), sender);
84 CHECK(s != senders_.end()) << ": Sender not in senders list";
85 senders_.erase(s);
86 UpdateTimingReport();
87}
88
89TimerHandler *EventLoop::NewTimer(std::unique_ptr<TimerHandler> timer) {
90 timers_.emplace_back(std::move(timer));
91 UpdateTimingReport();
92 return timers_.back().get();
93}
94
95PhasedLoopHandler *EventLoop::NewPhasedLoop(
96 std::unique_ptr<PhasedLoopHandler> phased_loop) {
97 phased_loops_.emplace_back(std::move(phased_loop));
98 UpdateTimingReport();
99 return phased_loops_.back().get();
100}
101
102void EventLoop::NewFetcher(RawFetcher *fetcher) {
103 fetchers_.emplace_back(fetcher);
104 UpdateTimingReport();
105}
106
107void EventLoop::DeleteFetcher(RawFetcher *fetcher) {
108 CHECK(!is_running());
109 auto f = std::find(fetchers_.begin(), fetchers_.end(), fetcher);
110 CHECK(f != fetchers_.end()) << ": Fetcher not in fetchers list";
111 fetchers_.erase(f);
112 UpdateTimingReport();
113}
114
115WatcherState *EventLoop::NewWatcher(std::unique_ptr<WatcherState> watcher) {
116 watchers_.emplace_back(std::move(watcher));
117
118 UpdateTimingReport();
119
120 return watchers_.back().get();
121}
122
Brian Silverman0fc69932020-01-24 21:54:02 -0800123void EventLoop::TakeWatcher(const Channel *channel) {
124 CHECK(!is_running()) << ": Cannot add new objects while running.";
125 ChannelIndex(channel);
126
127 CHECK(taken_senders_.find(channel) == taken_senders_.end())
128 << ": " << FlatbufferToJson(channel) << " is already being used.";
129
130 auto result = taken_watchers_.insert(channel);
131 CHECK(result.second) << ": " << FlatbufferToJson(channel)
132 << " is already being used.";
133
134 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
135 LOG(FATAL) << ": " << FlatbufferToJson(channel)
136 << " is not able to be watched on this node. Check your "
137 "configuration.";
138 }
139}
140
141void EventLoop::TakeSender(const Channel *channel) {
142 CHECK(!is_running()) << ": Cannot add new objects while running.";
143 ChannelIndex(channel);
144
145 CHECK(taken_watchers_.find(channel) == taken_watchers_.end())
146 << ": Channel " << FlatbufferToJson(channel) << " is already being used.";
147
148 // We don't care if this is a duplicate.
149 taken_senders_.insert(channel);
150}
151
Austin Schuh39788ff2019-12-01 18:22:57 -0800152void EventLoop::SendTimingReport() {
153 // We need to do a fancy dance here to get all the accounting to work right.
154 // We want to copy the memory here, but then send after resetting. Otherwise
155 // the send for the timing report won't be counted in the timing report.
156 //
157 // Also, flatbuffers build from the back end. So place this at the back end
158 // of the buffer. We only have to care because we are using this in a very
159 // raw fashion.
160 CHECK_LE(timing_report_.size(), timing_report_sender_->size())
161 << ": Timing report bigger than the sender size.";
162 std::copy(timing_report_.data(),
163 timing_report_.data() + timing_report_.size(),
164 reinterpret_cast<uint8_t *>(timing_report_sender_->data()) +
165 timing_report_sender_->size() - timing_report_.size());
166
167 for (const std::unique_ptr<TimerHandler> &timer : timers_) {
168 timer->timing_.ResetTimingReport();
169 }
170 for (const std::unique_ptr<WatcherState> &watcher : watchers_) {
171 watcher->ResetReport();
172 }
173 for (const std::unique_ptr<PhasedLoopHandler> &phased_loop : phased_loops_) {
174 phased_loop->timing_.ResetTimingReport();
175 }
176 for (RawSender *sender : senders_) {
177 sender->timing_.ResetTimingReport();
178 }
179 for (RawFetcher *fetcher : fetchers_) {
180 fetcher->timing_.ResetTimingReport();
181 }
182 timing_report_sender_->Send(timing_report_.size());
183}
184
185void EventLoop::UpdateTimingReport() {
186 // We need to support senders and fetchers changing while we are setting up
187 // the event loop. Otherwise we can't fetch or send until the loop runs. This
188 // means that on each change, we need to redo all this work. This makes setup
189 // more expensive, but not by all that much on a modern processor.
190
191 // Now, build up a report with everything pre-filled out.
192 flatbuffers::FlatBufferBuilder fbb;
193 fbb.ForceDefaults(1);
194
195 // Pre-fill in the defaults for timers.
196 std::vector<flatbuffers::Offset<timing::Timer>> timer_offsets;
197 for (const std::unique_ptr<TimerHandler> &timer : timers_) {
198 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
199 timing::CreateStatistic(fbb);
200 flatbuffers::Offset<timing::Statistic> handler_time_offset =
201 timing::CreateStatistic(fbb);
202 flatbuffers::Offset<flatbuffers::String> name_offset;
203 if (timer->name().size() != 0) {
204 name_offset = fbb.CreateString(timer->name());
205 }
206
207 timing::Timer::Builder timer_builder(fbb);
208
209 if (timer->name().size() != 0) {
210 timer_builder.add_name(name_offset);
211 }
212 timer_builder.add_wakeup_latency(wakeup_latency_offset);
213 timer_builder.add_handler_time(handler_time_offset);
214 timer_builder.add_count(0);
215 timer_offsets.emplace_back(timer_builder.Finish());
216 }
217
218 // Pre-fill in the defaults for phased_loops.
219 std::vector<flatbuffers::Offset<timing::Timer>> phased_loop_offsets;
220 for (const std::unique_ptr<PhasedLoopHandler> &phased_loop : phased_loops_) {
221 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
222 timing::CreateStatistic(fbb);
223 flatbuffers::Offset<timing::Statistic> handler_time_offset =
224 timing::CreateStatistic(fbb);
225 flatbuffers::Offset<flatbuffers::String> name_offset;
226 if (phased_loop->name().size() != 0) {
227 name_offset = fbb.CreateString(phased_loop->name());
228 }
229
230 timing::Timer::Builder timer_builder(fbb);
231
232 if (phased_loop->name().size() != 0) {
233 timer_builder.add_name(name_offset);
234 }
235 timer_builder.add_wakeup_latency(wakeup_latency_offset);
236 timer_builder.add_handler_time(handler_time_offset);
237 timer_builder.add_count(0);
238 phased_loop_offsets.emplace_back(timer_builder.Finish());
239 }
240
241 // Pre-fill in the defaults for watchers.
242 std::vector<flatbuffers::Offset<timing::Watcher>> watcher_offsets;
243 for (const std::unique_ptr<WatcherState> &watcher : watchers_) {
244 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
245 timing::CreateStatistic(fbb);
246 flatbuffers::Offset<timing::Statistic> handler_time_offset =
247 timing::CreateStatistic(fbb);
248
249 timing::Watcher::Builder watcher_builder(fbb);
250
251 watcher_builder.add_channel_index(watcher->channel_index());
252 watcher_builder.add_wakeup_latency(wakeup_latency_offset);
253 watcher_builder.add_handler_time(handler_time_offset);
254 watcher_builder.add_count(0);
255 watcher_offsets.emplace_back(watcher_builder.Finish());
256 }
257
258 // Pre-fill in the defaults for senders.
259 std::vector<flatbuffers::Offset<timing::Sender>> sender_offsets;
260 for (const RawSender *sender : senders_) {
261 flatbuffers::Offset<timing::Statistic> size_offset =
262 timing::CreateStatistic(fbb);
263
264 timing::Sender::Builder sender_builder(fbb);
265
266 sender_builder.add_channel_index(sender->timing_.channel_index);
267 sender_builder.add_size(size_offset);
268 sender_builder.add_count(0);
269 sender_offsets.emplace_back(sender_builder.Finish());
270 }
271
272 // Pre-fill in the defaults for fetchers.
273 std::vector<flatbuffers::Offset<timing::Fetcher>> fetcher_offsets;
274 for (RawFetcher *fetcher : fetchers_) {
275 flatbuffers::Offset<timing::Statistic> latency_offset =
276 timing::CreateStatistic(fbb);
277
278 timing::Fetcher::Builder fetcher_builder(fbb);
279
280 fetcher_builder.add_channel_index(fetcher->timing_.channel_index);
281 fetcher_builder.add_count(0);
282 fetcher_builder.add_latency(latency_offset);
283 fetcher_offsets.emplace_back(fetcher_builder.Finish());
284 }
285
286 // Then build the final report.
287 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Timer>>>
288 timers_offset;
289 if (timer_offsets.size() > 0) {
290 timers_offset = fbb.CreateVector(timer_offsets);
291 }
292
293 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Timer>>>
294 phased_loops_offset;
295 if (phased_loop_offsets.size() > 0) {
296 phased_loops_offset = fbb.CreateVector(phased_loop_offsets);
297 }
298
299 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Watcher>>>
300 watchers_offset;
301 if (watcher_offsets.size() > 0) {
302 watchers_offset = fbb.CreateVector(watcher_offsets);
303 }
304
305 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Sender>>>
306 senders_offset;
307 if (sender_offsets.size() > 0) {
308 senders_offset = fbb.CreateVector(sender_offsets);
309 }
310
311 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Fetcher>>>
312 fetchers_offset;
313 if (fetcher_offsets.size() > 0) {
314 fetchers_offset = fbb.CreateVector(fetcher_offsets);
315 }
316
317 flatbuffers::Offset<flatbuffers::String> name_offset =
318 fbb.CreateString(name());
319
320 timing::Report::Builder report_builder(fbb);
321 report_builder.add_name(name_offset);
322 report_builder.add_pid(GetTid());
323 if (timer_offsets.size() > 0) {
324 report_builder.add_timers(timers_offset);
325 }
326 if (phased_loop_offsets.size() > 0) {
327 report_builder.add_phased_loops(phased_loops_offset);
328 }
329 if (watcher_offsets.size() > 0) {
330 report_builder.add_watchers(watchers_offset);
331 }
332 if (sender_offsets.size() > 0) {
333 report_builder.add_senders(senders_offset);
334 }
335 if (fetcher_offsets.size() > 0) {
336 report_builder.add_fetchers(fetchers_offset);
337 }
338 fbb.Finish(report_builder.Finish());
339
340 timing_report_ = FlatbufferDetachedBuffer<timing::Report>(fbb.Release());
341
342 // Now that the pointers are stable, pass them to the timers and watchers to
343 // be updated.
344 for (size_t i = 0; i < timers_.size(); ++i) {
345 timers_[i]->timing_.set_timing_report(
346 timing_report_.mutable_message()->mutable_timers()->GetMutableObject(
347 i));
348 }
349
350 for (size_t i = 0; i < phased_loops_.size(); ++i) {
351 phased_loops_[i]->timing_.set_timing_report(
352 timing_report_.mutable_message()
353 ->mutable_phased_loops()
354 ->GetMutableObject(i));
355 }
356
357 for (size_t i = 0; i < watchers_.size(); ++i) {
358 watchers_[i]->set_timing_report(
359 timing_report_.mutable_message()->mutable_watchers()->GetMutableObject(
360 i));
361 }
362
363 for (size_t i = 0; i < senders_.size(); ++i) {
364 senders_[i]->timing_.set_timing_report(
365 timing_report_.mutable_message()->mutable_senders()->GetMutableObject(
366 i));
367 }
368
369 for (size_t i = 0; i < fetchers_.size(); ++i) {
370 fetchers_[i]->timing_.set_timing_report(
371 timing_report_.mutable_message()->mutable_fetchers()->GetMutableObject(
372 i));
373 }
374}
375
376void EventLoop::MaybeScheduleTimingReports() {
377 if (FLAGS_timing_reports && !skip_timing_report_) {
378 CHECK(!timing_report_sender_) << ": Timing reports already scheduled.";
379 // Make a raw sender for the report.
380 const Channel *channel = configuration::GetChannel(
381 configuration(), "/aos", timing::Report::GetFullyQualifiedName(),
Austin Schuhbca6cf02019-12-22 17:28:34 -0800382 name(), node());
383
384 // Since we are using a RawSender, validity isn't checked. So check it
385 // ourselves.
Austin Schuhca4828c2019-12-28 14:21:35 -0800386 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
387 LOG(FATAL) << "Channel { \"name\": \"/aos"
388 << channel->name()->string_view() << "\", \"type\": \""
389 << channel->type()->string_view()
390 << "\" } is not able to be sent on this node. Check your "
391 "configuration.";
Austin Schuhbca6cf02019-12-22 17:28:34 -0800392 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800393 CHECK(channel != nullptr) << ": Channel { \"name\": \"/aos\", \"type\": \""
394 << timing::Report::GetFullyQualifiedName()
395 << "\" } not found in config.";
396 timing_report_sender_ = MakeRawSender(channel);
397
398 // Register a handler which sends the report out by copying the raw data
399 // from the prebuilt and subsequently modified report.
400 TimerHandler *timing_reports_timer =
401 AddTimer([this]() { SendTimingReport(); });
402
403 // Set it up to send once per second.
404 timing_reports_timer->set_name("timing_reports");
405 OnRun([this, timing_reports_timer]() {
406 timing_reports_timer->Setup(
407 monotonic_now() + std::chrono::milliseconds(FLAGS_timing_report_ms),
408 std::chrono::milliseconds(FLAGS_timing_report_ms));
409 });
410
411 UpdateTimingReport();
412 }
413}
414
Austin Schuh7d87b672019-12-01 20:23:49 -0800415void EventLoop::ReserveEvents() {
416 events_.reserve(timers_.size() + phased_loops_.size() + watchers_.size());
417}
418
419namespace {
420bool CompareEvents(const EventLoopEvent *first, const EventLoopEvent *second) {
421 return first->event_time() > second->event_time();
422}
423} // namespace
424
425void EventLoop::AddEvent(EventLoopEvent *event) {
426 DCHECK(std::find(events_.begin(), events_.end(), event) == events_.end());
427 events_.push_back(event);
428 std::push_heap(events_.begin(), events_.end(), CompareEvents);
429}
430
431void EventLoop::RemoveEvent(EventLoopEvent *event) {
432 auto e = std::find(events_.begin(), events_.end(), event);
433 if (e != events_.end()) {
434 events_.erase(e);
435 std::make_heap(events_.begin(), events_.end(), CompareEvents);
436 event->Invalidate();
437 }
438}
439
440EventLoopEvent *EventLoop::PopEvent() {
441 EventLoopEvent *result = events_.front();
442 std::pop_heap(events_.begin(), events_.end(), CompareEvents);
443 events_.pop_back();
444 result->Invalidate();
445 return result;
446}
447
Austin Schuh39788ff2019-12-01 18:22:57 -0800448void WatcherState::set_timing_report(timing::Watcher *watcher) {
449 CHECK_NOTNULL(watcher);
450 watcher_ = watcher;
451 wakeup_latency_.set_statistic(watcher->mutable_wakeup_latency());
452 handler_time_.set_statistic(watcher->mutable_handler_time());
453}
454
455void WatcherState::ResetReport() {
456 wakeup_latency_.Reset();
457 handler_time_.Reset();
458 watcher_->mutate_count(0);
Austin Schuh54cf95f2019-11-29 13:14:18 -0800459}
460
461} // namespace aos