blob: 42489e531284d334a1b29e9f7bfa8777b932a2e2 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_LOOP_H_
2#define AOS_EVENTS_EVENT_LOOP_H_
3
Brian Silverman6a54ff32020-04-28 16:41:39 -07004#include <sched.h>
5
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <atomic>
7#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08008#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07009
Austin Schuh3054f5f2021-07-21 15:38:01 -070010#include "absl/container/btree_set.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070011#include "aos/configuration.h"
12#include "aos/configuration_generated.h"
Austin Schuh1af273d2020-03-07 20:11:34 -080013#include "aos/events/channel_preallocated_allocator.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080014#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080015#include "aos/events/event_loop_generated.h"
16#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070017#include "aos/flatbuffers.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050018#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080019#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070020#include "aos/json_to_flatbuffer.h"
21#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080022#include "aos/util/phased_loop.h"
Austin Schuh4385b142021-03-14 21:31:13 -070023#include "aos/uuid.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070024#include "flatbuffers/flatbuffers.h"
25#include "glog/logging.h"
26
Austin Schuh39788ff2019-12-01 18:22:57 -080027DECLARE_bool(timing_reports);
28DECLARE_int32(timing_report_ms);
29
Alex Perrycb7da4b2019-08-28 19:35:56 -070030namespace aos {
31
Austin Schuh39788ff2019-12-01 18:22:57 -080032class EventLoop;
33class WatcherState;
34
Austin Schuh6231cc32019-12-07 13:06:15 -080035// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
36// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070037struct Context {
Austin Schuhad154822019-12-27 15:45:13 -080038 // Time that the message was sent on this node, or the timer was triggered.
39 monotonic_clock::time_point monotonic_event_time;
40 // Realtime the message was sent on this node. This is set to min_time for
41 // Timers and PhasedLoops.
42 realtime_clock::time_point realtime_event_time;
43
44 // For a single-node configuration, these two are identical to *_event_time.
45 // In a multinode configuration, these are the times that the message was
46 // sent on the original node.
47 monotonic_clock::time_point monotonic_remote_time;
48 realtime_clock::time_point realtime_remote_time;
49
Austin Schuh6231cc32019-12-07 13:06:15 -080050 // The rest are only valid for Watchers and Fetchers.
Brian Silverman4f4e0612020-08-12 19:54:41 -070051
Alex Perrycb7da4b2019-08-28 19:35:56 -070052 // Index in the queue.
53 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080054 // Index into the remote queue. Useful to determine if data was lost. In a
55 // single-node configuration, this will match queue_index.
56 uint32_t remote_queue_index;
57
Alex Perrycb7da4b2019-08-28 19:35:56 -070058 // Size of the data sent.
59 size_t size;
60 // Pointer to the data.
Brian Silvermaneaa41d62020-07-08 19:47:35 -070061 const void *data;
Austin Schuh678078e2020-08-01 14:30:36 -070062
Brian Silverman4f4e0612020-08-12 19:54:41 -070063 // Index of the message buffer. This will be in [0, NumberBuffers) on
64 // read_method=PIN channels, and -1 for other channels.
65 //
66 // This only tells you about the underlying storage for this message, not
67 // anything about its position in the queue. This is only useful for advanced
68 // zero-copy use cases, on read_method=PIN channels.
69 //
70 // This will uniquely identify a message on this channel at a point in time.
71 // For senders, this point in time is while the sender has the message. With
72 // read_method==PIN, this point in time includes while the caller has access
73 // to this context. For other read_methods, this point in time may be before
74 // the caller has access to this context, which makes this pretty useless.
75 int buffer_index;
76
Austin Schuh8902fa52021-03-14 22:39:24 -070077 // UUID of the remote node which sent this message, or this node in the case
78 // of events which are local to this node.
Austin Schuha9012be2021-07-21 15:19:11 -070079 UUID source_boot_uuid = UUID::Zero();
Austin Schuh8902fa52021-03-14 22:39:24 -070080
Austin Schuhca75b6a2020-12-15 21:12:24 -080081 // Efficiently copies the flatbuffer into a FlatbufferVector, allocating
Austin Schuh678078e2020-08-01 14:30:36 -070082 // memory in the process. It is vital that T matches the type of the
83 // underlying flatbuffer.
84 template <typename T>
85 FlatbufferVector<T> CopyFlatBuffer() const {
Brian Silverman354697a2020-09-22 21:06:32 -070086 ResizeableBuffer buffer;
87 buffer.resize(size);
88 memcpy(buffer.data(), data, size);
89 return FlatbufferVector<T>(std::move(buffer));
Austin Schuh678078e2020-08-01 14:30:36 -070090 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070091};
92
93// Raw version of fetcher. Contains a local variable that the fetcher will
94// update. This is used for reflection and as an interface to implement typed
95// fetchers.
96class RawFetcher {
97 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080098 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070099 RawFetcher(const RawFetcher &) = delete;
100 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -0800101 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 // Fetches the next message in the queue without blocking. Returns true if
104 // there was a new message and we got it.
105 bool FetchNext();
106
107 // Fetches the latest message without blocking.
108 bool Fetch();
109
110 // Returns the channel this fetcher uses.
111 const Channel *channel() const { return channel_; }
112 // Returns the context for the current message.
113 const Context &context() const { return context_; }
114
115 protected:
116 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700117 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800118
Alex Perrycb7da4b2019-08-28 19:35:56 -0700119 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800120
121 private:
122 friend class EventLoop;
123 // Implementation
124 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
125 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
126
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500127 EventLoop *const event_loop_;
128 const Channel *const channel_;
129 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800130
131 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500132 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133};
134
135// Raw version of sender. Sends a block of data. This is used for reflection
136// and as a building block to implement typed senders.
137class RawSender {
138 public:
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700139 using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
140
Austin Schuh39788ff2019-12-01 18:22:57 -0800141 RawSender(EventLoop *event_loop, const Channel *channel);
142 RawSender(const RawSender &) = delete;
143 RawSender &operator=(const RawSender &) = delete;
144
145 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700146
147 // Sends a message without copying it. The users starts by copying up to
148 // size() bytes into the data backed by data(). They then call Send to send.
149 // Returns true on a successful send.
Austin Schuhad154822019-12-27 15:45:13 -0800150 // If provided, monotonic_remote_time, realtime_remote_time, and
151 // remote_queue_index are attached to the message and are available in the
152 // context on the read side. If they are not populated, the read side will
153 // get the sent times instead.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700154 virtual void *data() = 0;
155 virtual size_t size() = 0;
Austin Schuhb5c6f972021-03-14 21:53:07 -0700156 bool Send(size_t size);
157 bool Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
158 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700159 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700160
161 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800162 // The remote arguments have the same meaning as in Send above.
Austin Schuhb5c6f972021-03-14 21:53:07 -0700163 bool Send(const void *data, size_t size);
Austin Schuhad154822019-12-27 15:45:13 -0800164 bool Send(const void *data, size_t size,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700165 monotonic_clock::time_point monotonic_remote_time,
166 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700167 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700168
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700169 // Sends a single block of data by refcounting it to avoid copies. The data
170 // must not change after being passed into Send. The remote arguments have the
171 // same meaning as in Send above.
172 bool Send(const SharedSpan data);
173 bool Send(const SharedSpan data,
174 monotonic_clock::time_point monotonic_remote_time,
175 realtime_clock::time_point realtime_remote_time,
176 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
177
Austin Schuh54cf95f2019-11-29 13:14:18 -0800178 const Channel *channel() const { return channel_; }
179
Austin Schuhad154822019-12-27 15:45:13 -0800180 // Returns the time_points that the last message was sent at.
181 aos::monotonic_clock::time_point monotonic_sent_time() const {
182 return monotonic_sent_time_;
183 }
184 aos::realtime_clock::time_point realtime_sent_time() const {
185 return realtime_sent_time_;
186 }
187 // Returns the queue index that this was sent with.
188 uint32_t sent_queue_index() const { return sent_queue_index_; }
189
Brian Silvermana1652f32020-01-29 20:41:44 -0800190 // Returns the associated flatbuffers-style allocator. This must be
191 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800192 ChannelPreallocatedAllocator *fbb_allocator() {
193 fbb_allocator_ = ChannelPreallocatedAllocator(
194 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800195 return &fbb_allocator_;
196 }
197
Brian Silverman4f4e0612020-08-12 19:54:41 -0700198 // Index of the buffer which is currently exposed by data() and the various
199 // other accessors. This is the message the caller should be filling out.
200 virtual int buffer_index() = 0;
201
Alex Perrycb7da4b2019-08-28 19:35:56 -0700202 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800203 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700204 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800205
Austin Schuhb5c6f972021-03-14 21:53:07 -0700206 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
207 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800208 uint32_t sent_queue_index_ = 0xffffffff;
209
Austin Schuh39788ff2019-12-01 18:22:57 -0800210 private:
211 friend class EventLoop;
212
Austin Schuhad154822019-12-27 15:45:13 -0800213 virtual bool DoSend(const void *data, size_t size,
Austin Schuh8902fa52021-03-14 22:39:24 -0700214 monotonic_clock::time_point monotonic_remote_time,
215 realtime_clock::time_point realtime_remote_time,
216 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700217 const UUID &source_boot_uuid) = 0;
Austin Schuhad154822019-12-27 15:45:13 -0800218 virtual bool DoSend(size_t size,
Austin Schuh8902fa52021-03-14 22:39:24 -0700219 monotonic_clock::time_point monotonic_remote_time,
220 realtime_clock::time_point realtime_remote_time,
221 uint32_t remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700222 const UUID &source_boot_uuid) = 0;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700223 virtual bool DoSend(const SharedSpan data,
224 monotonic_clock::time_point monotonic_remote_time,
225 realtime_clock::time_point realtime_remote_time,
226 uint32_t remote_queue_index,
227 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800228
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500229 EventLoop *const event_loop_;
230 const Channel *const channel_;
231 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700232
Austin Schuh39788ff2019-12-01 18:22:57 -0800233 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500234 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800235
Austin Schuh1af273d2020-03-07 20:11:34 -0800236 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800237};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700238
239// Fetches the newest message from a channel.
240// This provides a polling based interface for channels.
241template <typename T>
242class Fetcher {
243 public:
244 Fetcher() {}
245
246 // Fetches the next message. Returns true if it fetched a new message. This
247 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800248 bool FetchNext() {
249 const bool result = fetcher_->FetchNext();
250 if (result) {
251 CheckChannelDataAlignment(fetcher_->context().data,
252 fetcher_->context().size);
253 }
254 return result;
255 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256
257 // Fetches the most recent message. Returns true if it fetched a new message.
258 // This will return the latest message regardless of if it was sent before or
259 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800260 bool Fetch() {
261 const bool result = fetcher_->Fetch();
262 if (result) {
263 CheckChannelDataAlignment(fetcher_->context().data,
264 fetcher_->context().size);
265 }
266 return result;
267 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700268
269 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
270 // available message.
271 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800272 return fetcher_->context().data != nullptr
273 ? flatbuffers::GetRoot<T>(
274 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700275 : nullptr;
276 }
277
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700278 // Returns the channel this fetcher uses
279 const Channel *channel() const { return fetcher_->channel(); }
280
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281 // Returns the context holding timestamps and other metadata about the
282 // message.
283 const Context &context() const { return fetcher_->context(); }
284
285 const T &operator*() const { return *get(); }
286 const T *operator->() const { return get(); }
287
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700288 // Returns true if this fetcher is valid and connected to a channel.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700289 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700290
Austin Schuhca75b6a2020-12-15 21:12:24 -0800291 // Copies the current flatbuffer into a FlatbufferVector.
292 FlatbufferVector<T> CopyFlatBuffer() const {
293 return context().template CopyFlatBuffer<T>();
294 }
295
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296 private:
297 friend class EventLoop;
298 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
299 : fetcher_(::std::move(fetcher)) {}
300 ::std::unique_ptr<RawFetcher> fetcher_;
301};
302
303// Sends messages to a channel.
304template <typename T>
305class Sender {
306 public:
307 Sender() {}
308
309 // Represents a single message about to be sent to the queue.
310 // The lifecycle goes:
311 //
312 // Builder builder = sender.MakeBuilder();
313 // T::Builder t_builder = builder.MakeBuilder<T>();
314 // Populate(&t_builder);
315 // builder.Send(t_builder.Finish());
316 class Builder {
317 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800318 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800319 : fbb_(allocator->size(), allocator),
320 allocator_(allocator),
321 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800322 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800323 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700324 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800325 Builder() {}
326 Builder(const Builder &) = delete;
327 Builder(Builder &&) = default;
328
329 Builder &operator=(const Builder &) = delete;
330 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331
332 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
333
334 template <typename T2>
335 typename T2::Builder MakeBuilder() {
336 return typename T2::Builder(fbb_);
337 }
338
339 bool Send(flatbuffers::Offset<T> offset) {
340 fbb_.Finish(offset);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800341 const bool result = sender_->Send(fbb_.GetSize());
342 // Ensure fbb_ knows it shouldn't access the memory any more.
343 fbb_ = flatbuffers::FlatBufferBuilder();
344 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 }
346
347 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800348 void CheckSent() {
349 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
350 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700351
Brian Silverman341b57e2020-06-23 16:23:18 -0700352 // Detaches a buffer, for later use calling Sender::Send directly.
353 //
354 // Note that the underlying memory remains with the Sender, so creating
355 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
356 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
357 fbb_.Finish(offset);
358 return fbb_.Release();
359 }
360
Alex Perrycb7da4b2019-08-28 19:35:56 -0700361 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700362 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800363 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700364 RawSender *sender_;
365 };
366
367 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800368 //
369 // Only a single one of these may be "alive" for this object at any point in
370 // time. After calling Send on the result, it is no longer "alive". This means
371 // that you must manually reset a variable holding the return value (by
372 // assigning a default-constructed Builder to it) before calling this method
373 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374 Builder MakeBuilder();
375
Austin Schuha28cbc32019-12-27 16:28:04 -0800376 // Sends a prebuilt flatbuffer.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800377 bool Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800378
Brian Silverman341b57e2020-06-23 16:23:18 -0700379 // Sends a prebuilt flatbuffer which was detached from a Builder created via
380 // MakeBuilder() on this object.
381 bool SendDetached(FlatbufferDetachedBuffer<T> detached);
382
Austin Schuh39788ff2019-12-01 18:22:57 -0800383 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800384 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385
Austin Schuha0c41ba2020-09-10 22:59:14 -0700386 operator bool() const { return sender_ ? true : false; }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800387
Austin Schuh7bc59052020-02-16 23:48:33 -0800388 // Returns the time_points that the last message was sent at.
389 aos::monotonic_clock::time_point monotonic_sent_time() const {
390 return sender_->monotonic_sent_time();
391 }
392 aos::realtime_clock::time_point realtime_sent_time() const {
393 return sender_->realtime_sent_time();
394 }
395 // Returns the queue index that this was sent with.
396 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
397
Brian Silverman4f4e0612020-08-12 19:54:41 -0700398 // Returns the buffer index which MakeBuilder() will expose access to. This is
399 // the buffer the caller can fill out.
400 int buffer_index() const { return sender_->buffer_index(); }
401
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402 private:
403 friend class EventLoop;
404 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
405 std::unique_ptr<RawSender> sender_;
406};
407
Brian Silverman4f4e0612020-08-12 19:54:41 -0700408// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409class TimerHandler {
410 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800411 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700412
413 // Timer should sleep until base, base + offset, base + offset * 2, ...
414 // If repeat_offset isn't set, the timer only expires once.
415 virtual void Setup(monotonic_clock::time_point base,
416 monotonic_clock::duration repeat_offset =
417 ::aos::monotonic_clock::zero()) = 0;
418
419 // Stop future calls to callback().
420 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800421
422 // Sets and gets the name of the timer. Set this if you want a descriptive
423 // name in the timing report.
424 void set_name(std::string_view name) { name_ = std::string(name); }
425 const std::string_view name() const { return name_; }
426
Austin Schuh39788ff2019-12-01 18:22:57 -0800427 protected:
428 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
429
Austin Schuhcde39fd2020-02-22 20:58:24 -0800430 monotonic_clock::time_point Call(
431 std::function<monotonic_clock::time_point()> get_time,
432 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800433
Austin Schuh1540c2f2019-11-29 21:59:29 -0800434 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800435 friend class EventLoop;
436
437 EventLoop *event_loop_;
438 // The function to call when Call is called.
439 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800440 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800441
442 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500443 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444};
445
446// Interface for phased loops. They are built on timers.
447class PhasedLoopHandler {
448 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800449 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450
451 // Sets the interval and offset. Any changes to interval and offset only take
452 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800453 void set_interval_and_offset(const monotonic_clock::duration interval,
454 const monotonic_clock::duration offset) {
455 phased_loop_.set_interval_and_offset(interval, offset);
456 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800457
458 // Sets and gets the name of the timer. Set this if you want a descriptive
459 // name in the timing report.
460 void set_name(std::string_view name) { name_ = std::string(name); }
461 const std::string_view name() const { return name_; }
462
Austin Schuh39788ff2019-12-01 18:22:57 -0800463 protected:
464 void Call(std::function<monotonic_clock::time_point()> get_time,
465 std::function<void(monotonic_clock::time_point)> schedule);
466
467 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
468 const monotonic_clock::duration interval,
469 const monotonic_clock::duration offset);
470
Austin Schuh1540c2f2019-11-29 21:59:29 -0800471 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800472 friend class EventLoop;
473
474 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
475 monotonic_clock::time_point monotonic_now) {
476 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
477 schedule(phased_loop_.sleep_time());
478 }
479
480 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
481
482 EventLoop *event_loop_;
483 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800484 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800485 time::PhasedLoop phased_loop_;
486
487 int cycles_elapsed_ = 0;
488
489 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500490 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700491};
492
Austin Schuh3054f5f2021-07-21 15:38:01 -0700493// Note, it is supported to create only:
494// multiple fetchers, and (one sender or one watcher) per <name, type>
495// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700496class EventLoop {
497 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700498 // Holds configuration by reference for the lifetime of this object. It may
499 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800500 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700501
Austin Schuh39788ff2019-12-01 18:22:57 -0800502 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700503
504 // Current time.
505 virtual monotonic_clock::time_point monotonic_now() = 0;
506 virtual realtime_clock::time_point realtime_now() = 0;
507
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700508 // Returns true if the channel exists in the configuration.
509 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800510 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800511 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800512 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800513 true);
514 }
515 template <typename T>
516 bool HasChannel(const std::string_view channel_name) {
517 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700518 }
519
Brian Silverman631b6262021-11-10 12:25:08 -0800520 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
521 // not readable on this node or does not exist.
522 template <typename T>
523 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
524 const Channel *const channel = GetChannel<T>(channel_name);
525 if (channel == nullptr) {
526 return Fetcher<T>();
527 }
528
529 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
530 return Fetcher<T>();
531 }
532
533 return Fetcher<T>(MakeRawFetcher(channel));
534 }
535
Alex Perrycb7da4b2019-08-28 19:35:56 -0700536 // Makes a class that will always fetch the most recent value
537 // sent to the provided channel.
538 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800539 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800540 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700541 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
542 << T::GetFullyQualifiedName() << "\" } not found in config.";
543
Brian Silverman631b6262021-11-10 12:25:08 -0800544 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
545 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800546 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
547 << "\", \"type\": \"" << T::GetFullyQualifiedName()
548 << "\" } is not able to be fetched on this node. Check your "
549 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800550 }
551
Brian Silverman631b6262021-11-10 12:25:08 -0800552 return result;
553 }
554
555 // Like MakeSender, but returns an invalid sender if the given channel is
556 // not readable on this node or does not exist.
557 template <typename T>
558 Sender<T> TryMakeSender(const std::string_view channel_name) {
559 const Channel *channel = GetChannel<T>(channel_name);
560 if (channel == nullptr) {
561 return Sender<T>();
562 }
563
564 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
565 return Sender<T>();
566 }
567
568 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700569 }
570
571 // Makes class that allows constructing and sending messages to
572 // the provided channel.
573 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800574 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800575 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700576 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800577 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700578 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800579 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700580 ? absl::StrCat(" on node ", node()->name()->string_view())
581 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700582
Brian Silverman631b6262021-11-10 12:25:08 -0800583 Sender<T> result = TryMakeSender<T>(channel_name);
584 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800585 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
586 << "\", \"type\": \"" << T::GetFullyQualifiedName()
587 << "\" } is not able to be sent on this node. Check your "
588 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800589 }
590
Brian Silverman631b6262021-11-10 12:25:08 -0800591 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700592 }
593
594 // This will watch messages sent to the provided channel.
595 //
Brian Silverman454bc112020-03-05 14:21:25 -0800596 // w must have a non-polymorphic operator() (aka it can only be called with a
597 // single set of arguments; no overloading or templates). It must be callable
598 // with this signature:
599 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700600 //
Brian Silverman454bc112020-03-05 14:21:25 -0800601 // Lambdas are a common form for w. A std::function will work too.
602 //
603 // Note that bind expressions have polymorphic call operators, so they are not
604 // allowed.
605 //
606 // We template Watch as a whole instead of using std::function<void(const T
607 // &)> to allow deducing MessageType from lambdas and other things which are
608 // implicitly convertible to std::function, but not actually std::function
609 // instantiations. Template deduction guides might allow solving this
610 // differently in newer versions of C++, but those have their own corner
611 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700612 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800613 void MakeWatcher(const std::string_view channel_name, Watch &&w);
614
615 // Like MakeWatcher, but doesn't have access to the message data. This may be
616 // implemented to use less resources than an equivalent MakeWatcher.
617 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800618 // The function will still have access to context(), although that will have
619 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800620 template <typename MessageType>
621 void MakeNoArgWatcher(const std::string_view channel_name,
622 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700623
624 // The passed in function will be called when the event loop starts.
625 // Use this to run code once the thread goes into "real-time-mode",
626 virtual void OnRun(::std::function<void()> on_run) = 0;
627
Austin Schuh217a9782019-12-21 23:02:50 -0800628 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800629 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630
Austin Schuh217a9782019-12-21 23:02:50 -0800631 // Returns the node that this event loop is running on. Returns nullptr if we
632 // are running in single-node mode.
633 virtual const Node *node() const = 0;
634
Alex Perrycb7da4b2019-08-28 19:35:56 -0700635 // Creates a timer that executes callback when the timer expires
636 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700637 // TODO(milind): callback should take the number of cycles elapsed as a
638 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700639 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
640
641 // Creates a timer that executes callback periodically at the specified
642 // interval and offset. Returns a PhasedLoopHandler for interacting with the
643 // timer.
644 virtual PhasedLoopHandler *AddPhasedLoop(
645 ::std::function<void(int)> callback,
646 const monotonic_clock::duration interval,
647 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
648
Austin Schuh217a9782019-12-21 23:02:50 -0800649 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700650
Austin Schuh3054f5f2021-07-21 15:38:01 -0700651 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700652 bool is_running() const { return is_running_.load(); }
653
654 // Sets the scheduler priority to run the event loop at. This may not be
655 // called after we go into "real-time-mode".
656 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800657 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700658
Brian Silverman6a54ff32020-04-28 16:41:39 -0700659 // Sets the scheduler affinity to run the event loop with. This may only be
660 // called before Run().
661 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
662
Austin Schuh217a9782019-12-21 23:02:50 -0800663 // Fetches new messages from the provided channel (path, type).
664 //
665 // Note: this channel must be a member of the exact configuration object this
666 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700667 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
668 const Channel *channel) = 0;
669
Austin Schuh217a9782019-12-21 23:02:50 -0800670 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700671 virtual void MakeRawWatcher(
672 const Channel *channel,
673 std::function<void(const Context &context, const void *message)>
674 watcher) = 0;
675
Brian Silverman454bc112020-03-05 14:21:25 -0800676 // Watches channel (name, type) for new messages, without needing to extract
677 // the message contents. Default implementation simply re-uses MakeRawWatcher.
678 virtual void MakeRawNoArgWatcher(
679 const Channel *channel,
680 std::function<void(const Context &context)> watcher) {
681 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800682 Context new_context = context;
683 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700684 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800685 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800686 });
687 }
688
Austin Schuh217a9782019-12-21 23:02:50 -0800689 // Creates a raw sender for the provided channel. This is used for reflection
690 // based sending.
691 // Note: this ignores any node constraints. Ignore at your own peril.
692 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
693
Austin Schuh6231cc32019-12-07 13:06:15 -0800694 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700695 const Context &context() const { return context_; }
696
697 // Returns the configuration that this event loop was built with.
698 const Configuration *configuration() const { return configuration_; }
699
Austin Schuh39788ff2019-12-01 18:22:57 -0800700 // Prevents the event loop from sending a timing report.
701 void SkipTimingReport() { skip_timing_report_ = true; }
702
Brian Silverman4f4e0612020-08-12 19:54:41 -0700703 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800704 void SkipAosLog() { skip_logger_ = true; }
705
Brian Silverman4f4e0612020-08-12 19:54:41 -0700706 // Returns the number of buffers for this channel. This corresponds with the
707 // range of Context::buffer_index values for this channel.
708 virtual int NumberBuffers(const Channel *channel) = 0;
709
Austin Schuh20ac95d2020-12-05 17:24:19 -0800710 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800711 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800712
Alex Perrycb7da4b2019-08-28 19:35:56 -0700713 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800714 // Sets the name of the event loop. This is the application name.
715 virtual void set_name(const std::string_view name) = 0;
716
Alex Perrycb7da4b2019-08-28 19:35:56 -0700717 void set_is_running(bool value) { is_running_.store(value); }
718
Austin Schuh39788ff2019-12-01 18:22:57 -0800719 // Validates that channel exists inside configuration_ and finds its index.
720 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700721
Brian Silverman5120afb2020-01-31 17:44:35 -0800722 // Returns the state for the watcher on the corresponding channel. This
723 // watcher must exist before calling this.
724 WatcherState *GetWatcherState(const Channel *channel);
725
Brian Silverman6d2b3592020-06-18 14:40:15 -0700726 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800727 template <typename T>
728 static RawSender *GetRawSender(aos::Sender<T> *sender) {
729 return sender->sender_.get();
730 }
731
Brian Silverman6d2b3592020-06-18 14:40:15 -0700732 // Returns a Fetcher's protected RawFetcher.
733 template <typename T>
734 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
735 return fetcher->fetcher_.get();
736 }
737
Austin Schuh6231cc32019-12-07 13:06:15 -0800738 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700739 Context context_;
740
Austin Schuh39788ff2019-12-01 18:22:57 -0800741 friend class RawSender;
742 friend class TimerHandler;
743 friend class RawFetcher;
744 friend class PhasedLoopHandler;
745 friend class WatcherState;
746
747 // Methods used to implement timing reports.
748 void NewSender(RawSender *sender);
749 void DeleteSender(RawSender *sender);
750 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
751 PhasedLoopHandler *NewPhasedLoop(
752 std::unique_ptr<PhasedLoopHandler> phased_loop);
753 void NewFetcher(RawFetcher *fetcher);
754 void DeleteFetcher(RawFetcher *fetcher);
755 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
756
Brian Silverman0fc69932020-01-24 21:54:02 -0800757 // Tracks that we have a (single) watcher on the given channel.
758 void TakeWatcher(const Channel *channel);
759 // Tracks that we have at least one sender on the given channel.
760 void TakeSender(const Channel *channel);
761
Austin Schuh39788ff2019-12-01 18:22:57 -0800762 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800763 std::vector<RawFetcher *> fetchers_;
764
Austin Schuh39788ff2019-12-01 18:22:57 -0800765 std::vector<std::unique_ptr<TimerHandler>> timers_;
766 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800767 std::vector<std::unique_ptr<WatcherState>> watchers_;
768
Brian Silvermance418d02021-11-03 11:25:52 -0700769 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800770 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700771
Austin Schuh39788ff2019-12-01 18:22:57 -0800772 void UpdateTimingReport();
773 void MaybeScheduleTimingReports();
774
775 std::unique_ptr<RawSender> timing_report_sender_;
776
Austin Schuh7d87b672019-12-01 20:23:49 -0800777 // Tracks which event sources (timers and watchers) have data, and which
778 // don't. Added events may not change their event_time().
779 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
780 // t2 to run, t2 should then be picked up without a context switch.
781 void AddEvent(EventLoopEvent *event);
782 void RemoveEvent(EventLoopEvent *event);
783 size_t EventCount() const { return events_.size(); }
784 EventLoopEvent *PopEvent();
785 EventLoopEvent *PeekEvent() { return events_.front(); }
786 void ReserveEvents();
787
788 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700789 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800790
Tyler Chatow67ddb032020-01-12 14:30:04 -0800791 // If true, don't send AOS_LOG to /aos
792 bool skip_logger_ = false;
793
Austin Schuha9012be2021-07-21 15:19:11 -0700794 // Sets context_ for a timed event which is supposed to happen at the provided
795 // time.
796 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
797
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800798 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800799 virtual pid_t GetTid() = 0;
800
801 FlatbufferDetachedBuffer<timing::Report> timing_report_;
802
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800803 ::std::atomic<bool> is_running_{false};
804
Alex Perrycb7da4b2019-08-28 19:35:56 -0700805 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800806
807 // If true, don't send out timing reports.
808 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800809
810 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700811};
812
813} // namespace aos
814
Austin Schuhb8075812020-10-19 09:36:49 -0700815#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700816
817#endif // AOS_EVENTS_EVENT_LOOP_H