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