blob: fa7895388f825d10792ce37f07d366c1e8768b92 [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.
Alex Perrycb7da4b2019-08-28 19:35:56 -070051 // Index in the queue.
52 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080053 // Index into the remote queue. Useful to determine if data was lost. In a
54 // single-node configuration, this will match queue_index.
55 uint32_t remote_queue_index;
56
Alex Perrycb7da4b2019-08-28 19:35:56 -070057 // Size of the data sent.
58 size_t size;
59 // Pointer to the data.
Brian Silvermaneaa41d62020-07-08 19:47:35 -070060 const void *data;
Austin Schuh678078e2020-08-01 14:30:36 -070061
62 // Efficiently coppies the flatbuffer into a FlatbufferVector, allocating
63 // memory in the process. It is vital that T matches the type of the
64 // underlying flatbuffer.
65 template <typename T>
66 FlatbufferVector<T> CopyFlatBuffer() const {
67 return FlatbufferVector<T>(
68 std::vector<uint8_t>(reinterpret_cast<const uint8_t *>(data),
69 reinterpret_cast<const uint8_t *>(data) + size));
70 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070071};
72
73// Raw version of fetcher. Contains a local variable that the fetcher will
74// update. This is used for reflection and as an interface to implement typed
75// fetchers.
76class RawFetcher {
77 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080078 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070079 RawFetcher(const RawFetcher &) = delete;
80 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080081 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070082
Austin Schuh39788ff2019-12-01 18:22:57 -080083 // Fetches the next message in the queue without blocking. Returns true if
84 // there was a new message and we got it.
85 bool FetchNext();
86
87 // Fetches the latest message without blocking.
88 bool Fetch();
89
90 // Returns the channel this fetcher uses.
91 const Channel *channel() const { return channel_; }
92 // Returns the context for the current message.
93 const Context &context() const { return context_; }
94
95 protected:
96 EventLoop *event_loop() { return event_loop_; }
97
Alex Perrycb7da4b2019-08-28 19:35:56 -070098 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080099
100 private:
101 friend class EventLoop;
102 // Implementation
103 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
104 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
105
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500106 EventLoop *const event_loop_;
107 const Channel *const channel_;
108 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800109
110 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500111 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700112};
113
114// Raw version of sender. Sends a block of data. This is used for reflection
115// and as a building block to implement typed senders.
116class RawSender {
117 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800118 RawSender(EventLoop *event_loop, const Channel *channel);
119 RawSender(const RawSender &) = delete;
120 RawSender &operator=(const RawSender &) = delete;
121
122 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700123
124 // Sends a message without copying it. The users starts by copying up to
125 // size() bytes into the data backed by data(). They then call Send to send.
126 // Returns true on a successful send.
Austin Schuhad154822019-12-27 15:45:13 -0800127 // If provided, monotonic_remote_time, realtime_remote_time, and
128 // remote_queue_index are attached to the message and are available in the
129 // context on the read side. If they are not populated, the read side will
130 // get the sent times instead.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700131 virtual void *data() = 0;
132 virtual size_t size() = 0;
Austin Schuhad154822019-12-27 15:45:13 -0800133 bool Send(size_t size,
134 aos::monotonic_clock::time_point monotonic_remote_time =
135 aos::monotonic_clock::min_time,
136 aos::realtime_clock::time_point realtime_remote_time =
137 aos::realtime_clock::min_time,
138 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700139
140 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800141 // The remote arguments have the same meaning as in Send above.
142 bool Send(const void *data, size_t size,
143 aos::monotonic_clock::time_point monotonic_remote_time =
144 aos::monotonic_clock::min_time,
145 aos::realtime_clock::time_point realtime_remote_time =
146 aos::realtime_clock::min_time,
147 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700148
Austin Schuh54cf95f2019-11-29 13:14:18 -0800149 const Channel *channel() const { return channel_; }
150
Austin Schuhad154822019-12-27 15:45:13 -0800151 // Returns the time_points that the last message was sent at.
152 aos::monotonic_clock::time_point monotonic_sent_time() const {
153 return monotonic_sent_time_;
154 }
155 aos::realtime_clock::time_point realtime_sent_time() const {
156 return realtime_sent_time_;
157 }
158 // Returns the queue index that this was sent with.
159 uint32_t sent_queue_index() const { return sent_queue_index_; }
160
Brian Silvermana1652f32020-01-29 20:41:44 -0800161 // Returns the associated flatbuffers-style allocator. This must be
162 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800163 ChannelPreallocatedAllocator *fbb_allocator() {
164 fbb_allocator_ = ChannelPreallocatedAllocator(
165 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800166 return &fbb_allocator_;
167 }
168
Alex Perrycb7da4b2019-08-28 19:35:56 -0700169 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800170 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800171
Austin Schuhad154822019-12-27 15:45:13 -0800172 aos::monotonic_clock::time_point monotonic_sent_time_ =
173 aos::monotonic_clock::min_time;
174 aos::realtime_clock::time_point realtime_sent_time_ =
175 aos::realtime_clock::min_time;
176 uint32_t sent_queue_index_ = 0xffffffff;
177
Austin Schuh39788ff2019-12-01 18:22:57 -0800178 private:
179 friend class EventLoop;
180
Austin Schuhad154822019-12-27 15:45:13 -0800181 virtual bool DoSend(const void *data, size_t size,
182 aos::monotonic_clock::time_point monotonic_remote_time,
183 aos::realtime_clock::time_point realtime_remote_time,
184 uint32_t remote_queue_index) = 0;
185 virtual bool DoSend(size_t size,
186 aos::monotonic_clock::time_point monotonic_remote_time,
187 aos::realtime_clock::time_point realtime_remote_time,
188 uint32_t remote_queue_index) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800189
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500190 EventLoop *const event_loop_;
191 const Channel *const channel_;
192 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700193
Austin Schuh39788ff2019-12-01 18:22:57 -0800194 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500195 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800196
Austin Schuh1af273d2020-03-07 20:11:34 -0800197 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800198};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700199
200// Fetches the newest message from a channel.
201// This provides a polling based interface for channels.
202template <typename T>
203class Fetcher {
204 public:
205 Fetcher() {}
206
207 // Fetches the next message. Returns true if it fetched a new message. This
208 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800209 bool FetchNext() {
210 const bool result = fetcher_->FetchNext();
211 if (result) {
212 CheckChannelDataAlignment(fetcher_->context().data,
213 fetcher_->context().size);
214 }
215 return result;
216 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217
218 // Fetches the most recent message. Returns true if it fetched a new message.
219 // This will return the latest message regardless of if it was sent before or
220 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800221 bool Fetch() {
222 const bool result = fetcher_->Fetch();
223 if (result) {
224 CheckChannelDataAlignment(fetcher_->context().data,
225 fetcher_->context().size);
226 }
227 return result;
228 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700229
230 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
231 // available message.
232 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800233 return fetcher_->context().data != nullptr
234 ? flatbuffers::GetRoot<T>(
235 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700236 : nullptr;
237 }
238
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700239 // Returns the channel this fetcher uses
240 const Channel *channel() const { return fetcher_->channel(); }
241
Alex Perrycb7da4b2019-08-28 19:35:56 -0700242 // Returns the context holding timestamps and other metadata about the
243 // message.
244 const Context &context() const { return fetcher_->context(); }
245
246 const T &operator*() const { return *get(); }
247 const T *operator->() const { return get(); }
248
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700249 // Returns true if this fetcher is valid and connected to a channel.
250 operator bool() const { return static_cast<bool>(fetcher_); }
251
Alex Perrycb7da4b2019-08-28 19:35:56 -0700252 private:
253 friend class EventLoop;
254 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
255 : fetcher_(::std::move(fetcher)) {}
256 ::std::unique_ptr<RawFetcher> fetcher_;
257};
258
259// Sends messages to a channel.
260template <typename T>
261class Sender {
262 public:
263 Sender() {}
264
265 // Represents a single message about to be sent to the queue.
266 // The lifecycle goes:
267 //
268 // Builder builder = sender.MakeBuilder();
269 // T::Builder t_builder = builder.MakeBuilder<T>();
270 // Populate(&t_builder);
271 // builder.Send(t_builder.Finish());
272 class Builder {
273 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800274 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800275 : fbb_(allocator->size(), allocator),
276 allocator_(allocator),
277 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800278 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800279 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700280 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800281 Builder() {}
282 Builder(const Builder &) = delete;
283 Builder(Builder &&) = default;
284
285 Builder &operator=(const Builder &) = delete;
286 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700287
288 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
289
290 template <typename T2>
291 typename T2::Builder MakeBuilder() {
292 return typename T2::Builder(fbb_);
293 }
294
295 bool Send(flatbuffers::Offset<T> offset) {
296 fbb_.Finish(offset);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800297 const bool result = sender_->Send(fbb_.GetSize());
298 // Ensure fbb_ knows it shouldn't access the memory any more.
299 fbb_ = flatbuffers::FlatBufferBuilder();
300 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700301 }
302
303 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800304 void CheckSent() {
305 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
306 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307
Brian Silverman341b57e2020-06-23 16:23:18 -0700308 // Detaches a buffer, for later use calling Sender::Send directly.
309 //
310 // Note that the underlying memory remains with the Sender, so creating
311 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
312 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
313 fbb_.Finish(offset);
314 return fbb_.Release();
315 }
316
Alex Perrycb7da4b2019-08-28 19:35:56 -0700317 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700318 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800319 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 RawSender *sender_;
321 };
322
323 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800324 //
325 // Only a single one of these may be "alive" for this object at any point in
326 // time. After calling Send on the result, it is no longer "alive". This means
327 // that you must manually reset a variable holding the return value (by
328 // assigning a default-constructed Builder to it) before calling this method
329 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700330 Builder MakeBuilder();
331
Austin Schuha28cbc32019-12-27 16:28:04 -0800332 // Sends a prebuilt flatbuffer.
333 bool Send(const Flatbuffer<T> &flatbuffer);
334
Brian Silverman341b57e2020-06-23 16:23:18 -0700335 // Sends a prebuilt flatbuffer which was detached from a Builder created via
336 // MakeBuilder() on this object.
337 bool SendDetached(FlatbufferDetachedBuffer<T> detached);
338
Austin Schuh39788ff2019-12-01 18:22:57 -0800339 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800340 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700341
Brian Silverman454bc112020-03-05 14:21:25 -0800342 operator bool() { return sender_ ? true : false; }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800343
Austin Schuh7bc59052020-02-16 23:48:33 -0800344 // Returns the time_points that the last message was sent at.
345 aos::monotonic_clock::time_point monotonic_sent_time() const {
346 return sender_->monotonic_sent_time();
347 }
348 aos::realtime_clock::time_point realtime_sent_time() const {
349 return sender_->realtime_sent_time();
350 }
351 // Returns the queue index that this was sent with.
352 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
353
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354 private:
355 friend class EventLoop;
356 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
357 std::unique_ptr<RawSender> sender_;
358};
359
360// Interface for timers
361class TimerHandler {
362 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800363 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700364
365 // Timer should sleep until base, base + offset, base + offset * 2, ...
366 // If repeat_offset isn't set, the timer only expires once.
367 virtual void Setup(monotonic_clock::time_point base,
368 monotonic_clock::duration repeat_offset =
369 ::aos::monotonic_clock::zero()) = 0;
370
371 // Stop future calls to callback().
372 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800373
374 // Sets and gets the name of the timer. Set this if you want a descriptive
375 // name in the timing report.
376 void set_name(std::string_view name) { name_ = std::string(name); }
377 const std::string_view name() const { return name_; }
378
Austin Schuh39788ff2019-12-01 18:22:57 -0800379 protected:
380 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
381
Austin Schuhcde39fd2020-02-22 20:58:24 -0800382 monotonic_clock::time_point Call(
383 std::function<monotonic_clock::time_point()> get_time,
384 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800385
Austin Schuh1540c2f2019-11-29 21:59:29 -0800386 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800387 friend class EventLoop;
388
389 EventLoop *event_loop_;
390 // The function to call when Call is called.
391 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800392 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800393
394 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500395 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700396};
397
398// Interface for phased loops. They are built on timers.
399class PhasedLoopHandler {
400 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800401 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402
403 // Sets the interval and offset. Any changes to interval and offset only take
404 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800405 void set_interval_and_offset(const monotonic_clock::duration interval,
406 const monotonic_clock::duration offset) {
407 phased_loop_.set_interval_and_offset(interval, offset);
408 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800409
410 // Sets and gets the name of the timer. Set this if you want a descriptive
411 // name in the timing report.
412 void set_name(std::string_view name) { name_ = std::string(name); }
413 const std::string_view name() const { return name_; }
414
Austin Schuh39788ff2019-12-01 18:22:57 -0800415 protected:
416 void Call(std::function<monotonic_clock::time_point()> get_time,
417 std::function<void(monotonic_clock::time_point)> schedule);
418
419 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
420 const monotonic_clock::duration interval,
421 const monotonic_clock::duration offset);
422
Austin Schuh1540c2f2019-11-29 21:59:29 -0800423 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800424 friend class EventLoop;
425
426 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
427 monotonic_clock::time_point monotonic_now) {
428 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
429 schedule(phased_loop_.sleep_time());
430 }
431
432 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
433
434 EventLoop *event_loop_;
435 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800436 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800437 time::PhasedLoop phased_loop_;
438
439 int cycles_elapsed_ = 0;
440
441 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500442 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443};
444
Brian Silverman6a54ff32020-04-28 16:41:39 -0700445inline cpu_set_t MakeCpusetFromCpus(std::initializer_list<int> cpus) {
446 cpu_set_t result;
447 CPU_ZERO(&result);
448 for (int cpu : cpus) {
449 CPU_SET(cpu, &result);
450 }
451 return result;
452}
453
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454class EventLoop {
455 public:
Tyler Chatow67ddb032020-01-12 14:30:04 -0800456 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457
Austin Schuh39788ff2019-12-01 18:22:57 -0800458 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459
460 // Current time.
461 virtual monotonic_clock::time_point monotonic_now() = 0;
462 virtual realtime_clock::time_point realtime_now() = 0;
463
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700464 // Returns true if the channel exists in the configuration.
465 template <typename T>
466 bool HasChannel(const std::string_view channel_name) {
467 return configuration::GetChannel(configuration_, channel_name,
468 T::GetFullyQualifiedName(), name(),
469 node()) != nullptr;
470 }
471
Alex Perrycb7da4b2019-08-28 19:35:56 -0700472 // Note, it is supported to create:
473 // multiple fetchers, and (one sender or one watcher) per <name, type>
474 // tuple.
475
476 // Makes a class that will always fetch the most recent value
477 // sent to the provided channel.
478 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800479 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800480 const Channel *channel =
481 configuration::GetChannel(configuration_, channel_name,
482 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483 CHECK(channel != nullptr)
484 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
485 << T::GetFullyQualifiedName() << "\" } not found in config.";
486
Austin Schuhca4828c2019-12-28 14:21:35 -0800487 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
488 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
489 << "\", \"type\": \"" << T::GetFullyQualifiedName()
490 << "\" } is not able to be fetched on this node. Check your "
491 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800492 }
493
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 return Fetcher<T>(MakeRawFetcher(channel));
495 }
496
497 // Makes class that allows constructing and sending messages to
498 // the provided channel.
499 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800500 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800501 const Channel *channel =
502 configuration::GetChannel(configuration_, channel_name,
503 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700504 CHECK(channel != nullptr)
505 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800506 << T::GetFullyQualifiedName() << "\" } not found in config for "
507 << name() << ".";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700508
Austin Schuhca4828c2019-12-28 14:21:35 -0800509 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
510 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
511 << "\", \"type\": \"" << T::GetFullyQualifiedName()
512 << "\" } is not able to be sent on this node. Check your "
513 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800514 }
515
Alex Perrycb7da4b2019-08-28 19:35:56 -0700516 return Sender<T>(MakeRawSender(channel));
517 }
518
519 // This will watch messages sent to the provided channel.
520 //
Brian Silverman454bc112020-03-05 14:21:25 -0800521 // w must have a non-polymorphic operator() (aka it can only be called with a
522 // single set of arguments; no overloading or templates). It must be callable
523 // with this signature:
524 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525 //
Brian Silverman454bc112020-03-05 14:21:25 -0800526 // Lambdas are a common form for w. A std::function will work too.
527 //
528 // Note that bind expressions have polymorphic call operators, so they are not
529 // allowed.
530 //
531 // We template Watch as a whole instead of using std::function<void(const T
532 // &)> to allow deducing MessageType from lambdas and other things which are
533 // implicitly convertible to std::function, but not actually std::function
534 // instantiations. Template deduction guides might allow solving this
535 // differently in newer versions of C++, but those have their own corner
536 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800538 void MakeWatcher(const std::string_view channel_name, Watch &&w);
539
540 // Like MakeWatcher, but doesn't have access to the message data. This may be
541 // implemented to use less resources than an equivalent MakeWatcher.
542 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800543 // The function will still have access to context(), although that will have
544 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800545 template <typename MessageType>
546 void MakeNoArgWatcher(const std::string_view channel_name,
547 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700548
549 // The passed in function will be called when the event loop starts.
550 // Use this to run code once the thread goes into "real-time-mode",
551 virtual void OnRun(::std::function<void()> on_run) = 0;
552
Austin Schuh217a9782019-12-21 23:02:50 -0800553 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800554 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555
Austin Schuh217a9782019-12-21 23:02:50 -0800556 // Returns the node that this event loop is running on. Returns nullptr if we
557 // are running in single-node mode.
558 virtual const Node *node() const = 0;
559
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560 // Creates a timer that executes callback when the timer expires
561 // Returns a TimerHandle for configuration of the timer
562 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
563
564 // Creates a timer that executes callback periodically at the specified
565 // interval and offset. Returns a PhasedLoopHandler for interacting with the
566 // timer.
567 virtual PhasedLoopHandler *AddPhasedLoop(
568 ::std::function<void(int)> callback,
569 const monotonic_clock::duration interval,
570 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
571
Austin Schuh217a9782019-12-21 23:02:50 -0800572 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700573
574 // Threadsafe.
575 bool is_running() const { return is_running_.load(); }
576
577 // Sets the scheduler priority to run the event loop at. This may not be
578 // called after we go into "real-time-mode".
579 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800580 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700581
Brian Silverman6a54ff32020-04-28 16:41:39 -0700582 // Sets the scheduler affinity to run the event loop with. This may only be
583 // called before Run().
584 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
585
Austin Schuh217a9782019-12-21 23:02:50 -0800586 // Fetches new messages from the provided channel (path, type).
587 //
588 // Note: this channel must be a member of the exact configuration object this
589 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
591 const Channel *channel) = 0;
592
Austin Schuh217a9782019-12-21 23:02:50 -0800593 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700594 virtual void MakeRawWatcher(
595 const Channel *channel,
596 std::function<void(const Context &context, const void *message)>
597 watcher) = 0;
598
Brian Silverman454bc112020-03-05 14:21:25 -0800599 // Watches channel (name, type) for new messages, without needing to extract
600 // the message contents. Default implementation simply re-uses MakeRawWatcher.
601 virtual void MakeRawNoArgWatcher(
602 const Channel *channel,
603 std::function<void(const Context &context)> watcher) {
604 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800605 Context new_context = context;
606 new_context.data = nullptr;
607 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800608 });
609 }
610
Austin Schuh217a9782019-12-21 23:02:50 -0800611 // Creates a raw sender for the provided channel. This is used for reflection
612 // based sending.
613 // Note: this ignores any node constraints. Ignore at your own peril.
614 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
615
Austin Schuh6231cc32019-12-07 13:06:15 -0800616 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617 const Context &context() const { return context_; }
618
619 // Returns the configuration that this event loop was built with.
620 const Configuration *configuration() const { return configuration_; }
621
Austin Schuh39788ff2019-12-01 18:22:57 -0800622 // Prevents the event loop from sending a timing report.
623 void SkipTimingReport() { skip_timing_report_ = true; }
624
Tyler Chatow67ddb032020-01-12 14:30:04 -0800625 // Prevents AOS_LOG being sent to message on /aos
626 void SkipAosLog() { skip_logger_ = true; }
627
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800629 // Sets the name of the event loop. This is the application name.
630 virtual void set_name(const std::string_view name) = 0;
631
Alex Perrycb7da4b2019-08-28 19:35:56 -0700632 void set_is_running(bool value) { is_running_.store(value); }
633
Austin Schuh39788ff2019-12-01 18:22:57 -0800634 // Validates that channel exists inside configuration_ and finds its index.
635 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700636
Brian Silverman5120afb2020-01-31 17:44:35 -0800637 // Returns the state for the watcher on the corresponding channel. This
638 // watcher must exist before calling this.
639 WatcherState *GetWatcherState(const Channel *channel);
640
Brian Silverman6d2b3592020-06-18 14:40:15 -0700641 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800642 template <typename T>
643 static RawSender *GetRawSender(aos::Sender<T> *sender) {
644 return sender->sender_.get();
645 }
646
Brian Silverman6d2b3592020-06-18 14:40:15 -0700647 // Returns a Fetcher's protected RawFetcher.
648 template <typename T>
649 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
650 return fetcher->fetcher_.get();
651 }
652
Austin Schuh6231cc32019-12-07 13:06:15 -0800653 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700654 Context context_;
655
Austin Schuh39788ff2019-12-01 18:22:57 -0800656 friend class RawSender;
657 friend class TimerHandler;
658 friend class RawFetcher;
659 friend class PhasedLoopHandler;
660 friend class WatcherState;
661
662 // Methods used to implement timing reports.
663 void NewSender(RawSender *sender);
664 void DeleteSender(RawSender *sender);
665 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
666 PhasedLoopHandler *NewPhasedLoop(
667 std::unique_ptr<PhasedLoopHandler> phased_loop);
668 void NewFetcher(RawFetcher *fetcher);
669 void DeleteFetcher(RawFetcher *fetcher);
670 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
671
Brian Silverman0fc69932020-01-24 21:54:02 -0800672 // Tracks that we have a (single) watcher on the given channel.
673 void TakeWatcher(const Channel *channel);
674 // Tracks that we have at least one sender on the given channel.
675 void TakeSender(const Channel *channel);
676
Austin Schuh39788ff2019-12-01 18:22:57 -0800677 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800678 std::vector<RawFetcher *> fetchers_;
679
Austin Schuh39788ff2019-12-01 18:22:57 -0800680 std::vector<std::unique_ptr<TimerHandler>> timers_;
681 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800682 std::vector<std::unique_ptr<WatcherState>> watchers_;
683
684 void SendTimingReport();
685 void UpdateTimingReport();
686 void MaybeScheduleTimingReports();
687
688 std::unique_ptr<RawSender> timing_report_sender_;
689
Austin Schuh7d87b672019-12-01 20:23:49 -0800690 // Tracks which event sources (timers and watchers) have data, and which
691 // don't. Added events may not change their event_time().
692 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
693 // t2 to run, t2 should then be picked up without a context switch.
694 void AddEvent(EventLoopEvent *event);
695 void RemoveEvent(EventLoopEvent *event);
696 size_t EventCount() const { return events_.size(); }
697 EventLoopEvent *PopEvent();
698 EventLoopEvent *PeekEvent() { return events_.front(); }
699 void ReserveEvents();
700
701 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700702 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800703
Tyler Chatow67ddb032020-01-12 14:30:04 -0800704 // If true, don't send AOS_LOG to /aos
705 bool skip_logger_ = false;
706
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800707 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800708 virtual pid_t GetTid() = 0;
709
710 FlatbufferDetachedBuffer<timing::Report> timing_report_;
711
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800712 ::std::atomic<bool> is_running_{false};
713
Alex Perrycb7da4b2019-08-28 19:35:56 -0700714 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800715
716 // If true, don't send out timing reports.
717 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800718
719 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700720};
721
722} // namespace aos
723
724#include "aos/events/event_loop_tmpl.h"
725
726#endif // AOS_EVENTS_EVENT_LOOP_H