blob: 1a0249547644f1a0a7279119f9f9de60716238aa [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_LOOP_TMPL_H_
2#define AOS_EVENTS_EVENT_LOOP_TMPL_H_
3
Tyler Chatowbf0609c2021-07-31 16:13:27 -07004#include <cinttypes>
5#include <cstdint>
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <type_traits>
Brian Silverman79ec7fc2020-06-08 20:11:22 -05007
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include "aos/events/event_loop.h"
9#include "glog/logging.h"
10
11namespace aos {
Brian Silverman454bc112020-03-05 14:21:25 -080012namespace event_loop_internal {
Alex Perrycb7da4b2019-08-28 19:35:56 -070013
Brian Silverman454bc112020-03-05 14:21:25 -080014// From a watch functor, specializations of this will extract the message type
15// of the template argument. If T is not a valid message type, there will be no
16// matching specialization.
17//
18// This is just the forward declaration, which will be used by one of the
19// following specializations to match valid argument types.
Alex Perrycb7da4b2019-08-28 19:35:56 -070020template <class T>
Brian Silverman454bc112020-03-05 14:21:25 -080021struct watch_message_type_trait;
Alex Perrycb7da4b2019-08-28 19:35:56 -070022
23// From a watch functor, this will extract the message type of the argument.
24// This is the template specialization.
25template <class ClassType, class ReturnType, class A1>
26struct watch_message_type_trait<ReturnType (ClassType::*)(A1) const> {
27 using message_type = typename std::decay<A1>::type;
28};
29
Brian Silverman454bc112020-03-05 14:21:25 -080030} // namespace event_loop_internal
31
Alex Perrycb7da4b2019-08-28 19:35:56 -070032template <typename T>
33typename Sender<T>::Builder Sender<T>::MakeBuilder() {
Brian Silvermana1652f32020-01-29 20:41:44 -080034 return Builder(sender_.get(), sender_->fbb_allocator());
Alex Perrycb7da4b2019-08-28 19:35:56 -070035}
36
37template <typename Watch>
James Kuszmaul3ae42262019-11-08 12:33:41 -080038void EventLoop::MakeWatcher(const std::string_view channel_name, Watch &&w) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070039 using MessageType =
40 typename event_loop_internal::watch_message_type_trait<decltype(
41 &Watch::operator())>::message_type;
Alex Perrycb7da4b2019-08-28 19:35:56 -070042 const Channel *channel = configuration::GetChannel(
Brian Silverman454bc112020-03-05 14:21:25 -080043 configuration_, channel_name, MessageType::GetFullyQualifiedName(),
44 name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -070045
46 CHECK(channel != nullptr)
47 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuhc59a1de2021-02-20 14:47:39 -080048 << MessageType::GetFullyQualifiedName()
49 << "\" } not found in config for application " << name() << ".";
Alex Perrycb7da4b2019-08-28 19:35:56 -070050
Brian Silverman454bc112020-03-05 14:21:25 -080051 MakeRawWatcher(channel,
52 [this, w](const Context &context, const void *message) {
53 context_ = context;
54 w(*flatbuffers::GetRoot<MessageType>(
55 reinterpret_cast<const char *>(message)));
56 });
57}
58
59template <typename MessageType>
60void EventLoop::MakeNoArgWatcher(const std::string_view channel_name,
61 std::function<void()> w) {
62 const Channel *channel = configuration::GetChannel(
63 configuration_, channel_name, MessageType::GetFullyQualifiedName(),
64 name(), node());
65 CHECK(channel != nullptr)
66 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuhc59a1de2021-02-20 14:47:39 -080067 << MessageType::GetFullyQualifiedName()
68 << "\" } not found in config for application " << name() << ".";
Brian Silverman454bc112020-03-05 14:21:25 -080069 MakeRawNoArgWatcher(channel, [this, w](const Context &context) {
70 context_ = context;
71 w();
72 });
Alex Perrycb7da4b2019-08-28 19:35:56 -070073}
74
Austin Schuh39788ff2019-12-01 18:22:57 -080075inline bool RawFetcher::FetchNext() {
76 const auto result = DoFetchNext();
77 if (result.first) {
Brian Silvermanbf889922021-11-10 12:41:57 -080078 if (timing_.fetcher) {
79 timing_.fetcher->mutate_count(timing_.fetcher->count() + 1);
80 }
Austin Schuh39788ff2019-12-01 18:22:57 -080081 const monotonic_clock::time_point monotonic_time = result.second;
Brian Silverman79ec7fc2020-06-08 20:11:22 -050082 ftrace_.FormatMessage(
83 "%.*s: fetch next: now=%" PRId64 " event=%" PRId64 " queue=%" PRIu32,
84 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
85 static_cast<int64_t>(monotonic_time.time_since_epoch().count()),
86 static_cast<int64_t>(
87 context_.monotonic_event_time.time_since_epoch().count()),
88 context_.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -080089 const float latency =
90 std::chrono::duration_cast<std::chrono::duration<float>>(
Austin Schuhad154822019-12-27 15:45:13 -080091 monotonic_time - context_.monotonic_event_time)
Austin Schuh39788ff2019-12-01 18:22:57 -080092 .count();
93 timing_.latency.Add(latency);
94 return true;
95 }
Brian Silverman79ec7fc2020-06-08 20:11:22 -050096 ftrace_.FormatMessage(
97 "%.*s: fetch next: still event=%" PRId64 " queue=%" PRIu32,
98 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
99 static_cast<int64_t>(
100 context_.monotonic_event_time.time_since_epoch().count()),
101 context_.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 return false;
103}
104
105inline bool RawFetcher::Fetch() {
106 const auto result = DoFetch();
107 if (result.first) {
Brian Silvermanbf889922021-11-10 12:41:57 -0800108 if (timing_.fetcher) {
109 timing_.fetcher->mutate_count(timing_.fetcher->count() + 1);
110 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800111 const monotonic_clock::time_point monotonic_time = result.second;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500112 ftrace_.FormatMessage(
113 "%.*s: fetch latest: now=%" PRId64 " event=%" PRId64 " queue=%" PRIu32,
114 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
115 static_cast<int64_t>(monotonic_time.time_since_epoch().count()),
116 static_cast<int64_t>(
117 context_.monotonic_event_time.time_since_epoch().count()),
118 context_.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -0800119 const float latency =
120 std::chrono::duration_cast<std::chrono::duration<float>>(
Austin Schuhad154822019-12-27 15:45:13 -0800121 monotonic_time - context_.monotonic_event_time)
Austin Schuh39788ff2019-12-01 18:22:57 -0800122 .count();
123 timing_.latency.Add(latency);
124 return true;
125 }
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500126 ftrace_.FormatMessage(
127 "%.*s: fetch latest: still event=%" PRId64 " queue=%" PRIu32,
128 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
129 static_cast<int64_t>(
130 context_.monotonic_event_time.time_since_epoch().count()),
131 context_.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -0800132 return false;
133}
134
Austin Schuhb5c6f972021-03-14 21:53:07 -0700135inline bool RawSender::Send(size_t size) {
136 return Send(size, monotonic_clock::min_time, realtime_clock::min_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700137 0xffffffffu, event_loop_->boot_uuid());
Austin Schuhb5c6f972021-03-14 21:53:07 -0700138}
139
Austin Schuhad154822019-12-27 15:45:13 -0800140inline bool RawSender::Send(
141 size_t size, aos::monotonic_clock::time_point monotonic_remote_time,
142 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700143 uint32_t remote_queue_index, const UUID &uuid) {
Austin Schuhad154822019-12-27 15:45:13 -0800144 if (DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700145 remote_queue_index, uuid)) {
Brian Silvermanbf889922021-11-10 12:41:57 -0800146 if (timing_.sender) {
147 timing_.size.Add(size);
148 timing_.sender->mutate_count(timing_.sender->count() + 1);
149 }
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500150 ftrace_.FormatMessage(
151 "%.*s: sent internal: event=%" PRId64 " queue=%" PRIu32,
152 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
153 static_cast<int64_t>(monotonic_sent_time().time_since_epoch().count()),
154 sent_queue_index());
Austin Schuh39788ff2019-12-01 18:22:57 -0800155 return true;
156 }
157 return false;
158}
159
Austin Schuhb5c6f972021-03-14 21:53:07 -0700160inline bool RawSender::Send(const void *data, size_t size) {
161 return Send(data, size, monotonic_clock::min_time, realtime_clock::min_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700162 0xffffffffu, event_loop_->boot_uuid());
Austin Schuhb5c6f972021-03-14 21:53:07 -0700163}
164
Austin Schuhad154822019-12-27 15:45:13 -0800165inline bool RawSender::Send(
166 const void *data, size_t size,
167 aos::monotonic_clock::time_point monotonic_remote_time,
168 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700169 uint32_t remote_queue_index, const UUID &uuid) {
Austin Schuhad154822019-12-27 15:45:13 -0800170 if (DoSend(data, size, monotonic_remote_time, realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700171 remote_queue_index, uuid)) {
Brian Silvermanbf889922021-11-10 12:41:57 -0800172 if (timing_.sender) {
173 timing_.size.Add(size);
174 timing_.sender->mutate_count(timing_.sender->count() + 1);
175 }
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500176 ftrace_.FormatMessage(
177 "%.*s: sent external: event=%" PRId64 " queue=%" PRIu32,
178 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
179 static_cast<int64_t>(monotonic_sent_time().time_since_epoch().count()),
180 sent_queue_index());
Austin Schuh39788ff2019-12-01 18:22:57 -0800181 return true;
182 }
183 return false;
184}
185
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700186inline bool RawSender::Send(const SharedSpan data) {
187 return Send(std::move(data), monotonic_clock::min_time,
188 realtime_clock::min_time, 0xffffffffu, event_loop_->boot_uuid());
189}
190
191inline bool RawSender::Send(
192 const SharedSpan data,
193 aos::monotonic_clock::time_point monotonic_remote_time,
194 aos::realtime_clock::time_point realtime_remote_time,
195 uint32_t remote_queue_index, const UUID &uuid) {
196 const size_t size = data->size();
197 if (DoSend(std::move(data), monotonic_remote_time, realtime_remote_time,
198 remote_queue_index, uuid)) {
Brian Silvermanbf889922021-11-10 12:41:57 -0800199 if (timing_.sender) {
200 timing_.size.Add(size);
201 timing_.sender->mutate_count(timing_.sender->count() + 1);
202 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700203 ftrace_.FormatMessage(
204 "%.*s: sent shared: event=%" PRId64 " queue=%" PRIu32,
205 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
206 static_cast<int64_t>(monotonic_sent_time().time_since_epoch().count()),
207 sent_queue_index());
208 return true;
209 }
210 return false;
211}
212
Austin Schuhcde39fd2020-02-22 20:58:24 -0800213inline monotonic_clock::time_point TimerHandler::Call(
Austin Schuh39788ff2019-12-01 18:22:57 -0800214 std::function<monotonic_clock::time_point()> get_time,
215 monotonic_clock::time_point event_time) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 const monotonic_clock::time_point monotonic_start_time = get_time();
217
Austin Schuha9012be2021-07-21 15:19:11 -0700218 event_loop_->SetTimerContext(event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800219
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500220 ftrace_.FormatMessage(
221 "timer: %.*s: start now=%" PRId64 " event=%" PRId64,
222 static_cast<int>(name_.size()), name_.data(),
223 static_cast<int64_t>(monotonic_start_time.time_since_epoch().count()),
224 static_cast<int64_t>(event_time.time_since_epoch().count()));
Brian Silvermanbf889922021-11-10 12:41:57 -0800225 if (timing_.timer) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800226 const float start_latency =
227 std::chrono::duration_cast<std::chrono::duration<float>>(
228 monotonic_start_time - event_time)
229 .count();
230 timing_.wakeup_latency.Add(start_latency);
Brian Silvermanbf889922021-11-10 12:41:57 -0800231 timing_.timer->mutate_count(timing_.timer->count() + 1);
Austin Schuh39788ff2019-12-01 18:22:57 -0800232 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800233 fn_();
234
235 const monotonic_clock::time_point monotonic_end_time = get_time();
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500236 ftrace_.FormatMessage(
237 "timer: %.*s: end now=%" PRId64, static_cast<int>(name_.size()),
238 name_.data(),
239 static_cast<int64_t>(monotonic_end_time.time_since_epoch().count()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800240
241 const float handler_latency =
242 std::chrono::duration_cast<std::chrono::duration<float>>(
243 monotonic_end_time - monotonic_start_time)
244 .count();
245 timing_.handler_time.Add(handler_latency);
Austin Schuhcde39fd2020-02-22 20:58:24 -0800246 return monotonic_start_time;
Austin Schuh39788ff2019-12-01 18:22:57 -0800247}
248
249inline void PhasedLoopHandler::Call(
250 std::function<monotonic_clock::time_point()> get_time,
251 std::function<void(monotonic_clock::time_point)> schedule) {
252 // Read time directly to save a vtable indirection...
253 const monotonic_clock::time_point monotonic_start_time = get_time();
254
255 // Update the context to hold the desired wakeup time.
Austin Schuha9012be2021-07-21 15:19:11 -0700256 event_loop_->SetTimerContext(phased_loop_.sleep_time());
Austin Schuh39788ff2019-12-01 18:22:57 -0800257
Milind Upadhyay42589bb2021-05-19 20:05:16 -0700258 // Compute how many cycles elapsed
259 cycles_elapsed_ += phased_loop_.Iterate(monotonic_start_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800260
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500261 ftrace_.FormatMessage(
262 "phased: %.*s: start now=%" PRId64 " event=%" PRId64 " cycles=%d",
263 static_cast<int>(name_.size()), name_.data(),
264 static_cast<int64_t>(monotonic_start_time.time_since_epoch().count()),
265 static_cast<int64_t>(
266 phased_loop_.sleep_time().time_since_epoch().count()),
267 cycles_elapsed_);
Brian Silvermanbf889922021-11-10 12:41:57 -0800268 if (timing_.timer) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800269 const float start_latency =
270 std::chrono::duration_cast<std::chrono::duration<float>>(
Austin Schuhad154822019-12-27 15:45:13 -0800271 monotonic_start_time - event_loop_->context_.monotonic_event_time)
Austin Schuh39788ff2019-12-01 18:22:57 -0800272 .count();
273 timing_.wakeup_latency.Add(start_latency);
Brian Silvermanbf889922021-11-10 12:41:57 -0800274 timing_.timer->mutate_count(timing_.timer->count() + 1);
Austin Schuh39788ff2019-12-01 18:22:57 -0800275 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800276
277 // Call the function with the elapsed cycles.
278 fn_(cycles_elapsed_);
279 cycles_elapsed_ = 0;
280
Milind Upadhyay42589bb2021-05-19 20:05:16 -0700281 // Schedule the next wakeup.
282 schedule(phased_loop_.sleep_time());
283
Austin Schuh39788ff2019-12-01 18:22:57 -0800284 const monotonic_clock::time_point monotonic_end_time = get_time();
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500285 ftrace_.FormatMessage(
286 "phased: %.*s: end now=%" PRId64, static_cast<int>(name_.size()),
287 name_.data(),
288 static_cast<int64_t>(monotonic_end_time.time_since_epoch().count()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800289
290 const float handler_latency =
291 std::chrono::duration_cast<std::chrono::duration<float>>(
292 monotonic_end_time - monotonic_start_time)
293 .count();
294 timing_.handler_time.Add(handler_latency);
295
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700296 // If the handler took too long so we blew by the previous deadline, we
Austin Schuh91ba6392020-10-03 13:27:47 -0700297 // want to just try for the next deadline. Reschedule.
Austin Schuh39788ff2019-12-01 18:22:57 -0800298 if (monotonic_end_time > phased_loop_.sleep_time()) {
299 Reschedule(schedule, monotonic_end_time);
300 }
301}
302
303// Class to automate the timing report generation for watchers.
304class WatcherState {
305 public:
306 WatcherState(
307 EventLoop *event_loop, const Channel *channel,
308 std::function<void(const Context &context, const void *message)> fn)
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500309 : channel_index_(event_loop->ChannelIndex(channel)),
310 ftrace_prefix_(configuration::StrippedChannelToString(channel)),
311 fn_(std::move(fn)) {}
Austin Schuh39788ff2019-12-01 18:22:57 -0800312
313 virtual ~WatcherState() {}
314
315 // Calls the callback, measuring time with get_time, with the provided
316 // context.
317 void DoCallCallback(std::function<monotonic_clock::time_point()> get_time,
Austin Schuhc5dc98f2021-06-16 14:52:46 -0700318 Context context) noexcept {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800319 if (context.data) {
320 CheckChannelDataAlignment(context.data, context.size);
321 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800322 const monotonic_clock::time_point monotonic_start_time = get_time();
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500323 ftrace_.FormatMessage(
324 "%.*s: watcher start: now=%" PRId64 " event=%" PRId64 " queue=%" PRIu32,
325 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
326 static_cast<int64_t>(monotonic_start_time.time_since_epoch().count()),
327 static_cast<int64_t>(
328 context.monotonic_event_time.time_since_epoch().count()),
329 context.queue_index);
Brian Silvermanbf889922021-11-10 12:41:57 -0800330 if (watcher_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800331 const float start_latency =
332 std::chrono::duration_cast<std::chrono::duration<float>>(
Austin Schuhad154822019-12-27 15:45:13 -0800333 monotonic_start_time - context.monotonic_event_time)
Austin Schuh39788ff2019-12-01 18:22:57 -0800334 .count();
335 wakeup_latency_.Add(start_latency);
Brian Silvermanbf889922021-11-10 12:41:57 -0800336 watcher_->mutate_count(watcher_->count() + 1);
Austin Schuh39788ff2019-12-01 18:22:57 -0800337 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800338 fn_(context, context.data);
339
340 const monotonic_clock::time_point monotonic_end_time = get_time();
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500341 ftrace_.FormatMessage(
342 "%.*s: watcher end: now=%" PRId64,
343 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
344 static_cast<int64_t>(monotonic_end_time.time_since_epoch().count()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800345
346 const float handler_latency =
347 std::chrono::duration_cast<std::chrono::duration<float>>(
348 monotonic_end_time - monotonic_start_time)
349 .count();
350 handler_time_.Add(handler_latency);
351 }
352
353 int channel_index() const { return channel_index_; }
354
355 void set_timing_report(timing::Watcher *watcher);
356 void ResetReport();
357
358 virtual void Startup(EventLoop *event_loop) = 0;
359
360 protected:
361 const int channel_index_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500362 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800363
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500364 const std::function<void(const Context &context, const void *message)> fn_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800365
366 internal::TimingStatistic wakeup_latency_;
367 internal::TimingStatistic handler_time_;
368 timing::Watcher *watcher_ = nullptr;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500369
370 Ftrace ftrace_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800371};
372
Austin Schuha28cbc32019-12-27 16:28:04 -0800373template <typename T>
Austin Schuhadd6eb32020-11-09 21:24:26 -0800374bool Sender<T>::Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer) {
375 return sender_->Send(flatbuffer.span().data(), flatbuffer.span().size());
Austin Schuha28cbc32019-12-27 16:28:04 -0800376}
377
Brian Silverman341b57e2020-06-23 16:23:18 -0700378template <typename T>
379bool Sender<T>::SendDetached(FlatbufferDetachedBuffer<T> detached) {
Austin Schuhadd6eb32020-11-09 21:24:26 -0800380 CHECK_EQ(static_cast<void *>(detached.span().data() + detached.span().size() -
381 sender_->size()),
382 sender_->data())
Brian Silverman341b57e2020-06-23 16:23:18 -0700383 << ": May only send the buffer detached from this Sender";
Austin Schuhadd6eb32020-11-09 21:24:26 -0800384 return sender_->Send(detached.span().size());
Brian Silverman341b57e2020-06-23 16:23:18 -0700385}
386
Alex Perrycb7da4b2019-08-28 19:35:56 -0700387} // namespace aos
388
389#endif // AOS_EVENTS_EVENT_LOOP_TMPL_H