blob: cf17c2ee9a2b88942c4ac0e9877d533d5c1cb741 [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
Alex Perrycb7da4b2019-08-28 19:35:56 -0700520 // Makes a class that will always fetch the most recent value
521 // sent to the provided channel.
522 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800523 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuha0654152021-02-21 21:38:24 -0800524 const Channel *channel = GetChannel<T>(channel_name);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525 CHECK(channel != nullptr)
526 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
527 << T::GetFullyQualifiedName() << "\" } not found in config.";
528
Austin Schuhca4828c2019-12-28 14:21:35 -0800529 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
530 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
531 << "\", \"type\": \"" << T::GetFullyQualifiedName()
532 << "\" } is not able to be fetched on this node. Check your "
533 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800534 }
535
Alex Perrycb7da4b2019-08-28 19:35:56 -0700536 return Fetcher<T>(MakeRawFetcher(channel));
537 }
538
539 // Makes class that allows constructing and sending messages to
540 // the provided channel.
541 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800542 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuha0654152021-02-21 21:38:24 -0800543 const Channel *channel = GetChannel<T>(channel_name);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544 CHECK(channel != nullptr)
545 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800546 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700547 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800548 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700549 ? absl::StrCat(" on node ", node()->name()->string_view())
550 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700551
Austin Schuhca4828c2019-12-28 14:21:35 -0800552 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
553 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
554 << "\", \"type\": \"" << T::GetFullyQualifiedName()
555 << "\" } is not able to be sent on this node. Check your "
556 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800557 }
558
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559 return Sender<T>(MakeRawSender(channel));
560 }
561
562 // This will watch messages sent to the provided channel.
563 //
Brian Silverman454bc112020-03-05 14:21:25 -0800564 // w must have a non-polymorphic operator() (aka it can only be called with a
565 // single set of arguments; no overloading or templates). It must be callable
566 // with this signature:
567 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700568 //
Brian Silverman454bc112020-03-05 14:21:25 -0800569 // Lambdas are a common form for w. A std::function will work too.
570 //
571 // Note that bind expressions have polymorphic call operators, so they are not
572 // allowed.
573 //
574 // We template Watch as a whole instead of using std::function<void(const T
575 // &)> to allow deducing MessageType from lambdas and other things which are
576 // implicitly convertible to std::function, but not actually std::function
577 // instantiations. Template deduction guides might allow solving this
578 // differently in newer versions of C++, but those have their own corner
579 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800581 void MakeWatcher(const std::string_view channel_name, Watch &&w);
582
583 // Like MakeWatcher, but doesn't have access to the message data. This may be
584 // implemented to use less resources than an equivalent MakeWatcher.
585 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800586 // The function will still have access to context(), although that will have
587 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800588 template <typename MessageType>
589 void MakeNoArgWatcher(const std::string_view channel_name,
590 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700591
592 // The passed in function will be called when the event loop starts.
593 // Use this to run code once the thread goes into "real-time-mode",
594 virtual void OnRun(::std::function<void()> on_run) = 0;
595
Austin Schuh217a9782019-12-21 23:02:50 -0800596 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800597 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598
Austin Schuh217a9782019-12-21 23:02:50 -0800599 // Returns the node that this event loop is running on. Returns nullptr if we
600 // are running in single-node mode.
601 virtual const Node *node() const = 0;
602
Alex Perrycb7da4b2019-08-28 19:35:56 -0700603 // Creates a timer that executes callback when the timer expires
604 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700605 // TODO(milind): callback should take the number of cycles elapsed as a
606 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700607 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
608
609 // Creates a timer that executes callback periodically at the specified
610 // interval and offset. Returns a PhasedLoopHandler for interacting with the
611 // timer.
612 virtual PhasedLoopHandler *AddPhasedLoop(
613 ::std::function<void(int)> callback,
614 const monotonic_clock::duration interval,
615 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
616
Austin Schuh217a9782019-12-21 23:02:50 -0800617 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618
Austin Schuh3054f5f2021-07-21 15:38:01 -0700619 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700620 bool is_running() const { return is_running_.load(); }
621
622 // Sets the scheduler priority to run the event loop at. This may not be
623 // called after we go into "real-time-mode".
624 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800625 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700626
Brian Silverman6a54ff32020-04-28 16:41:39 -0700627 // Sets the scheduler affinity to run the event loop with. This may only be
628 // called before Run().
629 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
630
Austin Schuh217a9782019-12-21 23:02:50 -0800631 // Fetches new messages from the provided channel (path, type).
632 //
633 // Note: this channel must be a member of the exact configuration object this
634 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700635 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
636 const Channel *channel) = 0;
637
Austin Schuh217a9782019-12-21 23:02:50 -0800638 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700639 virtual void MakeRawWatcher(
640 const Channel *channel,
641 std::function<void(const Context &context, const void *message)>
642 watcher) = 0;
643
Brian Silverman454bc112020-03-05 14:21:25 -0800644 // Watches channel (name, type) for new messages, without needing to extract
645 // the message contents. Default implementation simply re-uses MakeRawWatcher.
646 virtual void MakeRawNoArgWatcher(
647 const Channel *channel,
648 std::function<void(const Context &context)> watcher) {
649 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800650 Context new_context = context;
651 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700652 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800653 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800654 });
655 }
656
Austin Schuh217a9782019-12-21 23:02:50 -0800657 // Creates a raw sender for the provided channel. This is used for reflection
658 // based sending.
659 // Note: this ignores any node constraints. Ignore at your own peril.
660 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
661
Austin Schuh6231cc32019-12-07 13:06:15 -0800662 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700663 const Context &context() const { return context_; }
664
665 // Returns the configuration that this event loop was built with.
666 const Configuration *configuration() const { return configuration_; }
667
Austin Schuh39788ff2019-12-01 18:22:57 -0800668 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800669 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800670
Brian Silverman4f4e0612020-08-12 19:54:41 -0700671 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800672 void SkipAosLog() { skip_logger_ = true; }
673
Brian Silverman4f4e0612020-08-12 19:54:41 -0700674 // Returns the number of buffers for this channel. This corresponds with the
675 // range of Context::buffer_index values for this channel.
676 virtual int NumberBuffers(const Channel *channel) = 0;
677
Austin Schuh20ac95d2020-12-05 17:24:19 -0800678 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800679 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800680
Alex Perrycb7da4b2019-08-28 19:35:56 -0700681 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800682 // Sets the name of the event loop. This is the application name.
683 virtual void set_name(const std::string_view name) = 0;
684
Alex Perrycb7da4b2019-08-28 19:35:56 -0700685 void set_is_running(bool value) { is_running_.store(value); }
686
Austin Schuh39788ff2019-12-01 18:22:57 -0800687 // Validates that channel exists inside configuration_ and finds its index.
688 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700689
Brian Silverman5120afb2020-01-31 17:44:35 -0800690 // Returns the state for the watcher on the corresponding channel. This
691 // watcher must exist before calling this.
692 WatcherState *GetWatcherState(const Channel *channel);
693
Brian Silverman6d2b3592020-06-18 14:40:15 -0700694 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800695 template <typename T>
696 static RawSender *GetRawSender(aos::Sender<T> *sender) {
697 return sender->sender_.get();
698 }
699
Brian Silverman6d2b3592020-06-18 14:40:15 -0700700 // Returns a Fetcher's protected RawFetcher.
701 template <typename T>
702 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
703 return fetcher->fetcher_.get();
704 }
705
Austin Schuh6231cc32019-12-07 13:06:15 -0800706 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700707 Context context_;
708
Austin Schuh39788ff2019-12-01 18:22:57 -0800709 friend class RawSender;
710 friend class TimerHandler;
711 friend class RawFetcher;
712 friend class PhasedLoopHandler;
713 friend class WatcherState;
714
715 // Methods used to implement timing reports.
716 void NewSender(RawSender *sender);
717 void DeleteSender(RawSender *sender);
718 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
719 PhasedLoopHandler *NewPhasedLoop(
720 std::unique_ptr<PhasedLoopHandler> phased_loop);
721 void NewFetcher(RawFetcher *fetcher);
722 void DeleteFetcher(RawFetcher *fetcher);
723 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
724
Brian Silverman0fc69932020-01-24 21:54:02 -0800725 // Tracks that we have a (single) watcher on the given channel.
726 void TakeWatcher(const Channel *channel);
727 // Tracks that we have at least one sender on the given channel.
728 void TakeSender(const Channel *channel);
729
Austin Schuh39788ff2019-12-01 18:22:57 -0800730 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800731 std::vector<RawFetcher *> fetchers_;
732
Austin Schuh39788ff2019-12-01 18:22:57 -0800733 std::vector<std::unique_ptr<TimerHandler>> timers_;
734 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800735 std::vector<std::unique_ptr<WatcherState>> watchers_;
736
Brian Silvermance418d02021-11-03 11:25:52 -0700737 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800738 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700739
Austin Schuh39788ff2019-12-01 18:22:57 -0800740 void UpdateTimingReport();
741 void MaybeScheduleTimingReports();
742
743 std::unique_ptr<RawSender> timing_report_sender_;
744
Austin Schuh7d87b672019-12-01 20:23:49 -0800745 // Tracks which event sources (timers and watchers) have data, and which
746 // don't. Added events may not change their event_time().
747 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
748 // t2 to run, t2 should then be picked up without a context switch.
749 void AddEvent(EventLoopEvent *event);
750 void RemoveEvent(EventLoopEvent *event);
751 size_t EventCount() const { return events_.size(); }
752 EventLoopEvent *PopEvent();
753 EventLoopEvent *PeekEvent() { return events_.front(); }
754 void ReserveEvents();
755
756 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700757 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800758
Tyler Chatow67ddb032020-01-12 14:30:04 -0800759 // If true, don't send AOS_LOG to /aos
760 bool skip_logger_ = false;
761
Austin Schuha9012be2021-07-21 15:19:11 -0700762 // Sets context_ for a timed event which is supposed to happen at the provided
763 // time.
764 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
765
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800766 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800767 virtual pid_t GetTid() = 0;
768
769 FlatbufferDetachedBuffer<timing::Report> timing_report_;
770
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800771 ::std::atomic<bool> is_running_{false};
772
Alex Perrycb7da4b2019-08-28 19:35:56 -0700773 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800774
775 // If true, don't send out timing reports.
776 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800777
778 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700779};
780
781} // namespace aos
782
Austin Schuhb8075812020-10-19 09:36:49 -0700783#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700784
785#endif // AOS_EVENTS_EVENT_LOOP_H