blob: 454b976d769d1135858fa993bc1bb923391677c7 [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.
60 void *data;
61};
62
63// Raw version of fetcher. Contains a local variable that the fetcher will
64// update. This is used for reflection and as an interface to implement typed
65// fetchers.
66class RawFetcher {
67 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080068 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070069 RawFetcher(const RawFetcher &) = delete;
70 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080071 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070072
Austin Schuh39788ff2019-12-01 18:22:57 -080073 // Fetches the next message in the queue without blocking. Returns true if
74 // there was a new message and we got it.
75 bool FetchNext();
76
77 // Fetches the latest message without blocking.
78 bool Fetch();
79
80 // Returns the channel this fetcher uses.
81 const Channel *channel() const { return channel_; }
82 // Returns the context for the current message.
83 const Context &context() const { return context_; }
84
85 protected:
86 EventLoop *event_loop() { return event_loop_; }
87
Alex Perrycb7da4b2019-08-28 19:35:56 -070088 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080089
90 private:
91 friend class EventLoop;
92 // Implementation
93 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
94 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
95
Brian Silverman79ec7fc2020-06-08 20:11:22 -050096 EventLoop *const event_loop_;
97 const Channel *const channel_;
98 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -080099
100 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500101 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102};
103
104// Raw version of sender. Sends a block of data. This is used for reflection
105// and as a building block to implement typed senders.
106class RawSender {
107 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800108 RawSender(EventLoop *event_loop, const Channel *channel);
109 RawSender(const RawSender &) = delete;
110 RawSender &operator=(const RawSender &) = delete;
111
112 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700113
114 // Sends a message without copying it. The users starts by copying up to
115 // size() bytes into the data backed by data(). They then call Send to send.
116 // Returns true on a successful send.
Austin Schuhad154822019-12-27 15:45:13 -0800117 // If provided, monotonic_remote_time, realtime_remote_time, and
118 // remote_queue_index are attached to the message and are available in the
119 // context on the read side. If they are not populated, the read side will
120 // get the sent times instead.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700121 virtual void *data() = 0;
122 virtual size_t size() = 0;
Austin Schuhad154822019-12-27 15:45:13 -0800123 bool Send(size_t size,
124 aos::monotonic_clock::time_point monotonic_remote_time =
125 aos::monotonic_clock::min_time,
126 aos::realtime_clock::time_point realtime_remote_time =
127 aos::realtime_clock::min_time,
128 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700129
130 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800131 // The remote arguments have the same meaning as in Send above.
132 bool Send(const void *data, size_t size,
133 aos::monotonic_clock::time_point monotonic_remote_time =
134 aos::monotonic_clock::min_time,
135 aos::realtime_clock::time_point realtime_remote_time =
136 aos::realtime_clock::min_time,
137 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700138
Austin Schuh54cf95f2019-11-29 13:14:18 -0800139 const Channel *channel() const { return channel_; }
140
Austin Schuhad154822019-12-27 15:45:13 -0800141 // Returns the time_points that the last message was sent at.
142 aos::monotonic_clock::time_point monotonic_sent_time() const {
143 return monotonic_sent_time_;
144 }
145 aos::realtime_clock::time_point realtime_sent_time() const {
146 return realtime_sent_time_;
147 }
148 // Returns the queue index that this was sent with.
149 uint32_t sent_queue_index() const { return sent_queue_index_; }
150
Brian Silvermana1652f32020-01-29 20:41:44 -0800151 // Returns the associated flatbuffers-style allocator. This must be
152 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800153 ChannelPreallocatedAllocator *fbb_allocator() {
154 fbb_allocator_ = ChannelPreallocatedAllocator(
155 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800156 return &fbb_allocator_;
157 }
158
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800160 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800161
Austin Schuhad154822019-12-27 15:45:13 -0800162 aos::monotonic_clock::time_point monotonic_sent_time_ =
163 aos::monotonic_clock::min_time;
164 aos::realtime_clock::time_point realtime_sent_time_ =
165 aos::realtime_clock::min_time;
166 uint32_t sent_queue_index_ = 0xffffffff;
167
Austin Schuh39788ff2019-12-01 18:22:57 -0800168 private:
169 friend class EventLoop;
170
Austin Schuhad154822019-12-27 15:45:13 -0800171 virtual bool DoSend(const void *data, size_t size,
172 aos::monotonic_clock::time_point monotonic_remote_time,
173 aos::realtime_clock::time_point realtime_remote_time,
174 uint32_t remote_queue_index) = 0;
175 virtual bool DoSend(size_t size,
176 aos::monotonic_clock::time_point monotonic_remote_time,
177 aos::realtime_clock::time_point realtime_remote_time,
178 uint32_t remote_queue_index) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800179
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500180 EventLoop *const event_loop_;
181 const Channel *const channel_;
182 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700183
Austin Schuh39788ff2019-12-01 18:22:57 -0800184 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500185 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800186
Austin Schuh1af273d2020-03-07 20:11:34 -0800187 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800188};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700189
190// Fetches the newest message from a channel.
191// This provides a polling based interface for channels.
192template <typename T>
193class Fetcher {
194 public:
195 Fetcher() {}
196
197 // Fetches the next message. Returns true if it fetched a new message. This
198 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800199 bool FetchNext() {
200 const bool result = fetcher_->FetchNext();
201 if (result) {
202 CheckChannelDataAlignment(fetcher_->context().data,
203 fetcher_->context().size);
204 }
205 return result;
206 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700207
208 // Fetches the most recent message. Returns true if it fetched a new message.
209 // This will return the latest message regardless of if it was sent before or
210 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800211 bool Fetch() {
212 const bool result = fetcher_->Fetch();
213 if (result) {
214 CheckChannelDataAlignment(fetcher_->context().data,
215 fetcher_->context().size);
216 }
217 return result;
218 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700219
220 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
221 // available message.
222 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800223 return fetcher_->context().data != nullptr
224 ? flatbuffers::GetRoot<T>(
225 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700226 : nullptr;
227 }
228
229 // Returns the context holding timestamps and other metadata about the
230 // message.
231 const Context &context() const { return fetcher_->context(); }
232
233 const T &operator*() const { return *get(); }
234 const T *operator->() const { return get(); }
235
236 private:
237 friend class EventLoop;
238 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
239 : fetcher_(::std::move(fetcher)) {}
240 ::std::unique_ptr<RawFetcher> fetcher_;
241};
242
243// Sends messages to a channel.
244template <typename T>
245class Sender {
246 public:
247 Sender() {}
248
249 // Represents a single message about to be sent to the queue.
250 // The lifecycle goes:
251 //
252 // Builder builder = sender.MakeBuilder();
253 // T::Builder t_builder = builder.MakeBuilder<T>();
254 // Populate(&t_builder);
255 // builder.Send(t_builder.Finish());
256 class Builder {
257 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800258 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800259 : fbb_(allocator->size(), allocator),
260 allocator_(allocator),
261 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800262 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800263 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700264 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800265 Builder() {}
266 Builder(const Builder &) = delete;
267 Builder(Builder &&) = default;
268
269 Builder &operator=(const Builder &) = delete;
270 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700271
272 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
273
274 template <typename T2>
275 typename T2::Builder MakeBuilder() {
276 return typename T2::Builder(fbb_);
277 }
278
279 bool Send(flatbuffers::Offset<T> offset) {
280 fbb_.Finish(offset);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800281 const bool result = sender_->Send(fbb_.GetSize());
282 // Ensure fbb_ knows it shouldn't access the memory any more.
283 fbb_ = flatbuffers::FlatBufferBuilder();
284 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285 }
286
287 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800288 void CheckSent() {
289 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
290 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291
292 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700293 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800294 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700295 RawSender *sender_;
296 };
297
298 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800299 //
300 // Only a single one of these may be "alive" for this object at any point in
301 // time. After calling Send on the result, it is no longer "alive". This means
302 // that you must manually reset a variable holding the return value (by
303 // assigning a default-constructed Builder to it) before calling this method
304 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700305 Builder MakeBuilder();
306
Austin Schuha28cbc32019-12-27 16:28:04 -0800307 // Sends a prebuilt flatbuffer.
308 bool Send(const Flatbuffer<T> &flatbuffer);
309
Austin Schuh39788ff2019-12-01 18:22:57 -0800310 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800311 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700312
Brian Silverman454bc112020-03-05 14:21:25 -0800313 operator bool() { return sender_ ? true : false; }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800314
Austin Schuh7bc59052020-02-16 23:48:33 -0800315 // Returns the time_points that the last message was sent at.
316 aos::monotonic_clock::time_point monotonic_sent_time() const {
317 return sender_->monotonic_sent_time();
318 }
319 aos::realtime_clock::time_point realtime_sent_time() const {
320 return sender_->realtime_sent_time();
321 }
322 // Returns the queue index that this was sent with.
323 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
324
Alex Perrycb7da4b2019-08-28 19:35:56 -0700325 private:
326 friend class EventLoop;
327 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
328 std::unique_ptr<RawSender> sender_;
329};
330
331// Interface for timers
332class TimerHandler {
333 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800334 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700335
336 // Timer should sleep until base, base + offset, base + offset * 2, ...
337 // If repeat_offset isn't set, the timer only expires once.
338 virtual void Setup(monotonic_clock::time_point base,
339 monotonic_clock::duration repeat_offset =
340 ::aos::monotonic_clock::zero()) = 0;
341
342 // Stop future calls to callback().
343 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800344
345 // Sets and gets the name of the timer. Set this if you want a descriptive
346 // name in the timing report.
347 void set_name(std::string_view name) { name_ = std::string(name); }
348 const std::string_view name() const { return name_; }
349
Austin Schuh39788ff2019-12-01 18:22:57 -0800350 protected:
351 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
352
Austin Schuhcde39fd2020-02-22 20:58:24 -0800353 monotonic_clock::time_point Call(
354 std::function<monotonic_clock::time_point()> get_time,
355 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800356
Austin Schuh1540c2f2019-11-29 21:59:29 -0800357 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800358 friend class EventLoop;
359
360 EventLoop *event_loop_;
361 // The function to call when Call is called.
362 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800363 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800364
365 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500366 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700367};
368
369// Interface for phased loops. They are built on timers.
370class PhasedLoopHandler {
371 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800372 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700373
374 // Sets the interval and offset. Any changes to interval and offset only take
375 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800376 void set_interval_and_offset(const monotonic_clock::duration interval,
377 const monotonic_clock::duration offset) {
378 phased_loop_.set_interval_and_offset(interval, offset);
379 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800380
381 // Sets and gets the name of the timer. Set this if you want a descriptive
382 // name in the timing report.
383 void set_name(std::string_view name) { name_ = std::string(name); }
384 const std::string_view name() const { return name_; }
385
Austin Schuh39788ff2019-12-01 18:22:57 -0800386 protected:
387 void Call(std::function<monotonic_clock::time_point()> get_time,
388 std::function<void(monotonic_clock::time_point)> schedule);
389
390 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
391 const monotonic_clock::duration interval,
392 const monotonic_clock::duration offset);
393
Austin Schuh1540c2f2019-11-29 21:59:29 -0800394 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800395 friend class EventLoop;
396
397 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
398 monotonic_clock::time_point monotonic_now) {
399 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
400 schedule(phased_loop_.sleep_time());
401 }
402
403 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
404
405 EventLoop *event_loop_;
406 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800407 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800408 time::PhasedLoop phased_loop_;
409
410 int cycles_elapsed_ = 0;
411
412 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500413 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700414};
415
Brian Silverman6a54ff32020-04-28 16:41:39 -0700416inline cpu_set_t MakeCpusetFromCpus(std::initializer_list<int> cpus) {
417 cpu_set_t result;
418 CPU_ZERO(&result);
419 for (int cpu : cpus) {
420 CPU_SET(cpu, &result);
421 }
422 return result;
423}
424
Alex Perrycb7da4b2019-08-28 19:35:56 -0700425class EventLoop {
426 public:
Tyler Chatow67ddb032020-01-12 14:30:04 -0800427 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700428
Austin Schuh39788ff2019-12-01 18:22:57 -0800429 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700430
431 // Current time.
432 virtual monotonic_clock::time_point monotonic_now() = 0;
433 virtual realtime_clock::time_point realtime_now() = 0;
434
435 // Note, it is supported to create:
436 // multiple fetchers, and (one sender or one watcher) per <name, type>
437 // tuple.
438
439 // Makes a class that will always fetch the most recent value
440 // sent to the provided channel.
441 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800442 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800443 const Channel *channel =
444 configuration::GetChannel(configuration_, channel_name,
445 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446 CHECK(channel != nullptr)
447 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
448 << T::GetFullyQualifiedName() << "\" } not found in config.";
449
Austin Schuhca4828c2019-12-28 14:21:35 -0800450 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
451 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
452 << "\", \"type\": \"" << T::GetFullyQualifiedName()
453 << "\" } is not able to be fetched on this node. Check your "
454 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800455 }
456
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457 return Fetcher<T>(MakeRawFetcher(channel));
458 }
459
460 // Makes class that allows constructing and sending messages to
461 // the provided channel.
462 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800463 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800464 const Channel *channel =
465 configuration::GetChannel(configuration_, channel_name,
466 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467 CHECK(channel != nullptr)
468 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800469 << T::GetFullyQualifiedName() << "\" } not found in config for "
470 << name() << ".";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700471
Austin Schuhca4828c2019-12-28 14:21:35 -0800472 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
473 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
474 << "\", \"type\": \"" << T::GetFullyQualifiedName()
475 << "\" } is not able to be sent on this node. Check your "
476 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800477 }
478
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479 return Sender<T>(MakeRawSender(channel));
480 }
481
482 // This will watch messages sent to the provided channel.
483 //
Brian Silverman454bc112020-03-05 14:21:25 -0800484 // w must have a non-polymorphic operator() (aka it can only be called with a
485 // single set of arguments; no overloading or templates). It must be callable
486 // with this signature:
487 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700488 //
Brian Silverman454bc112020-03-05 14:21:25 -0800489 // Lambdas are a common form for w. A std::function will work too.
490 //
491 // Note that bind expressions have polymorphic call operators, so they are not
492 // allowed.
493 //
494 // We template Watch as a whole instead of using std::function<void(const T
495 // &)> to allow deducing MessageType from lambdas and other things which are
496 // implicitly convertible to std::function, but not actually std::function
497 // instantiations. Template deduction guides might allow solving this
498 // differently in newer versions of C++, but those have their own corner
499 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800501 void MakeWatcher(const std::string_view channel_name, Watch &&w);
502
503 // Like MakeWatcher, but doesn't have access to the message data. This may be
504 // implemented to use less resources than an equivalent MakeWatcher.
505 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800506 // The function will still have access to context(), although that will have
507 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800508 template <typename MessageType>
509 void MakeNoArgWatcher(const std::string_view channel_name,
510 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511
512 // The passed in function will be called when the event loop starts.
513 // Use this to run code once the thread goes into "real-time-mode",
514 virtual void OnRun(::std::function<void()> on_run) = 0;
515
Austin Schuh217a9782019-12-21 23:02:50 -0800516 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800517 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700518
Austin Schuh217a9782019-12-21 23:02:50 -0800519 // Returns the node that this event loop is running on. Returns nullptr if we
520 // are running in single-node mode.
521 virtual const Node *node() const = 0;
522
Alex Perrycb7da4b2019-08-28 19:35:56 -0700523 // Creates a timer that executes callback when the timer expires
524 // Returns a TimerHandle for configuration of the timer
525 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
526
527 // Creates a timer that executes callback periodically at the specified
528 // interval and offset. Returns a PhasedLoopHandler for interacting with the
529 // timer.
530 virtual PhasedLoopHandler *AddPhasedLoop(
531 ::std::function<void(int)> callback,
532 const monotonic_clock::duration interval,
533 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
534
Austin Schuh217a9782019-12-21 23:02:50 -0800535 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700536
537 // Threadsafe.
538 bool is_running() const { return is_running_.load(); }
539
540 // Sets the scheduler priority to run the event loop at. This may not be
541 // called after we go into "real-time-mode".
542 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800543 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544
Brian Silverman6a54ff32020-04-28 16:41:39 -0700545 // Sets the scheduler affinity to run the event loop with. This may only be
546 // called before Run().
547 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
548
Austin Schuh217a9782019-12-21 23:02:50 -0800549 // Fetches new messages from the provided channel (path, type).
550 //
551 // Note: this channel must be a member of the exact configuration object this
552 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
554 const Channel *channel) = 0;
555
Austin Schuh217a9782019-12-21 23:02:50 -0800556 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557 virtual void MakeRawWatcher(
558 const Channel *channel,
559 std::function<void(const Context &context, const void *message)>
560 watcher) = 0;
561
Brian Silverman454bc112020-03-05 14:21:25 -0800562 // Watches channel (name, type) for new messages, without needing to extract
563 // the message contents. Default implementation simply re-uses MakeRawWatcher.
564 virtual void MakeRawNoArgWatcher(
565 const Channel *channel,
566 std::function<void(const Context &context)> watcher) {
567 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800568 Context new_context = context;
569 new_context.data = nullptr;
570 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800571 });
572 }
573
Austin Schuh217a9782019-12-21 23:02:50 -0800574 // Creates a raw sender for the provided channel. This is used for reflection
575 // based sending.
576 // Note: this ignores any node constraints. Ignore at your own peril.
577 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
578
Austin Schuh6231cc32019-12-07 13:06:15 -0800579 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580 const Context &context() const { return context_; }
581
582 // Returns the configuration that this event loop was built with.
583 const Configuration *configuration() const { return configuration_; }
584
Austin Schuh39788ff2019-12-01 18:22:57 -0800585 // Prevents the event loop from sending a timing report.
586 void SkipTimingReport() { skip_timing_report_ = true; }
587
Tyler Chatow67ddb032020-01-12 14:30:04 -0800588 // Prevents AOS_LOG being sent to message on /aos
589 void SkipAosLog() { skip_logger_ = true; }
590
Alex Perrycb7da4b2019-08-28 19:35:56 -0700591 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800592 // Sets the name of the event loop. This is the application name.
593 virtual void set_name(const std::string_view name) = 0;
594
Alex Perrycb7da4b2019-08-28 19:35:56 -0700595 void set_is_running(bool value) { is_running_.store(value); }
596
Austin Schuh39788ff2019-12-01 18:22:57 -0800597 // Validates that channel exists inside configuration_ and finds its index.
598 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700599
Brian Silverman5120afb2020-01-31 17:44:35 -0800600 // Returns the state for the watcher on the corresponding channel. This
601 // watcher must exist before calling this.
602 WatcherState *GetWatcherState(const Channel *channel);
603
604 // Returns a Sender's protected RawSender
605 template <typename T>
606 static RawSender *GetRawSender(aos::Sender<T> *sender) {
607 return sender->sender_.get();
608 }
609
Austin Schuh6231cc32019-12-07 13:06:15 -0800610 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700611 Context context_;
612
Austin Schuh39788ff2019-12-01 18:22:57 -0800613 friend class RawSender;
614 friend class TimerHandler;
615 friend class RawFetcher;
616 friend class PhasedLoopHandler;
617 friend class WatcherState;
618
619 // Methods used to implement timing reports.
620 void NewSender(RawSender *sender);
621 void DeleteSender(RawSender *sender);
622 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
623 PhasedLoopHandler *NewPhasedLoop(
624 std::unique_ptr<PhasedLoopHandler> phased_loop);
625 void NewFetcher(RawFetcher *fetcher);
626 void DeleteFetcher(RawFetcher *fetcher);
627 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
628
Brian Silverman0fc69932020-01-24 21:54:02 -0800629 // Tracks that we have a (single) watcher on the given channel.
630 void TakeWatcher(const Channel *channel);
631 // Tracks that we have at least one sender on the given channel.
632 void TakeSender(const Channel *channel);
633
Austin Schuh39788ff2019-12-01 18:22:57 -0800634 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800635 std::vector<RawFetcher *> fetchers_;
636
Austin Schuh39788ff2019-12-01 18:22:57 -0800637 std::vector<std::unique_ptr<TimerHandler>> timers_;
638 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800639 std::vector<std::unique_ptr<WatcherState>> watchers_;
640
641 void SendTimingReport();
642 void UpdateTimingReport();
643 void MaybeScheduleTimingReports();
644
645 std::unique_ptr<RawSender> timing_report_sender_;
646
Austin Schuh7d87b672019-12-01 20:23:49 -0800647 // Tracks which event sources (timers and watchers) have data, and which
648 // don't. Added events may not change their event_time().
649 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
650 // t2 to run, t2 should then be picked up without a context switch.
651 void AddEvent(EventLoopEvent *event);
652 void RemoveEvent(EventLoopEvent *event);
653 size_t EventCount() const { return events_.size(); }
654 EventLoopEvent *PopEvent();
655 EventLoopEvent *PeekEvent() { return events_.front(); }
656 void ReserveEvents();
657
658 std::vector<EventLoopEvent *> events_;
659
Tyler Chatow67ddb032020-01-12 14:30:04 -0800660 // If true, don't send AOS_LOG to /aos
661 bool skip_logger_ = false;
662
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800663 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800664 virtual pid_t GetTid() = 0;
665
666 FlatbufferDetachedBuffer<timing::Report> timing_report_;
667
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800668 ::std::atomic<bool> is_running_{false};
669
Alex Perrycb7da4b2019-08-28 19:35:56 -0700670 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800671
672 // If true, don't send out timing reports.
673 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800674
675 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700676};
677
678} // namespace aos
679
680#include "aos/events/event_loop_tmpl.h"
681
682#endif // AOS_EVENTS_EVENT_LOOP_H