blob: 7e560fe8cfa63b070075c461efe31772bf6edfb1 [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) {
78 timing_.fetcher->mutate_count(timing_.fetcher->count() + 1);
79 const monotonic_clock::time_point monotonic_time = result.second;
Brian Silverman79ec7fc2020-06-08 20:11:22 -050080 ftrace_.FormatMessage(
81 "%.*s: fetch next: now=%" PRId64 " event=%" PRId64 " queue=%" PRIu32,
82 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
83 static_cast<int64_t>(monotonic_time.time_since_epoch().count()),
84 static_cast<int64_t>(
85 context_.monotonic_event_time.time_since_epoch().count()),
86 context_.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -080087 const float latency =
88 std::chrono::duration_cast<std::chrono::duration<float>>(
Austin Schuhad154822019-12-27 15:45:13 -080089 monotonic_time - context_.monotonic_event_time)
Austin Schuh39788ff2019-12-01 18:22:57 -080090 .count();
91 timing_.latency.Add(latency);
92 return true;
93 }
Brian Silverman79ec7fc2020-06-08 20:11:22 -050094 ftrace_.FormatMessage(
95 "%.*s: fetch next: still event=%" PRId64 " queue=%" PRIu32,
96 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
97 static_cast<int64_t>(
98 context_.monotonic_event_time.time_since_epoch().count()),
99 context_.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -0800100 return false;
101}
102
103inline bool RawFetcher::Fetch() {
104 const auto result = DoFetch();
105 if (result.first) {
106 timing_.fetcher->mutate_count(timing_.fetcher->count() + 1);
107 const monotonic_clock::time_point monotonic_time = result.second;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500108 ftrace_.FormatMessage(
109 "%.*s: fetch latest: now=%" PRId64 " event=%" PRId64 " queue=%" PRIu32,
110 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
111 static_cast<int64_t>(monotonic_time.time_since_epoch().count()),
112 static_cast<int64_t>(
113 context_.monotonic_event_time.time_since_epoch().count()),
114 context_.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -0800115 const float latency =
116 std::chrono::duration_cast<std::chrono::duration<float>>(
Austin Schuhad154822019-12-27 15:45:13 -0800117 monotonic_time - context_.monotonic_event_time)
Austin Schuh39788ff2019-12-01 18:22:57 -0800118 .count();
119 timing_.latency.Add(latency);
120 return true;
121 }
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500122 ftrace_.FormatMessage(
123 "%.*s: fetch latest: still event=%" PRId64 " queue=%" PRIu32,
124 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
125 static_cast<int64_t>(
126 context_.monotonic_event_time.time_since_epoch().count()),
127 context_.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -0800128 return false;
129}
130
Austin Schuhb5c6f972021-03-14 21:53:07 -0700131inline bool RawSender::Send(size_t size) {
132 return Send(size, monotonic_clock::min_time, realtime_clock::min_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700133 0xffffffffu, event_loop_->boot_uuid());
Austin Schuhb5c6f972021-03-14 21:53:07 -0700134}
135
Austin Schuhad154822019-12-27 15:45:13 -0800136inline bool RawSender::Send(
137 size_t size, aos::monotonic_clock::time_point monotonic_remote_time,
138 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700139 uint32_t remote_queue_index, const UUID &uuid) {
Austin Schuhad154822019-12-27 15:45:13 -0800140 if (DoSend(size, monotonic_remote_time, realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700141 remote_queue_index, uuid)) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800142 timing_.size.Add(size);
143 timing_.sender->mutate_count(timing_.sender->count() + 1);
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500144 ftrace_.FormatMessage(
145 "%.*s: sent internal: event=%" PRId64 " queue=%" PRIu32,
146 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
147 static_cast<int64_t>(monotonic_sent_time().time_since_epoch().count()),
148 sent_queue_index());
Austin Schuh39788ff2019-12-01 18:22:57 -0800149 return true;
150 }
151 return false;
152}
153
Austin Schuhb5c6f972021-03-14 21:53:07 -0700154inline bool RawSender::Send(const void *data, size_t size) {
155 return Send(data, size, monotonic_clock::min_time, realtime_clock::min_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700156 0xffffffffu, event_loop_->boot_uuid());
Austin Schuhb5c6f972021-03-14 21:53:07 -0700157}
158
Austin Schuhad154822019-12-27 15:45:13 -0800159inline bool RawSender::Send(
160 const void *data, size_t size,
161 aos::monotonic_clock::time_point monotonic_remote_time,
162 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700163 uint32_t remote_queue_index, const UUID &uuid) {
Austin Schuhad154822019-12-27 15:45:13 -0800164 if (DoSend(data, size, monotonic_remote_time, realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700165 remote_queue_index, uuid)) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800166 timing_.size.Add(size);
167 timing_.sender->mutate_count(timing_.sender->count() + 1);
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500168 ftrace_.FormatMessage(
169 "%.*s: sent external: event=%" PRId64 " queue=%" PRIu32,
170 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
171 static_cast<int64_t>(monotonic_sent_time().time_since_epoch().count()),
172 sent_queue_index());
Austin Schuh39788ff2019-12-01 18:22:57 -0800173 return true;
174 }
175 return false;
176}
177
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700178inline bool RawSender::Send(const SharedSpan data) {
179 return Send(std::move(data), monotonic_clock::min_time,
180 realtime_clock::min_time, 0xffffffffu, event_loop_->boot_uuid());
181}
182
183inline bool RawSender::Send(
184 const SharedSpan data,
185 aos::monotonic_clock::time_point monotonic_remote_time,
186 aos::realtime_clock::time_point realtime_remote_time,
187 uint32_t remote_queue_index, const UUID &uuid) {
188 const size_t size = data->size();
189 if (DoSend(std::move(data), monotonic_remote_time, realtime_remote_time,
190 remote_queue_index, uuid)) {
191 timing_.size.Add(size);
192 timing_.sender->mutate_count(timing_.sender->count() + 1);
193 ftrace_.FormatMessage(
194 "%.*s: sent shared: event=%" PRId64 " queue=%" PRIu32,
195 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
196 static_cast<int64_t>(monotonic_sent_time().time_since_epoch().count()),
197 sent_queue_index());
198 return true;
199 }
200 return false;
201}
202
Austin Schuhcde39fd2020-02-22 20:58:24 -0800203inline monotonic_clock::time_point TimerHandler::Call(
Austin Schuh39788ff2019-12-01 18:22:57 -0800204 std::function<monotonic_clock::time_point()> get_time,
205 monotonic_clock::time_point event_time) {
206 CHECK_NOTNULL(timing_.timer);
207 const monotonic_clock::time_point monotonic_start_time = get_time();
208
Austin Schuha9012be2021-07-21 15:19:11 -0700209 event_loop_->SetTimerContext(event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800210
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500211 ftrace_.FormatMessage(
212 "timer: %.*s: start now=%" PRId64 " event=%" PRId64,
213 static_cast<int>(name_.size()), name_.data(),
214 static_cast<int64_t>(monotonic_start_time.time_since_epoch().count()),
215 static_cast<int64_t>(event_time.time_since_epoch().count()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 {
217 const float start_latency =
218 std::chrono::duration_cast<std::chrono::duration<float>>(
219 monotonic_start_time - event_time)
220 .count();
221 timing_.wakeup_latency.Add(start_latency);
222 }
223 timing_.timer->mutate_count(timing_.timer->count() + 1);
224 fn_();
225
226 const monotonic_clock::time_point monotonic_end_time = get_time();
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500227 ftrace_.FormatMessage(
228 "timer: %.*s: end now=%" PRId64, static_cast<int>(name_.size()),
229 name_.data(),
230 static_cast<int64_t>(monotonic_end_time.time_since_epoch().count()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800231
232 const float handler_latency =
233 std::chrono::duration_cast<std::chrono::duration<float>>(
234 monotonic_end_time - monotonic_start_time)
235 .count();
236 timing_.handler_time.Add(handler_latency);
Austin Schuhcde39fd2020-02-22 20:58:24 -0800237 return monotonic_start_time;
Austin Schuh39788ff2019-12-01 18:22:57 -0800238}
239
240inline void PhasedLoopHandler::Call(
241 std::function<monotonic_clock::time_point()> get_time,
242 std::function<void(monotonic_clock::time_point)> schedule) {
243 // Read time directly to save a vtable indirection...
244 const monotonic_clock::time_point monotonic_start_time = get_time();
245
246 // Update the context to hold the desired wakeup time.
Austin Schuha9012be2021-07-21 15:19:11 -0700247 event_loop_->SetTimerContext(phased_loop_.sleep_time());
Austin Schuh39788ff2019-12-01 18:22:57 -0800248
Milind Upadhyay42589bb2021-05-19 20:05:16 -0700249 // Compute how many cycles elapsed
250 cycles_elapsed_ += phased_loop_.Iterate(monotonic_start_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800251
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500252 ftrace_.FormatMessage(
253 "phased: %.*s: start now=%" PRId64 " event=%" PRId64 " cycles=%d",
254 static_cast<int>(name_.size()), name_.data(),
255 static_cast<int64_t>(monotonic_start_time.time_since_epoch().count()),
256 static_cast<int64_t>(
257 phased_loop_.sleep_time().time_since_epoch().count()),
258 cycles_elapsed_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800259 {
260 const float start_latency =
261 std::chrono::duration_cast<std::chrono::duration<float>>(
Austin Schuhad154822019-12-27 15:45:13 -0800262 monotonic_start_time - event_loop_->context_.monotonic_event_time)
Austin Schuh39788ff2019-12-01 18:22:57 -0800263 .count();
264 timing_.wakeup_latency.Add(start_latency);
265 }
266 timing_.timer->mutate_count(timing_.timer->count() + 1);
267
268 // Call the function with the elapsed cycles.
269 fn_(cycles_elapsed_);
270 cycles_elapsed_ = 0;
271
Milind Upadhyay42589bb2021-05-19 20:05:16 -0700272 // Schedule the next wakeup.
273 schedule(phased_loop_.sleep_time());
274
Austin Schuh39788ff2019-12-01 18:22:57 -0800275 const monotonic_clock::time_point monotonic_end_time = get_time();
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500276 ftrace_.FormatMessage(
277 "phased: %.*s: end now=%" PRId64, static_cast<int>(name_.size()),
278 name_.data(),
279 static_cast<int64_t>(monotonic_end_time.time_since_epoch().count()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800280
281 const float handler_latency =
282 std::chrono::duration_cast<std::chrono::duration<float>>(
283 monotonic_end_time - monotonic_start_time)
284 .count();
285 timing_.handler_time.Add(handler_latency);
286
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700287 // If the handler took too long so we blew by the previous deadline, we
Austin Schuh91ba6392020-10-03 13:27:47 -0700288 // want to just try for the next deadline. Reschedule.
Austin Schuh39788ff2019-12-01 18:22:57 -0800289 if (monotonic_end_time > phased_loop_.sleep_time()) {
290 Reschedule(schedule, monotonic_end_time);
291 }
292}
293
294// Class to automate the timing report generation for watchers.
295class WatcherState {
296 public:
297 WatcherState(
298 EventLoop *event_loop, const Channel *channel,
299 std::function<void(const Context &context, const void *message)> fn)
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500300 : channel_index_(event_loop->ChannelIndex(channel)),
301 ftrace_prefix_(configuration::StrippedChannelToString(channel)),
302 fn_(std::move(fn)) {}
Austin Schuh39788ff2019-12-01 18:22:57 -0800303
304 virtual ~WatcherState() {}
305
306 // Calls the callback, measuring time with get_time, with the provided
307 // context.
308 void DoCallCallback(std::function<monotonic_clock::time_point()> get_time,
Austin Schuhc5dc98f2021-06-16 14:52:46 -0700309 Context context) noexcept {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800310 if (context.data) {
311 CheckChannelDataAlignment(context.data, context.size);
312 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800313 const monotonic_clock::time_point monotonic_start_time = get_time();
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500314 ftrace_.FormatMessage(
315 "%.*s: watcher start: now=%" PRId64 " event=%" PRId64 " queue=%" PRIu32,
316 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
317 static_cast<int64_t>(monotonic_start_time.time_since_epoch().count()),
318 static_cast<int64_t>(
319 context.monotonic_event_time.time_since_epoch().count()),
320 context.queue_index);
Austin Schuh39788ff2019-12-01 18:22:57 -0800321 {
322 const float start_latency =
323 std::chrono::duration_cast<std::chrono::duration<float>>(
Austin Schuhad154822019-12-27 15:45:13 -0800324 monotonic_start_time - context.monotonic_event_time)
Austin Schuh39788ff2019-12-01 18:22:57 -0800325 .count();
326 wakeup_latency_.Add(start_latency);
327 }
328 watcher_->mutate_count(watcher_->count() + 1);
329 fn_(context, context.data);
330
331 const monotonic_clock::time_point monotonic_end_time = get_time();
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500332 ftrace_.FormatMessage(
333 "%.*s: watcher end: now=%" PRId64,
334 static_cast<int>(ftrace_prefix_.size()), ftrace_prefix_.data(),
335 static_cast<int64_t>(monotonic_end_time.time_since_epoch().count()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800336
337 const float handler_latency =
338 std::chrono::duration_cast<std::chrono::duration<float>>(
339 monotonic_end_time - monotonic_start_time)
340 .count();
341 handler_time_.Add(handler_latency);
342 }
343
344 int channel_index() const { return channel_index_; }
345
346 void set_timing_report(timing::Watcher *watcher);
347 void ResetReport();
348
349 virtual void Startup(EventLoop *event_loop) = 0;
350
351 protected:
352 const int channel_index_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500353 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800354
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500355 const std::function<void(const Context &context, const void *message)> fn_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800356
357 internal::TimingStatistic wakeup_latency_;
358 internal::TimingStatistic handler_time_;
359 timing::Watcher *watcher_ = nullptr;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500360
361 Ftrace ftrace_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800362};
363
Austin Schuha28cbc32019-12-27 16:28:04 -0800364template <typename T>
Austin Schuhadd6eb32020-11-09 21:24:26 -0800365bool Sender<T>::Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer) {
366 return sender_->Send(flatbuffer.span().data(), flatbuffer.span().size());
Austin Schuha28cbc32019-12-27 16:28:04 -0800367}
368
Brian Silverman341b57e2020-06-23 16:23:18 -0700369template <typename T>
370bool Sender<T>::SendDetached(FlatbufferDetachedBuffer<T> detached) {
Austin Schuhadd6eb32020-11-09 21:24:26 -0800371 CHECK_EQ(static_cast<void *>(detached.span().data() + detached.span().size() -
372 sender_->size()),
373 sender_->data())
Brian Silverman341b57e2020-06-23 16:23:18 -0700374 << ": May only send the buffer detached from this Sender";
Austin Schuhadd6eb32020-11-09 21:24:26 -0800375 return sender_->Send(detached.span().size());
Brian Silverman341b57e2020-06-23 16:23:18 -0700376}
377
Alex Perrycb7da4b2019-08-28 19:35:56 -0700378} // namespace aos
379
380#endif // AOS_EVENTS_EVENT_LOOP_TMPL_H