blob: d23314e1e939dad04d20bb14218b560cb611b0d3 [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
Alex Perrycb7da4b2019-08-28 19:35:56 -070010#include "aos/configuration.h"
11#include "aos/configuration_generated.h"
Austin Schuh1af273d2020-03-07 20:11:34 -080012#include "aos/events/channel_preallocated_allocator.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080013#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080014#include "aos/events/event_loop_generated.h"
15#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "aos/flatbuffers.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050017#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080018#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070019#include "aos/json_to_flatbuffer.h"
20#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080021#include "aos/util/phased_loop.h"
Austin Schuh4385b142021-03-14 21:31:13 -070022#include "aos/uuid.h"
Brian Silverman0fc69932020-01-24 21:54:02 -080023
24#include "absl/container/btree_set.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070025#include "flatbuffers/flatbuffers.h"
26#include "glog/logging.h"
27
Austin Schuh39788ff2019-12-01 18:22:57 -080028DECLARE_bool(timing_reports);
29DECLARE_int32(timing_report_ms);
30
Alex Perrycb7da4b2019-08-28 19:35:56 -070031namespace aos {
32
Austin Schuh39788ff2019-12-01 18:22:57 -080033class EventLoop;
34class WatcherState;
35
Austin Schuh6231cc32019-12-07 13:06:15 -080036// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
37// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070038struct Context {
Austin Schuhad154822019-12-27 15:45:13 -080039 // Time that the message was sent on this node, or the timer was triggered.
40 monotonic_clock::time_point monotonic_event_time;
41 // Realtime the message was sent on this node. This is set to min_time for
42 // Timers and PhasedLoops.
43 realtime_clock::time_point realtime_event_time;
44
45 // For a single-node configuration, these two are identical to *_event_time.
46 // In a multinode configuration, these are the times that the message was
47 // sent on the original node.
48 monotonic_clock::time_point monotonic_remote_time;
49 realtime_clock::time_point realtime_remote_time;
50
Austin Schuh6231cc32019-12-07 13:06:15 -080051 // The rest are only valid for Watchers and Fetchers.
Brian Silverman4f4e0612020-08-12 19:54:41 -070052
Alex Perrycb7da4b2019-08-28 19:35:56 -070053 // Index in the queue.
54 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080055 // Index into the remote queue. Useful to determine if data was lost. In a
56 // single-node configuration, this will match queue_index.
57 uint32_t remote_queue_index;
58
Alex Perrycb7da4b2019-08-28 19:35:56 -070059 // Size of the data sent.
60 size_t size;
61 // Pointer to the data.
Brian Silvermaneaa41d62020-07-08 19:47:35 -070062 const void *data;
Austin Schuh678078e2020-08-01 14:30:36 -070063
Brian Silverman4f4e0612020-08-12 19:54:41 -070064 // Index of the message buffer. This will be in [0, NumberBuffers) on
65 // read_method=PIN channels, and -1 for other channels.
66 //
67 // This only tells you about the underlying storage for this message, not
68 // anything about its position in the queue. This is only useful for advanced
69 // zero-copy use cases, on read_method=PIN channels.
70 //
71 // This will uniquely identify a message on this channel at a point in time.
72 // For senders, this point in time is while the sender has the message. With
73 // read_method==PIN, this point in time includes while the caller has access
74 // to this context. For other read_methods, this point in time may be before
75 // the caller has access to this context, which makes this pretty useless.
76 int buffer_index;
77
Austin Schuh8902fa52021-03-14 22:39:24 -070078 // UUID of the remote node which sent this message, or this node in the case
79 // of events which are local to this node.
80 UUID remote_boot_uuid = UUID::Zero();
81
Austin Schuhca75b6a2020-12-15 21:12:24 -080082 // Efficiently copies the flatbuffer into a FlatbufferVector, allocating
Austin Schuh678078e2020-08-01 14:30:36 -070083 // memory in the process. It is vital that T matches the type of the
84 // underlying flatbuffer.
85 template <typename T>
86 FlatbufferVector<T> CopyFlatBuffer() const {
Brian Silverman354697a2020-09-22 21:06:32 -070087 ResizeableBuffer buffer;
88 buffer.resize(size);
89 memcpy(buffer.data(), data, size);
90 return FlatbufferVector<T>(std::move(buffer));
Austin Schuh678078e2020-08-01 14:30:36 -070091 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070092};
93
94// Raw version of fetcher. Contains a local variable that the fetcher will
95// update. This is used for reflection and as an interface to implement typed
96// fetchers.
97class RawFetcher {
98 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080099 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700100 RawFetcher(const RawFetcher &) = delete;
101 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700103
Austin Schuh39788ff2019-12-01 18:22:57 -0800104 // Fetches the next message in the queue without blocking. Returns true if
105 // there was a new message and we got it.
106 bool FetchNext();
107
108 // Fetches the latest message without blocking.
109 bool Fetch();
110
111 // Returns the channel this fetcher uses.
112 const Channel *channel() const { return channel_; }
113 // Returns the context for the current message.
114 const Context &context() const { return context_; }
115
116 protected:
117 EventLoop *event_loop() { return event_loop_; }
118
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:
Austin Schuh39788ff2019-12-01 18:22:57 -0800139 RawSender(EventLoop *event_loop, const Channel *channel);
140 RawSender(const RawSender &) = delete;
141 RawSender &operator=(const RawSender &) = delete;
142
143 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700144
145 // Sends a message without copying it. The users starts by copying up to
146 // size() bytes into the data backed by data(). They then call Send to send.
147 // Returns true on a successful send.
Austin Schuhad154822019-12-27 15:45:13 -0800148 // If provided, monotonic_remote_time, realtime_remote_time, and
149 // remote_queue_index are attached to the message and are available in the
150 // context on the read side. If they are not populated, the read side will
151 // get the sent times instead.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700152 virtual void *data() = 0;
153 virtual size_t size() = 0;
Austin Schuhb5c6f972021-03-14 21:53:07 -0700154 bool Send(size_t size);
155 bool Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
156 realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700157 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700158
159 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800160 // The remote arguments have the same meaning as in Send above.
Austin Schuhb5c6f972021-03-14 21:53:07 -0700161 bool Send(const void *data, size_t size);
Austin Schuhad154822019-12-27 15:45:13 -0800162 bool Send(const void *data, size_t size,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700163 monotonic_clock::time_point monotonic_remote_time,
164 realtime_clock::time_point realtime_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -0700165 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700166
Austin Schuh54cf95f2019-11-29 13:14:18 -0800167 const Channel *channel() const { return channel_; }
168
Austin Schuhad154822019-12-27 15:45:13 -0800169 // Returns the time_points that the last message was sent at.
170 aos::monotonic_clock::time_point monotonic_sent_time() const {
171 return monotonic_sent_time_;
172 }
173 aos::realtime_clock::time_point realtime_sent_time() const {
174 return realtime_sent_time_;
175 }
176 // Returns the queue index that this was sent with.
177 uint32_t sent_queue_index() const { return sent_queue_index_; }
178
Brian Silvermana1652f32020-01-29 20:41:44 -0800179 // Returns the associated flatbuffers-style allocator. This must be
180 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800181 ChannelPreallocatedAllocator *fbb_allocator() {
182 fbb_allocator_ = ChannelPreallocatedAllocator(
183 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800184 return &fbb_allocator_;
185 }
186
Brian Silverman4f4e0612020-08-12 19:54:41 -0700187 // Index of the buffer which is currently exposed by data() and the various
188 // other accessors. This is the message the caller should be filling out.
189 virtual int buffer_index() = 0;
190
Alex Perrycb7da4b2019-08-28 19:35:56 -0700191 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800192 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800193
Austin Schuhb5c6f972021-03-14 21:53:07 -0700194 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
195 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800196 uint32_t sent_queue_index_ = 0xffffffff;
197
Austin Schuh39788ff2019-12-01 18:22:57 -0800198 private:
199 friend class EventLoop;
200
Austin Schuhad154822019-12-27 15:45:13 -0800201 virtual bool DoSend(const void *data, size_t size,
Austin Schuh8902fa52021-03-14 22:39:24 -0700202 monotonic_clock::time_point monotonic_remote_time,
203 realtime_clock::time_point realtime_remote_time,
204 uint32_t remote_queue_index,
205 const UUID &remote_boot_uuid) = 0;
Austin Schuhad154822019-12-27 15:45:13 -0800206 virtual bool DoSend(size_t size,
Austin Schuh8902fa52021-03-14 22:39:24 -0700207 monotonic_clock::time_point monotonic_remote_time,
208 realtime_clock::time_point realtime_remote_time,
209 uint32_t remote_queue_index,
210 const UUID &remote_boot_uuid) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800211
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500212 EventLoop *const event_loop_;
213 const Channel *const channel_;
214 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700215
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500217 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800218
Austin Schuh1af273d2020-03-07 20:11:34 -0800219 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800220};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700221
222// Fetches the newest message from a channel.
223// This provides a polling based interface for channels.
224template <typename T>
225class Fetcher {
226 public:
227 Fetcher() {}
228
229 // Fetches the next message. Returns true if it fetched a new message. This
230 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800231 bool FetchNext() {
232 const bool result = fetcher_->FetchNext();
233 if (result) {
234 CheckChannelDataAlignment(fetcher_->context().data,
235 fetcher_->context().size);
236 }
237 return result;
238 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700239
240 // Fetches the most recent message. Returns true if it fetched a new message.
241 // This will return the latest message regardless of if it was sent before or
242 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800243 bool Fetch() {
244 const bool result = fetcher_->Fetch();
245 if (result) {
246 CheckChannelDataAlignment(fetcher_->context().data,
247 fetcher_->context().size);
248 }
249 return result;
250 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700251
252 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
253 // available message.
254 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800255 return fetcher_->context().data != nullptr
256 ? flatbuffers::GetRoot<T>(
257 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700258 : nullptr;
259 }
260
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700261 // Returns the channel this fetcher uses
262 const Channel *channel() const { return fetcher_->channel(); }
263
Alex Perrycb7da4b2019-08-28 19:35:56 -0700264 // Returns the context holding timestamps and other metadata about the
265 // message.
266 const Context &context() const { return fetcher_->context(); }
267
268 const T &operator*() const { return *get(); }
269 const T *operator->() const { return get(); }
270
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700271 // Returns true if this fetcher is valid and connected to a channel.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700272 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700273
Austin Schuhca75b6a2020-12-15 21:12:24 -0800274 // Copies the current flatbuffer into a FlatbufferVector.
275 FlatbufferVector<T> CopyFlatBuffer() const {
276 return context().template CopyFlatBuffer<T>();
277 }
278
Alex Perrycb7da4b2019-08-28 19:35:56 -0700279 private:
280 friend class EventLoop;
281 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
282 : fetcher_(::std::move(fetcher)) {}
283 ::std::unique_ptr<RawFetcher> fetcher_;
284};
285
286// Sends messages to a channel.
287template <typename T>
288class Sender {
289 public:
290 Sender() {}
291
292 // Represents a single message about to be sent to the queue.
293 // The lifecycle goes:
294 //
295 // Builder builder = sender.MakeBuilder();
296 // T::Builder t_builder = builder.MakeBuilder<T>();
297 // Populate(&t_builder);
298 // builder.Send(t_builder.Finish());
299 class Builder {
300 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800301 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800302 : fbb_(allocator->size(), allocator),
303 allocator_(allocator),
304 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800305 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800306 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800308 Builder() {}
309 Builder(const Builder &) = delete;
310 Builder(Builder &&) = default;
311
312 Builder &operator=(const Builder &) = delete;
313 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700314
315 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
316
317 template <typename T2>
318 typename T2::Builder MakeBuilder() {
319 return typename T2::Builder(fbb_);
320 }
321
322 bool Send(flatbuffers::Offset<T> offset) {
323 fbb_.Finish(offset);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800324 const bool result = sender_->Send(fbb_.GetSize());
325 // Ensure fbb_ knows it shouldn't access the memory any more.
326 fbb_ = flatbuffers::FlatBufferBuilder();
327 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700328 }
329
330 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800331 void CheckSent() {
332 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
333 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334
Brian Silverman341b57e2020-06-23 16:23:18 -0700335 // Detaches a buffer, for later use calling Sender::Send directly.
336 //
337 // Note that the underlying memory remains with the Sender, so creating
338 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
339 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
340 fbb_.Finish(offset);
341 return fbb_.Release();
342 }
343
Alex Perrycb7da4b2019-08-28 19:35:56 -0700344 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800346 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700347 RawSender *sender_;
348 };
349
350 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800351 //
352 // Only a single one of these may be "alive" for this object at any point in
353 // time. After calling Send on the result, it is no longer "alive". This means
354 // that you must manually reset a variable holding the return value (by
355 // assigning a default-constructed Builder to it) before calling this method
356 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357 Builder MakeBuilder();
358
Austin Schuha28cbc32019-12-27 16:28:04 -0800359 // Sends a prebuilt flatbuffer.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800360 bool Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800361
Brian Silverman341b57e2020-06-23 16:23:18 -0700362 // Sends a prebuilt flatbuffer which was detached from a Builder created via
363 // MakeBuilder() on this object.
364 bool SendDetached(FlatbufferDetachedBuffer<T> detached);
365
Austin Schuh39788ff2019-12-01 18:22:57 -0800366 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800367 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700368
Austin Schuha0c41ba2020-09-10 22:59:14 -0700369 operator bool() const { return sender_ ? true : false; }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800370
Austin Schuh7bc59052020-02-16 23:48:33 -0800371 // Returns the time_points that the last message was sent at.
372 aos::monotonic_clock::time_point monotonic_sent_time() const {
373 return sender_->monotonic_sent_time();
374 }
375 aos::realtime_clock::time_point realtime_sent_time() const {
376 return sender_->realtime_sent_time();
377 }
378 // Returns the queue index that this was sent with.
379 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
380
Brian Silverman4f4e0612020-08-12 19:54:41 -0700381 // Returns the buffer index which MakeBuilder() will expose access to. This is
382 // the buffer the caller can fill out.
383 int buffer_index() const { return sender_->buffer_index(); }
384
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385 private:
386 friend class EventLoop;
387 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
388 std::unique_ptr<RawSender> sender_;
389};
390
Brian Silverman4f4e0612020-08-12 19:54:41 -0700391// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700392class TimerHandler {
393 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800394 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395
396 // Timer should sleep until base, base + offset, base + offset * 2, ...
397 // If repeat_offset isn't set, the timer only expires once.
398 virtual void Setup(monotonic_clock::time_point base,
399 monotonic_clock::duration repeat_offset =
400 ::aos::monotonic_clock::zero()) = 0;
401
402 // Stop future calls to callback().
403 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800404
405 // Sets and gets the name of the timer. Set this if you want a descriptive
406 // name in the timing report.
407 void set_name(std::string_view name) { name_ = std::string(name); }
408 const std::string_view name() const { return name_; }
409
Austin Schuh39788ff2019-12-01 18:22:57 -0800410 protected:
411 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
412
Austin Schuhcde39fd2020-02-22 20:58:24 -0800413 monotonic_clock::time_point Call(
414 std::function<monotonic_clock::time_point()> get_time,
415 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800416
Austin Schuh1540c2f2019-11-29 21:59:29 -0800417 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800418 friend class EventLoop;
419
420 EventLoop *event_loop_;
421 // The function to call when Call is called.
422 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800423 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800424
425 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500426 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700427};
428
429// Interface for phased loops. They are built on timers.
430class PhasedLoopHandler {
431 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800432 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433
434 // Sets the interval and offset. Any changes to interval and offset only take
435 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800436 void set_interval_and_offset(const monotonic_clock::duration interval,
437 const monotonic_clock::duration offset) {
438 phased_loop_.set_interval_and_offset(interval, offset);
439 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800440
441 // Sets and gets the name of the timer. Set this if you want a descriptive
442 // name in the timing report.
443 void set_name(std::string_view name) { name_ = std::string(name); }
444 const std::string_view name() const { return name_; }
445
Austin Schuh39788ff2019-12-01 18:22:57 -0800446 protected:
447 void Call(std::function<monotonic_clock::time_point()> get_time,
448 std::function<void(monotonic_clock::time_point)> schedule);
449
450 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
451 const monotonic_clock::duration interval,
452 const monotonic_clock::duration offset);
453
Austin Schuh1540c2f2019-11-29 21:59:29 -0800454 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800455 friend class EventLoop;
456
457 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
458 monotonic_clock::time_point monotonic_now) {
459 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
460 schedule(phased_loop_.sleep_time());
461 }
462
463 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
464
465 EventLoop *event_loop_;
466 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800467 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800468 time::PhasedLoop phased_loop_;
469
470 int cycles_elapsed_ = 0;
471
472 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500473 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474};
475
Alex Perrycb7da4b2019-08-28 19:35:56 -0700476class EventLoop {
477 public:
Austin Schuh83c7f702021-01-19 22:36:29 -0800478 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479
Austin Schuh39788ff2019-12-01 18:22:57 -0800480 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481
482 // Current time.
483 virtual monotonic_clock::time_point monotonic_now() = 0;
484 virtual realtime_clock::time_point realtime_now() = 0;
485
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700486 // Returns true if the channel exists in the configuration.
487 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800488 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800489 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800490 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800491 true);
492 }
493 template <typename T>
494 bool HasChannel(const std::string_view channel_name) {
495 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700496 }
497
Alex Perrycb7da4b2019-08-28 19:35:56 -0700498 // Note, it is supported to create:
499 // multiple fetchers, and (one sender or one watcher) per <name, type>
500 // tuple.
501
502 // Makes a class that will always fetch the most recent value
503 // sent to the provided channel.
504 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800505 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuha0654152021-02-21 21:38:24 -0800506 const Channel *channel = GetChannel<T>(channel_name);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507 CHECK(channel != nullptr)
508 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
509 << T::GetFullyQualifiedName() << "\" } not found in config.";
510
Austin Schuhca4828c2019-12-28 14:21:35 -0800511 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
512 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
513 << "\", \"type\": \"" << T::GetFullyQualifiedName()
514 << "\" } is not able to be fetched on this node. Check your "
515 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800516 }
517
Alex Perrycb7da4b2019-08-28 19:35:56 -0700518 return Fetcher<T>(MakeRawFetcher(channel));
519 }
520
521 // Makes class that allows constructing and sending messages to
522 // the provided channel.
523 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800524 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuha0654152021-02-21 21:38:24 -0800525 const Channel *channel = GetChannel<T>(channel_name);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700526 CHECK(channel != nullptr)
527 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800528 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700529 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800530 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700531 ? absl::StrCat(" on node ", node()->name()->string_view())
532 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533
Austin Schuhca4828c2019-12-28 14:21:35 -0800534 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
535 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
536 << "\", \"type\": \"" << T::GetFullyQualifiedName()
537 << "\" } is not able to be sent on this node. Check your "
538 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800539 }
540
Alex Perrycb7da4b2019-08-28 19:35:56 -0700541 return Sender<T>(MakeRawSender(channel));
542 }
543
544 // This will watch messages sent to the provided channel.
545 //
Brian Silverman454bc112020-03-05 14:21:25 -0800546 // w must have a non-polymorphic operator() (aka it can only be called with a
547 // single set of arguments; no overloading or templates). It must be callable
548 // with this signature:
549 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550 //
Brian Silverman454bc112020-03-05 14:21:25 -0800551 // Lambdas are a common form for w. A std::function will work too.
552 //
553 // Note that bind expressions have polymorphic call operators, so they are not
554 // allowed.
555 //
556 // We template Watch as a whole instead of using std::function<void(const T
557 // &)> to allow deducing MessageType from lambdas and other things which are
558 // implicitly convertible to std::function, but not actually std::function
559 // instantiations. Template deduction guides might allow solving this
560 // differently in newer versions of C++, but those have their own corner
561 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800563 void MakeWatcher(const std::string_view channel_name, Watch &&w);
564
565 // Like MakeWatcher, but doesn't have access to the message data. This may be
566 // implemented to use less resources than an equivalent MakeWatcher.
567 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800568 // The function will still have access to context(), although that will have
569 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800570 template <typename MessageType>
571 void MakeNoArgWatcher(const std::string_view channel_name,
572 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700573
574 // The passed in function will be called when the event loop starts.
575 // Use this to run code once the thread goes into "real-time-mode",
576 virtual void OnRun(::std::function<void()> on_run) = 0;
577
Austin Schuh217a9782019-12-21 23:02:50 -0800578 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800579 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580
Austin Schuh217a9782019-12-21 23:02:50 -0800581 // Returns the node that this event loop is running on. Returns nullptr if we
582 // are running in single-node mode.
583 virtual const Node *node() const = 0;
584
Alex Perrycb7da4b2019-08-28 19:35:56 -0700585 // Creates a timer that executes callback when the timer expires
586 // Returns a TimerHandle for configuration of the timer
587 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
588
589 // Creates a timer that executes callback periodically at the specified
590 // interval and offset. Returns a PhasedLoopHandler for interacting with the
591 // timer.
592 virtual PhasedLoopHandler *AddPhasedLoop(
593 ::std::function<void(int)> callback,
594 const monotonic_clock::duration interval,
595 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
596
Austin Schuh217a9782019-12-21 23:02:50 -0800597 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598
599 // Threadsafe.
600 bool is_running() const { return is_running_.load(); }
601
602 // Sets the scheduler priority to run the event loop at. This may not be
603 // called after we go into "real-time-mode".
604 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800605 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700606
Brian Silverman6a54ff32020-04-28 16:41:39 -0700607 // Sets the scheduler affinity to run the event loop with. This may only be
608 // called before Run().
609 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
610
Austin Schuh217a9782019-12-21 23:02:50 -0800611 // Fetches new messages from the provided channel (path, type).
612 //
613 // Note: this channel must be a member of the exact configuration object this
614 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700615 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
616 const Channel *channel) = 0;
617
Austin Schuh217a9782019-12-21 23:02:50 -0800618 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700619 virtual void MakeRawWatcher(
620 const Channel *channel,
621 std::function<void(const Context &context, const void *message)>
622 watcher) = 0;
623
Brian Silverman454bc112020-03-05 14:21:25 -0800624 // Watches channel (name, type) for new messages, without needing to extract
625 // the message contents. Default implementation simply re-uses MakeRawWatcher.
626 virtual void MakeRawNoArgWatcher(
627 const Channel *channel,
628 std::function<void(const Context &context)> watcher) {
629 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800630 Context new_context = context;
631 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700632 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800633 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800634 });
635 }
636
Austin Schuh217a9782019-12-21 23:02:50 -0800637 // Creates a raw sender for the provided channel. This is used for reflection
638 // based sending.
639 // Note: this ignores any node constraints. Ignore at your own peril.
640 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
641
Austin Schuh6231cc32019-12-07 13:06:15 -0800642 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700643 const Context &context() const { return context_; }
644
645 // Returns the configuration that this event loop was built with.
646 const Configuration *configuration() const { return configuration_; }
647
Austin Schuh39788ff2019-12-01 18:22:57 -0800648 // Prevents the event loop from sending a timing report.
649 void SkipTimingReport() { skip_timing_report_ = true; }
650
Brian Silverman4f4e0612020-08-12 19:54:41 -0700651 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800652 void SkipAosLog() { skip_logger_ = true; }
653
Brian Silverman4f4e0612020-08-12 19:54:41 -0700654 // Returns the number of buffers for this channel. This corresponds with the
655 // range of Context::buffer_index values for this channel.
656 virtual int NumberBuffers(const Channel *channel) = 0;
657
Austin Schuh20ac95d2020-12-05 17:24:19 -0800658 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800659 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800660
Alex Perrycb7da4b2019-08-28 19:35:56 -0700661 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800662 // Sets the name of the event loop. This is the application name.
663 virtual void set_name(const std::string_view name) = 0;
664
Alex Perrycb7da4b2019-08-28 19:35:56 -0700665 void set_is_running(bool value) { is_running_.store(value); }
666
Austin Schuh39788ff2019-12-01 18:22:57 -0800667 // Validates that channel exists inside configuration_ and finds its index.
668 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700669
Brian Silverman5120afb2020-01-31 17:44:35 -0800670 // Returns the state for the watcher on the corresponding channel. This
671 // watcher must exist before calling this.
672 WatcherState *GetWatcherState(const Channel *channel);
673
Brian Silverman6d2b3592020-06-18 14:40:15 -0700674 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800675 template <typename T>
676 static RawSender *GetRawSender(aos::Sender<T> *sender) {
677 return sender->sender_.get();
678 }
679
Brian Silverman6d2b3592020-06-18 14:40:15 -0700680 // Returns a Fetcher's protected RawFetcher.
681 template <typename T>
682 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
683 return fetcher->fetcher_.get();
684 }
685
Austin Schuh6231cc32019-12-07 13:06:15 -0800686 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700687 Context context_;
688
Austin Schuh39788ff2019-12-01 18:22:57 -0800689 friend class RawSender;
690 friend class TimerHandler;
691 friend class RawFetcher;
692 friend class PhasedLoopHandler;
693 friend class WatcherState;
694
695 // Methods used to implement timing reports.
696 void NewSender(RawSender *sender);
697 void DeleteSender(RawSender *sender);
698 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
699 PhasedLoopHandler *NewPhasedLoop(
700 std::unique_ptr<PhasedLoopHandler> phased_loop);
701 void NewFetcher(RawFetcher *fetcher);
702 void DeleteFetcher(RawFetcher *fetcher);
703 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
704
Brian Silverman0fc69932020-01-24 21:54:02 -0800705 // Tracks that we have a (single) watcher on the given channel.
706 void TakeWatcher(const Channel *channel);
707 // Tracks that we have at least one sender on the given channel.
708 void TakeSender(const Channel *channel);
709
Austin Schuh39788ff2019-12-01 18:22:57 -0800710 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800711 std::vector<RawFetcher *> fetchers_;
712
Austin Schuh39788ff2019-12-01 18:22:57 -0800713 std::vector<std::unique_ptr<TimerHandler>> timers_;
714 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800715 std::vector<std::unique_ptr<WatcherState>> watchers_;
716
717 void SendTimingReport();
718 void UpdateTimingReport();
719 void MaybeScheduleTimingReports();
720
721 std::unique_ptr<RawSender> timing_report_sender_;
722
Austin Schuh7d87b672019-12-01 20:23:49 -0800723 // Tracks which event sources (timers and watchers) have data, and which
724 // don't. Added events may not change their event_time().
725 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
726 // t2 to run, t2 should then be picked up without a context switch.
727 void AddEvent(EventLoopEvent *event);
728 void RemoveEvent(EventLoopEvent *event);
729 size_t EventCount() const { return events_.size(); }
730 EventLoopEvent *PopEvent();
731 EventLoopEvent *PeekEvent() { return events_.front(); }
732 void ReserveEvents();
733
734 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700735 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800736
Tyler Chatow67ddb032020-01-12 14:30:04 -0800737 // If true, don't send AOS_LOG to /aos
738 bool skip_logger_ = false;
739
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800740 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800741 virtual pid_t GetTid() = 0;
742
743 FlatbufferDetachedBuffer<timing::Report> timing_report_;
744
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800745 ::std::atomic<bool> is_running_{false};
746
Alex Perrycb7da4b2019-08-28 19:35:56 -0700747 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800748
749 // If true, don't send out timing reports.
750 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800751
752 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700753};
754
755} // namespace aos
756
Austin Schuhb8075812020-10-19 09:36:49 -0700757#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700758
759#endif // AOS_EVENTS_EVENT_LOOP_H