blob: 6ffb0fe2fa2e9c6427119d09ff68f5705bf95c86 [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"
Brian Silverman0fc69932020-01-24 21:54:02 -080022
23#include "absl/container/btree_set.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 Schuh678078e2020-08-01 14:30:36 -070077 // Efficiently coppies the flatbuffer into a FlatbufferVector, allocating
78 // memory in the process. It is vital that T matches the type of the
79 // underlying flatbuffer.
80 template <typename T>
81 FlatbufferVector<T> CopyFlatBuffer() const {
Brian Silverman354697a2020-09-22 21:06:32 -070082 ResizeableBuffer buffer;
83 buffer.resize(size);
84 memcpy(buffer.data(), data, size);
85 return FlatbufferVector<T>(std::move(buffer));
Austin Schuh678078e2020-08-01 14:30:36 -070086 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070087};
88
89// Raw version of fetcher. Contains a local variable that the fetcher will
90// update. This is used for reflection and as an interface to implement typed
91// fetchers.
92class RawFetcher {
93 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080094 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070095 RawFetcher(const RawFetcher &) = delete;
96 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080097 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070098
Austin Schuh39788ff2019-12-01 18:22:57 -080099 // Fetches the next message in the queue without blocking. Returns true if
100 // there was a new message and we got it.
101 bool FetchNext();
102
103 // Fetches the latest message without blocking.
104 bool Fetch();
105
106 // Returns the channel this fetcher uses.
107 const Channel *channel() const { return channel_; }
108 // Returns the context for the current message.
109 const Context &context() const { return context_; }
110
111 protected:
112 EventLoop *event_loop() { return event_loop_; }
113
Alex Perrycb7da4b2019-08-28 19:35:56 -0700114 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800115
116 private:
117 friend class EventLoop;
118 // Implementation
119 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
120 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
121
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500122 EventLoop *const event_loop_;
123 const Channel *const channel_;
124 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800125
126 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500127 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700128};
129
130// Raw version of sender. Sends a block of data. This is used for reflection
131// and as a building block to implement typed senders.
132class RawSender {
133 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800134 RawSender(EventLoop *event_loop, const Channel *channel);
135 RawSender(const RawSender &) = delete;
136 RawSender &operator=(const RawSender &) = delete;
137
138 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700139
140 // Sends a message without copying it. The users starts by copying up to
141 // size() bytes into the data backed by data(). They then call Send to send.
142 // Returns true on a successful send.
Austin Schuhad154822019-12-27 15:45:13 -0800143 // If provided, monotonic_remote_time, realtime_remote_time, and
144 // remote_queue_index are attached to the message and are available in the
145 // context on the read side. If they are not populated, the read side will
146 // get the sent times instead.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700147 virtual void *data() = 0;
148 virtual size_t size() = 0;
Austin Schuhad154822019-12-27 15:45:13 -0800149 bool Send(size_t size,
150 aos::monotonic_clock::time_point monotonic_remote_time =
151 aos::monotonic_clock::min_time,
152 aos::realtime_clock::time_point realtime_remote_time =
153 aos::realtime_clock::min_time,
154 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700155
156 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800157 // The remote arguments have the same meaning as in Send above.
158 bool Send(const void *data, size_t size,
159 aos::monotonic_clock::time_point monotonic_remote_time =
160 aos::monotonic_clock::min_time,
161 aos::realtime_clock::time_point realtime_remote_time =
162 aos::realtime_clock::min_time,
163 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164
Austin Schuh54cf95f2019-11-29 13:14:18 -0800165 const Channel *channel() const { return channel_; }
166
Austin Schuhad154822019-12-27 15:45:13 -0800167 // Returns the time_points that the last message was sent at.
168 aos::monotonic_clock::time_point monotonic_sent_time() const {
169 return monotonic_sent_time_;
170 }
171 aos::realtime_clock::time_point realtime_sent_time() const {
172 return realtime_sent_time_;
173 }
174 // Returns the queue index that this was sent with.
175 uint32_t sent_queue_index() const { return sent_queue_index_; }
176
Brian Silvermana1652f32020-01-29 20:41:44 -0800177 // Returns the associated flatbuffers-style allocator. This must be
178 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800179 ChannelPreallocatedAllocator *fbb_allocator() {
180 fbb_allocator_ = ChannelPreallocatedAllocator(
181 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800182 return &fbb_allocator_;
183 }
184
Brian Silverman4f4e0612020-08-12 19:54:41 -0700185 // Index of the buffer which is currently exposed by data() and the various
186 // other accessors. This is the message the caller should be filling out.
187 virtual int buffer_index() = 0;
188
Alex Perrycb7da4b2019-08-28 19:35:56 -0700189 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800190 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800191
Austin Schuhad154822019-12-27 15:45:13 -0800192 aos::monotonic_clock::time_point monotonic_sent_time_ =
193 aos::monotonic_clock::min_time;
194 aos::realtime_clock::time_point realtime_sent_time_ =
195 aos::realtime_clock::min_time;
196 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,
202 aos::monotonic_clock::time_point monotonic_remote_time,
203 aos::realtime_clock::time_point realtime_remote_time,
204 uint32_t remote_queue_index) = 0;
205 virtual bool DoSend(size_t size,
206 aos::monotonic_clock::time_point monotonic_remote_time,
207 aos::realtime_clock::time_point realtime_remote_time,
208 uint32_t remote_queue_index) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800209
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500210 EventLoop *const event_loop_;
211 const Channel *const channel_;
212 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700213
Austin Schuh39788ff2019-12-01 18:22:57 -0800214 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500215 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800216
Austin Schuh1af273d2020-03-07 20:11:34 -0800217 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800218};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700219
220// Fetches the newest message from a channel.
221// This provides a polling based interface for channels.
222template <typename T>
223class Fetcher {
224 public:
225 Fetcher() {}
226
227 // Fetches the next message. Returns true if it fetched a new message. This
228 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800229 bool FetchNext() {
230 const bool result = fetcher_->FetchNext();
231 if (result) {
232 CheckChannelDataAlignment(fetcher_->context().data,
233 fetcher_->context().size);
234 }
235 return result;
236 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700237
238 // Fetches the most recent message. Returns true if it fetched a new message.
239 // This will return the latest message regardless of if it was sent before or
240 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800241 bool Fetch() {
242 const bool result = fetcher_->Fetch();
243 if (result) {
244 CheckChannelDataAlignment(fetcher_->context().data,
245 fetcher_->context().size);
246 }
247 return result;
248 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700249
250 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
251 // available message.
252 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800253 return fetcher_->context().data != nullptr
254 ? flatbuffers::GetRoot<T>(
255 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256 : nullptr;
257 }
258
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700259 // Returns the channel this fetcher uses
260 const Channel *channel() const { return fetcher_->channel(); }
261
Alex Perrycb7da4b2019-08-28 19:35:56 -0700262 // Returns the context holding timestamps and other metadata about the
263 // message.
264 const Context &context() const { return fetcher_->context(); }
265
266 const T &operator*() const { return *get(); }
267 const T *operator->() const { return get(); }
268
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700269 // Returns true if this fetcher is valid and connected to a channel.
270 operator bool() const { return static_cast<bool>(fetcher_); }
271
Alex Perrycb7da4b2019-08-28 19:35:56 -0700272 private:
273 friend class EventLoop;
274 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
275 : fetcher_(::std::move(fetcher)) {}
276 ::std::unique_ptr<RawFetcher> fetcher_;
277};
278
279// Sends messages to a channel.
280template <typename T>
281class Sender {
282 public:
283 Sender() {}
284
285 // Represents a single message about to be sent to the queue.
286 // The lifecycle goes:
287 //
288 // Builder builder = sender.MakeBuilder();
289 // T::Builder t_builder = builder.MakeBuilder<T>();
290 // Populate(&t_builder);
291 // builder.Send(t_builder.Finish());
292 class Builder {
293 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800294 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800295 : fbb_(allocator->size(), allocator),
296 allocator_(allocator),
297 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800298 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800299 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700300 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800301 Builder() {}
302 Builder(const Builder &) = delete;
303 Builder(Builder &&) = default;
304
305 Builder &operator=(const Builder &) = delete;
306 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307
308 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
309
310 template <typename T2>
311 typename T2::Builder MakeBuilder() {
312 return typename T2::Builder(fbb_);
313 }
314
315 bool Send(flatbuffers::Offset<T> offset) {
316 fbb_.Finish(offset);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800317 const bool result = sender_->Send(fbb_.GetSize());
318 // Ensure fbb_ knows it shouldn't access the memory any more.
319 fbb_ = flatbuffers::FlatBufferBuilder();
320 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700321 }
322
323 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800324 void CheckSent() {
325 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
326 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327
Brian Silverman341b57e2020-06-23 16:23:18 -0700328 // Detaches a buffer, for later use calling Sender::Send directly.
329 //
330 // Note that the underlying memory remains with the Sender, so creating
331 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
332 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
333 fbb_.Finish(offset);
334 return fbb_.Release();
335 }
336
Alex Perrycb7da4b2019-08-28 19:35:56 -0700337 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700338 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800339 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700340 RawSender *sender_;
341 };
342
343 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800344 //
345 // Only a single one of these may be "alive" for this object at any point in
346 // time. After calling Send on the result, it is no longer "alive". This means
347 // that you must manually reset a variable holding the return value (by
348 // assigning a default-constructed Builder to it) before calling this method
349 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700350 Builder MakeBuilder();
351
Austin Schuha28cbc32019-12-27 16:28:04 -0800352 // Sends a prebuilt flatbuffer.
353 bool Send(const Flatbuffer<T> &flatbuffer);
354
Brian Silverman341b57e2020-06-23 16:23:18 -0700355 // Sends a prebuilt flatbuffer which was detached from a Builder created via
356 // MakeBuilder() on this object.
357 bool SendDetached(FlatbufferDetachedBuffer<T> detached);
358
Austin Schuh39788ff2019-12-01 18:22:57 -0800359 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800360 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700361
Austin Schuha0c41ba2020-09-10 22:59:14 -0700362 operator bool() const { return sender_ ? true : false; }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800363
Austin Schuh7bc59052020-02-16 23:48:33 -0800364 // Returns the time_points that the last message was sent at.
365 aos::monotonic_clock::time_point monotonic_sent_time() const {
366 return sender_->monotonic_sent_time();
367 }
368 aos::realtime_clock::time_point realtime_sent_time() const {
369 return sender_->realtime_sent_time();
370 }
371 // Returns the queue index that this was sent with.
372 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
373
Brian Silverman4f4e0612020-08-12 19:54:41 -0700374 // Returns the buffer index which MakeBuilder() will expose access to. This is
375 // the buffer the caller can fill out.
376 int buffer_index() const { return sender_->buffer_index(); }
377
Alex Perrycb7da4b2019-08-28 19:35:56 -0700378 private:
379 friend class EventLoop;
380 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
381 std::unique_ptr<RawSender> sender_;
382};
383
Brian Silverman4f4e0612020-08-12 19:54:41 -0700384// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385class TimerHandler {
386 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800387 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700388
389 // Timer should sleep until base, base + offset, base + offset * 2, ...
390 // If repeat_offset isn't set, the timer only expires once.
391 virtual void Setup(monotonic_clock::time_point base,
392 monotonic_clock::duration repeat_offset =
393 ::aos::monotonic_clock::zero()) = 0;
394
395 // Stop future calls to callback().
396 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800397
398 // Sets and gets the name of the timer. Set this if you want a descriptive
399 // name in the timing report.
400 void set_name(std::string_view name) { name_ = std::string(name); }
401 const std::string_view name() const { return name_; }
402
Austin Schuh39788ff2019-12-01 18:22:57 -0800403 protected:
404 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
405
Austin Schuhcde39fd2020-02-22 20:58:24 -0800406 monotonic_clock::time_point Call(
407 std::function<monotonic_clock::time_point()> get_time,
408 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800409
Austin Schuh1540c2f2019-11-29 21:59:29 -0800410 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800411 friend class EventLoop;
412
413 EventLoop *event_loop_;
414 // The function to call when Call is called.
415 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800416 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800417
418 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500419 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420};
421
422// Interface for phased loops. They are built on timers.
423class PhasedLoopHandler {
424 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800425 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426
427 // Sets the interval and offset. Any changes to interval and offset only take
428 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800429 void set_interval_and_offset(const monotonic_clock::duration interval,
430 const monotonic_clock::duration offset) {
431 phased_loop_.set_interval_and_offset(interval, offset);
432 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800433
434 // Sets and gets the name of the timer. Set this if you want a descriptive
435 // name in the timing report.
436 void set_name(std::string_view name) { name_ = std::string(name); }
437 const std::string_view name() const { return name_; }
438
Austin Schuh39788ff2019-12-01 18:22:57 -0800439 protected:
440 void Call(std::function<monotonic_clock::time_point()> get_time,
441 std::function<void(monotonic_clock::time_point)> schedule);
442
443 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
444 const monotonic_clock::duration interval,
445 const monotonic_clock::duration offset);
446
Austin Schuh1540c2f2019-11-29 21:59:29 -0800447 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800448 friend class EventLoop;
449
450 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
451 monotonic_clock::time_point monotonic_now) {
452 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
453 schedule(phased_loop_.sleep_time());
454 }
455
456 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
457
458 EventLoop *event_loop_;
459 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800460 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800461 time::PhasedLoop phased_loop_;
462
463 int cycles_elapsed_ = 0;
464
465 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500466 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467};
468
Brian Silverman6a54ff32020-04-28 16:41:39 -0700469inline cpu_set_t MakeCpusetFromCpus(std::initializer_list<int> cpus) {
470 cpu_set_t result;
471 CPU_ZERO(&result);
472 for (int cpu : cpus) {
473 CPU_SET(cpu, &result);
474 }
475 return result;
476}
477
Alex Perrycb7da4b2019-08-28 19:35:56 -0700478class EventLoop {
479 public:
Tyler Chatow67ddb032020-01-12 14:30:04 -0800480 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481
Austin Schuh39788ff2019-12-01 18:22:57 -0800482 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483
484 // Current time.
485 virtual monotonic_clock::time_point monotonic_now() = 0;
486 virtual realtime_clock::time_point realtime_now() = 0;
487
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700488 // Returns true if the channel exists in the configuration.
489 template <typename T>
490 bool HasChannel(const std::string_view channel_name) {
491 return configuration::GetChannel(configuration_, channel_name,
492 T::GetFullyQualifiedName(), name(),
493 node()) != nullptr;
494 }
495
Alex Perrycb7da4b2019-08-28 19:35:56 -0700496 // Note, it is supported to create:
497 // multiple fetchers, and (one sender or one watcher) per <name, type>
498 // tuple.
499
500 // Makes a class that will always fetch the most recent value
501 // sent to the provided channel.
502 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800503 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800504 const Channel *channel =
505 configuration::GetChannel(configuration_, channel_name,
506 T::GetFullyQualifiedName(), name(), node());
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 Schuhbca6cf02019-12-22 17:28:34 -0800525 const Channel *channel =
526 configuration::GetChannel(configuration_, channel_name,
527 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700528 CHECK(channel != nullptr)
529 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800530 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700531 << name()
532 << (configuration::MultiNode(configuration_)
533 ? absl::StrCat(" on node ", node()->name()->string_view())
534 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535
Austin Schuhca4828c2019-12-28 14:21:35 -0800536 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
537 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
538 << "\", \"type\": \"" << T::GetFullyQualifiedName()
539 << "\" } is not able to be sent on this node. Check your "
540 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800541 }
542
Alex Perrycb7da4b2019-08-28 19:35:56 -0700543 return Sender<T>(MakeRawSender(channel));
544 }
545
546 // This will watch messages sent to the provided channel.
547 //
Brian Silverman454bc112020-03-05 14:21:25 -0800548 // w must have a non-polymorphic operator() (aka it can only be called with a
549 // single set of arguments; no overloading or templates). It must be callable
550 // with this signature:
551 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 //
Brian Silverman454bc112020-03-05 14:21:25 -0800553 // Lambdas are a common form for w. A std::function will work too.
554 //
555 // Note that bind expressions have polymorphic call operators, so they are not
556 // allowed.
557 //
558 // We template Watch as a whole instead of using std::function<void(const T
559 // &)> to allow deducing MessageType from lambdas and other things which are
560 // implicitly convertible to std::function, but not actually std::function
561 // instantiations. Template deduction guides might allow solving this
562 // differently in newer versions of C++, but those have their own corner
563 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700564 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800565 void MakeWatcher(const std::string_view channel_name, Watch &&w);
566
567 // Like MakeWatcher, but doesn't have access to the message data. This may be
568 // implemented to use less resources than an equivalent MakeWatcher.
569 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800570 // The function will still have access to context(), although that will have
571 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800572 template <typename MessageType>
573 void MakeNoArgWatcher(const std::string_view channel_name,
574 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700575
576 // The passed in function will be called when the event loop starts.
577 // Use this to run code once the thread goes into "real-time-mode",
578 virtual void OnRun(::std::function<void()> on_run) = 0;
579
Austin Schuh217a9782019-12-21 23:02:50 -0800580 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800581 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700582
Austin Schuh217a9782019-12-21 23:02:50 -0800583 // Returns the node that this event loop is running on. Returns nullptr if we
584 // are running in single-node mode.
585 virtual const Node *node() const = 0;
586
Alex Perrycb7da4b2019-08-28 19:35:56 -0700587 // Creates a timer that executes callback when the timer expires
588 // Returns a TimerHandle for configuration of the timer
589 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
590
591 // Creates a timer that executes callback periodically at the specified
592 // interval and offset. Returns a PhasedLoopHandler for interacting with the
593 // timer.
594 virtual PhasedLoopHandler *AddPhasedLoop(
595 ::std::function<void(int)> callback,
596 const monotonic_clock::duration interval,
597 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
598
Austin Schuh217a9782019-12-21 23:02:50 -0800599 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700600
601 // Threadsafe.
602 bool is_running() const { return is_running_.load(); }
603
604 // Sets the scheduler priority to run the event loop at. This may not be
605 // called after we go into "real-time-mode".
606 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800607 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700608
Brian Silverman6a54ff32020-04-28 16:41:39 -0700609 // Sets the scheduler affinity to run the event loop with. This may only be
610 // called before Run().
611 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
612
Austin Schuh217a9782019-12-21 23:02:50 -0800613 // Fetches new messages from the provided channel (path, type).
614 //
615 // Note: this channel must be a member of the exact configuration object this
616 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
618 const Channel *channel) = 0;
619
Austin Schuh217a9782019-12-21 23:02:50 -0800620 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700621 virtual void MakeRawWatcher(
622 const Channel *channel,
623 std::function<void(const Context &context, const void *message)>
624 watcher) = 0;
625
Brian Silverman454bc112020-03-05 14:21:25 -0800626 // Watches channel (name, type) for new messages, without needing to extract
627 // the message contents. Default implementation simply re-uses MakeRawWatcher.
628 virtual void MakeRawNoArgWatcher(
629 const Channel *channel,
630 std::function<void(const Context &context)> watcher) {
631 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800632 Context new_context = context;
633 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700634 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800635 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800636 });
637 }
638
Austin Schuh217a9782019-12-21 23:02:50 -0800639 // Creates a raw sender for the provided channel. This is used for reflection
640 // based sending.
641 // Note: this ignores any node constraints. Ignore at your own peril.
642 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
643
Austin Schuh6231cc32019-12-07 13:06:15 -0800644 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645 const Context &context() const { return context_; }
646
647 // Returns the configuration that this event loop was built with.
648 const Configuration *configuration() const { return configuration_; }
649
Austin Schuh39788ff2019-12-01 18:22:57 -0800650 // Prevents the event loop from sending a timing report.
651 void SkipTimingReport() { skip_timing_report_ = true; }
652
Brian Silverman4f4e0612020-08-12 19:54:41 -0700653 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800654 void SkipAosLog() { skip_logger_ = true; }
655
Brian Silverman4f4e0612020-08-12 19:54:41 -0700656 // Returns the number of buffers for this channel. This corresponds with the
657 // range of Context::buffer_index values for this channel.
658 virtual int NumberBuffers(const Channel *channel) = 0;
659
Alex Perrycb7da4b2019-08-28 19:35:56 -0700660 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800661 // Sets the name of the event loop. This is the application name.
662 virtual void set_name(const std::string_view name) = 0;
663
Alex Perrycb7da4b2019-08-28 19:35:56 -0700664 void set_is_running(bool value) { is_running_.store(value); }
665
Austin Schuh39788ff2019-12-01 18:22:57 -0800666 // Validates that channel exists inside configuration_ and finds its index.
667 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700668
Brian Silverman5120afb2020-01-31 17:44:35 -0800669 // Returns the state for the watcher on the corresponding channel. This
670 // watcher must exist before calling this.
671 WatcherState *GetWatcherState(const Channel *channel);
672
Brian Silverman6d2b3592020-06-18 14:40:15 -0700673 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800674 template <typename T>
675 static RawSender *GetRawSender(aos::Sender<T> *sender) {
676 return sender->sender_.get();
677 }
678
Brian Silverman6d2b3592020-06-18 14:40:15 -0700679 // Returns a Fetcher's protected RawFetcher.
680 template <typename T>
681 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
682 return fetcher->fetcher_.get();
683 }
684
Austin Schuh6231cc32019-12-07 13:06:15 -0800685 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700686 Context context_;
687
Austin Schuh39788ff2019-12-01 18:22:57 -0800688 friend class RawSender;
689 friend class TimerHandler;
690 friend class RawFetcher;
691 friend class PhasedLoopHandler;
692 friend class WatcherState;
693
694 // Methods used to implement timing reports.
695 void NewSender(RawSender *sender);
696 void DeleteSender(RawSender *sender);
697 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
698 PhasedLoopHandler *NewPhasedLoop(
699 std::unique_ptr<PhasedLoopHandler> phased_loop);
700 void NewFetcher(RawFetcher *fetcher);
701 void DeleteFetcher(RawFetcher *fetcher);
702 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
703
Brian Silverman0fc69932020-01-24 21:54:02 -0800704 // Tracks that we have a (single) watcher on the given channel.
705 void TakeWatcher(const Channel *channel);
706 // Tracks that we have at least one sender on the given channel.
707 void TakeSender(const Channel *channel);
708
Austin Schuh39788ff2019-12-01 18:22:57 -0800709 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800710 std::vector<RawFetcher *> fetchers_;
711
Austin Schuh39788ff2019-12-01 18:22:57 -0800712 std::vector<std::unique_ptr<TimerHandler>> timers_;
713 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800714 std::vector<std::unique_ptr<WatcherState>> watchers_;
715
716 void SendTimingReport();
717 void UpdateTimingReport();
718 void MaybeScheduleTimingReports();
719
720 std::unique_ptr<RawSender> timing_report_sender_;
721
Austin Schuh7d87b672019-12-01 20:23:49 -0800722 // Tracks which event sources (timers and watchers) have data, and which
723 // don't. Added events may not change their event_time().
724 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
725 // t2 to run, t2 should then be picked up without a context switch.
726 void AddEvent(EventLoopEvent *event);
727 void RemoveEvent(EventLoopEvent *event);
728 size_t EventCount() const { return events_.size(); }
729 EventLoopEvent *PopEvent();
730 EventLoopEvent *PeekEvent() { return events_.front(); }
731 void ReserveEvents();
732
733 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700734 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800735
Tyler Chatow67ddb032020-01-12 14:30:04 -0800736 // If true, don't send AOS_LOG to /aos
737 bool skip_logger_ = false;
738
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800739 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800740 virtual pid_t GetTid() = 0;
741
742 FlatbufferDetachedBuffer<timing::Report> timing_report_;
743
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800744 ::std::atomic<bool> is_running_{false};
745
Alex Perrycb7da4b2019-08-28 19:35:56 -0700746 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800747
748 // If true, don't send out timing reports.
749 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800750
751 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700752};
753
754} // namespace aos
755
756#include "aos/events/event_loop_tmpl.h"
757
758#endif // AOS_EVENTS_EVENT_LOOP_H