blob: 68b1b5e4f0890c5d21378e8fd7a8b5581dc16054 [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
4#include <atomic>
5#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08006#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07007
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include "aos/configuration.h"
9#include "aos/configuration_generated.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080010#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080011#include "aos/events/event_loop_generated.h"
12#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include "aos/flatbuffers.h"
14#include "aos/json_to_flatbuffer.h"
15#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080016#include "aos/util/phased_loop.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070017#include "flatbuffers/flatbuffers.h"
18#include "glog/logging.h"
19
Austin Schuh39788ff2019-12-01 18:22:57 -080020DECLARE_bool(timing_reports);
21DECLARE_int32(timing_report_ms);
22
Alex Perrycb7da4b2019-08-28 19:35:56 -070023namespace aos {
24
Austin Schuh39788ff2019-12-01 18:22:57 -080025class EventLoop;
26class WatcherState;
27
Austin Schuh6231cc32019-12-07 13:06:15 -080028// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
29// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070030struct Context {
Austin Schuh6231cc32019-12-07 13:06:15 -080031 // Time that the message was sent, or the timer was triggered.
Alex Perrycb7da4b2019-08-28 19:35:56 -070032 monotonic_clock::time_point monotonic_sent_time;
Austin Schuh6231cc32019-12-07 13:06:15 -080033 // Realtime the message was sent. This is set to min_time for Timers and
34 // PhasedLoops.
Alex Perrycb7da4b2019-08-28 19:35:56 -070035 realtime_clock::time_point realtime_sent_time;
Austin Schuh6231cc32019-12-07 13:06:15 -080036 // The rest are only valid for Watchers and Fetchers.
Alex Perrycb7da4b2019-08-28 19:35:56 -070037 // Index in the queue.
38 uint32_t queue_index;
39 // Size of the data sent.
40 size_t size;
41 // Pointer to the data.
42 void *data;
43};
44
45// Raw version of fetcher. Contains a local variable that the fetcher will
46// update. This is used for reflection and as an interface to implement typed
47// fetchers.
48class RawFetcher {
49 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080050 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070051 RawFetcher(const RawFetcher &) = delete;
52 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080053 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070054
Austin Schuh39788ff2019-12-01 18:22:57 -080055 // Fetches the next message in the queue without blocking. Returns true if
56 // there was a new message and we got it.
57 bool FetchNext();
58
59 // Fetches the latest message without blocking.
60 bool Fetch();
61
62 // Returns the channel this fetcher uses.
63 const Channel *channel() const { return channel_; }
64 // Returns the context for the current message.
65 const Context &context() const { return context_; }
66
67 protected:
68 EventLoop *event_loop() { return event_loop_; }
69
Alex Perrycb7da4b2019-08-28 19:35:56 -070070 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080071
72 private:
73 friend class EventLoop;
74 // Implementation
75 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
76 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
77
78 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -080079 const Channel *channel_;
Austin Schuh39788ff2019-12-01 18:22:57 -080080
81 internal::RawFetcherTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070082};
83
84// Raw version of sender. Sends a block of data. This is used for reflection
85// and as a building block to implement typed senders.
86class RawSender {
87 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080088 RawSender(EventLoop *event_loop, const Channel *channel);
89 RawSender(const RawSender &) = delete;
90 RawSender &operator=(const RawSender &) = delete;
91
92 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -070093
94 // Sends a message without copying it. The users starts by copying up to
95 // size() bytes into the data backed by data(). They then call Send to send.
96 // Returns true on a successful send.
97 virtual void *data() = 0;
98 virtual size_t size() = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080099 bool Send(size_t size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700100
101 // Sends a single block of data by copying it.
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 bool Send(const void *data, size_t size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700103
Austin Schuh54cf95f2019-11-29 13:14:18 -0800104 const Channel *channel() const { return channel_; }
105
Alex Perrycb7da4b2019-08-28 19:35:56 -0700106 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800107 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800108
Austin Schuh39788ff2019-12-01 18:22:57 -0800109 private:
110 friend class EventLoop;
111
112 virtual bool DoSend(const void *data, size_t size) = 0;
113 virtual bool DoSend(size_t size) = 0;
114
115 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -0800116 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117
Austin Schuh39788ff2019-12-01 18:22:57 -0800118 internal::RawSenderTiming timing_;
119};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700120
121// Fetches the newest message from a channel.
122// This provides a polling based interface for channels.
123template <typename T>
124class Fetcher {
125 public:
126 Fetcher() {}
127
128 // Fetches the next message. Returns true if it fetched a new message. This
129 // method will only return messages sent after the Fetcher was created.
130 bool FetchNext() { return fetcher_->FetchNext(); }
131
132 // Fetches the most recent message. Returns true if it fetched a new message.
133 // This will return the latest message regardless of if it was sent before or
134 // after the fetcher was created.
135 bool Fetch() { return fetcher_->Fetch(); }
136
137 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
138 // available message.
139 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800140 return fetcher_->context().data != nullptr
141 ? flatbuffers::GetRoot<T>(
142 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700143 : nullptr;
144 }
145
146 // Returns the context holding timestamps and other metadata about the
147 // message.
148 const Context &context() const { return fetcher_->context(); }
149
150 const T &operator*() const { return *get(); }
151 const T *operator->() const { return get(); }
152
153 private:
154 friend class EventLoop;
155 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
156 : fetcher_(::std::move(fetcher)) {}
157 ::std::unique_ptr<RawFetcher> fetcher_;
158};
159
160// Sends messages to a channel.
161template <typename T>
162class Sender {
163 public:
164 Sender() {}
165
166 // Represents a single message about to be sent to the queue.
167 // The lifecycle goes:
168 //
169 // Builder builder = sender.MakeBuilder();
170 // T::Builder t_builder = builder.MakeBuilder<T>();
171 // Populate(&t_builder);
172 // builder.Send(t_builder.Finish());
173 class Builder {
174 public:
175 Builder(RawSender *sender, void *data, size_t size)
176 : alloc_(data, size), fbb_(size, &alloc_), sender_(sender) {
177 fbb_.ForceDefaults(1);
178 }
179
180 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
181
182 template <typename T2>
183 typename T2::Builder MakeBuilder() {
184 return typename T2::Builder(fbb_);
185 }
186
187 bool Send(flatbuffers::Offset<T> offset) {
188 fbb_.Finish(offset);
189 return sender_->Send(fbb_.GetSize());
190 }
191
192 // CHECKs that this message was sent.
193 void CheckSent() { fbb_.Finished(); }
194
195 private:
196 PreallocatedAllocator alloc_;
197 flatbuffers::FlatBufferBuilder fbb_;
198 RawSender *sender_;
199 };
200
201 // Constructs an above builder.
202 Builder MakeBuilder();
203
Austin Schuh39788ff2019-12-01 18:22:57 -0800204 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800205 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700206
207 private:
208 friend class EventLoop;
209 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
210 std::unique_ptr<RawSender> sender_;
211};
212
213// Interface for timers
214class TimerHandler {
215 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217
218 // Timer should sleep until base, base + offset, base + offset * 2, ...
219 // If repeat_offset isn't set, the timer only expires once.
220 virtual void Setup(monotonic_clock::time_point base,
221 monotonic_clock::duration repeat_offset =
222 ::aos::monotonic_clock::zero()) = 0;
223
224 // Stop future calls to callback().
225 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800226
227 // Sets and gets the name of the timer. Set this if you want a descriptive
228 // name in the timing report.
229 void set_name(std::string_view name) { name_ = std::string(name); }
230 const std::string_view name() const { return name_; }
231
Austin Schuh39788ff2019-12-01 18:22:57 -0800232 protected:
233 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
234
235 void Call(std::function<monotonic_clock::time_point()> get_time,
236 monotonic_clock::time_point event_time);
237
Austin Schuh1540c2f2019-11-29 21:59:29 -0800238 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800239 friend class EventLoop;
240
241 EventLoop *event_loop_;
242 // The function to call when Call is called.
243 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800244 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800245
246 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700247};
248
249// Interface for phased loops. They are built on timers.
250class PhasedLoopHandler {
251 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800252 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700253
254 // Sets the interval and offset. Any changes to interval and offset only take
255 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800256 void set_interval_and_offset(const monotonic_clock::duration interval,
257 const monotonic_clock::duration offset) {
258 phased_loop_.set_interval_and_offset(interval, offset);
259 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800260
261 // Sets and gets the name of the timer. Set this if you want a descriptive
262 // name in the timing report.
263 void set_name(std::string_view name) { name_ = std::string(name); }
264 const std::string_view name() const { return name_; }
265
Austin Schuh39788ff2019-12-01 18:22:57 -0800266 protected:
267 void Call(std::function<monotonic_clock::time_point()> get_time,
268 std::function<void(monotonic_clock::time_point)> schedule);
269
270 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
271 const monotonic_clock::duration interval,
272 const monotonic_clock::duration offset);
273
Austin Schuh1540c2f2019-11-29 21:59:29 -0800274 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800275 friend class EventLoop;
276
277 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
278 monotonic_clock::time_point monotonic_now) {
279 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
280 schedule(phased_loop_.sleep_time());
281 }
282
283 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
284
285 EventLoop *event_loop_;
286 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800287 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800288 time::PhasedLoop phased_loop_;
289
290 int cycles_elapsed_ = 0;
291
292 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700293};
294
Alex Perrycb7da4b2019-08-28 19:35:56 -0700295class EventLoop {
296 public:
297 EventLoop(const Configuration *configuration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800298 : timing_report_(flatbuffers::DetachedBuffer()),
299 configuration_(configuration) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700300
Austin Schuh39788ff2019-12-01 18:22:57 -0800301 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700302
303 // Current time.
304 virtual monotonic_clock::time_point monotonic_now() = 0;
305 virtual realtime_clock::time_point realtime_now() = 0;
306
307 // Note, it is supported to create:
308 // multiple fetchers, and (one sender or one watcher) per <name, type>
309 // tuple.
310
311 // Makes a class that will always fetch the most recent value
312 // sent to the provided channel.
313 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800314 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315 const Channel *channel = configuration::GetChannel(
316 configuration_, channel_name, T::GetFullyQualifiedName(), name());
317 CHECK(channel != nullptr)
318 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
319 << T::GetFullyQualifiedName() << "\" } not found in config.";
320
321 return Fetcher<T>(MakeRawFetcher(channel));
322 }
323
324 // Makes class that allows constructing and sending messages to
325 // the provided channel.
326 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800327 Sender<T> MakeSender(const std::string_view channel_name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700328 const Channel *channel = configuration::GetChannel(
329 configuration_, channel_name, T::GetFullyQualifiedName(), name());
330 CHECK(channel != nullptr)
331 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
332 << T::GetFullyQualifiedName() << "\" } not found in config.";
333
334 return Sender<T>(MakeRawSender(channel));
335 }
336
337 // This will watch messages sent to the provided channel.
338 //
339 // Watch is a functor that have a call signature like so:
340 // void Event(const MessageType& type);
341 //
342 // TODO(parker): Need to support ::std::bind. For now, use lambdas.
343 // TODO(austin): Do we need a functor? Or is a std::function good enough?
344 template <typename Watch>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800345 void MakeWatcher(const std::string_view name, Watch &&w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700346
347 // The passed in function will be called when the event loop starts.
348 // Use this to run code once the thread goes into "real-time-mode",
349 virtual void OnRun(::std::function<void()> on_run) = 0;
350
351 // Sets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800352 virtual void set_name(const std::string_view name) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700353 // Gets the name of the event loop.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800354 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700355
356 // Creates a timer that executes callback when the timer expires
357 // Returns a TimerHandle for configuration of the timer
358 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
359
360 // Creates a timer that executes callback periodically at the specified
361 // interval and offset. Returns a PhasedLoopHandler for interacting with the
362 // timer.
363 virtual PhasedLoopHandler *AddPhasedLoop(
364 ::std::function<void(int)> callback,
365 const monotonic_clock::duration interval,
366 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
367
368 // TODO(austin): OnExit
369
370 // Threadsafe.
371 bool is_running() const { return is_running_.load(); }
372
373 // Sets the scheduler priority to run the event loop at. This may not be
374 // called after we go into "real-time-mode".
375 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800376 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700377
378 // Fetches new messages from the provided channel (path, type). Note: this
379 // channel must be a member of the exact configuration object this was built
380 // with.
381 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
382 const Channel *channel) = 0;
383
384 // Will watch channel (name, type) for new messages
385 virtual void MakeRawWatcher(
386 const Channel *channel,
387 std::function<void(const Context &context, const void *message)>
388 watcher) = 0;
389
Austin Schuh6231cc32019-12-07 13:06:15 -0800390 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 const Context &context() const { return context_; }
392
393 // Returns the configuration that this event loop was built with.
394 const Configuration *configuration() const { return configuration_; }
395
Austin Schuh54cf95f2019-11-29 13:14:18 -0800396 // Will send new messages from channel (path, type).
397 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
398
Austin Schuh39788ff2019-12-01 18:22:57 -0800399 // Prevents the event loop from sending a timing report.
400 void SkipTimingReport() { skip_timing_report_ = true; }
401
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402 protected:
403 void set_is_running(bool value) { is_running_.store(value); }
404
Austin Schuh39788ff2019-12-01 18:22:57 -0800405 // Validates that channel exists inside configuration_ and finds its index.
406 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407
Austin Schuh6231cc32019-12-07 13:06:15 -0800408 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409 Context context_;
410
Austin Schuh39788ff2019-12-01 18:22:57 -0800411 friend class RawSender;
412 friend class TimerHandler;
413 friend class RawFetcher;
414 friend class PhasedLoopHandler;
415 friend class WatcherState;
416
417 // Methods used to implement timing reports.
418 void NewSender(RawSender *sender);
419 void DeleteSender(RawSender *sender);
420 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
421 PhasedLoopHandler *NewPhasedLoop(
422 std::unique_ptr<PhasedLoopHandler> phased_loop);
423 void NewFetcher(RawFetcher *fetcher);
424 void DeleteFetcher(RawFetcher *fetcher);
425 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
426
427 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800428 std::vector<RawFetcher *> fetchers_;
429
Austin Schuh39788ff2019-12-01 18:22:57 -0800430 std::vector<std::unique_ptr<TimerHandler>> timers_;
431 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800432 std::vector<std::unique_ptr<WatcherState>> watchers_;
433
434 void SendTimingReport();
435 void UpdateTimingReport();
436 void MaybeScheduleTimingReports();
437
438 std::unique_ptr<RawSender> timing_report_sender_;
439
Austin Schuh7d87b672019-12-01 20:23:49 -0800440 // Tracks which event sources (timers and watchers) have data, and which
441 // don't. Added events may not change their event_time().
442 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
443 // t2 to run, t2 should then be picked up without a context switch.
444 void AddEvent(EventLoopEvent *event);
445 void RemoveEvent(EventLoopEvent *event);
446 size_t EventCount() const { return events_.size(); }
447 EventLoopEvent *PopEvent();
448 EventLoopEvent *PeekEvent() { return events_.front(); }
449 void ReserveEvents();
450
451 std::vector<EventLoopEvent *> events_;
452
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800453 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800454 virtual pid_t GetTid() = 0;
455
456 FlatbufferDetachedBuffer<timing::Report> timing_report_;
457
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800458 ::std::atomic<bool> is_running_{false};
459
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800461
462 // If true, don't send out timing reports.
463 bool skip_timing_report_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700464};
465
466} // namespace aos
467
468#include "aos/events/event_loop_tmpl.h"
469
470#endif // AOS_EVENTS_EVENT_LOOP_H