blob: 397b5f07cd2e834a1c008c03a9183b7577ad7f6b [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_SCHEDULER_H_
2#define AOS_EVENTS_EVENT_SCHEDULER_H_
3
4#include <algorithm>
5#include <map>
6#include <memory>
7#include <unordered_set>
8#include <utility>
9#include <vector>
10
11#include "aos/events/event_loop.h"
Austin Schuh8bd96322020-02-13 21:18:22 -080012#include "aos/logging/implementations.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include "aos/time/time.h"
14#include "glog/logging.h"
15
16namespace aos {
17
Austin Schuhac0771c2020-01-07 18:36:30 -080018// This clock is the basis for distributed time. It is used to synchronize time
19// between multiple nodes. This is a new type so conversions to and from the
20// monotonic and realtime clocks aren't implicit.
21class distributed_clock {
22 public:
23 typedef ::std::chrono::nanoseconds::rep rep;
24 typedef ::std::chrono::nanoseconds::period period;
25 typedef ::std::chrono::nanoseconds duration;
26 typedef ::std::chrono::time_point<distributed_clock> time_point;
27
28 // This clock is the base clock for the simulation and everything is synced to
29 // it. It never jumps.
30 static constexpr bool is_steady = true;
31
32 // Returns the epoch (0).
33 static constexpr time_point epoch() { return time_point(zero()); }
34
35 static constexpr duration zero() { return duration(0); }
36
37 static constexpr time_point min_time{
38 time_point(duration(::std::numeric_limits<duration::rep>::min()))};
39 static constexpr time_point max_time{
40 time_point(duration(::std::numeric_limits<duration::rep>::max()))};
41};
42
43std::ostream &operator<<(std::ostream &stream,
44 const aos::distributed_clock::time_point &now);
45
Austin Schuha9abc032021-01-01 16:46:19 -080046// Interface to handle converting time on a node to and from the distributed
47// clock accurately.
48class TimeConverter {
49 public:
50 virtual ~TimeConverter() {}
51
52 // Converts a time to the distributed clock for scheduling and cross-node
53 // time measurement.
54 virtual distributed_clock::time_point ToDistributedClock(
55 size_t node_index, monotonic_clock::time_point time) = 0;
56
57 // Takes the distributed time and converts it to the monotonic clock for this
58 // node.
59 virtual monotonic_clock::time_point FromDistributedClock(
60 size_t node_index, distributed_clock::time_point time) = 0;
61};
62
Austin Schuh8bd96322020-02-13 21:18:22 -080063class EventSchedulerScheduler;
64
Alex Perrycb7da4b2019-08-28 19:35:56 -070065class EventScheduler {
66 public:
67 using ChannelType =
Austin Schuh8bd96322020-02-13 21:18:22 -080068 std::multimap<monotonic_clock::time_point, std::function<void()>>;
Alex Perrycb7da4b2019-08-28 19:35:56 -070069 using Token = ChannelType::iterator;
70
Austin Schuh87dd3832021-01-01 23:07:31 -080071 // Sets the time converter in use for this scheduler (and the corresponding
72 // node index)
73 void SetTimeConverter(size_t node_index, TimeConverter *converter) {
74 node_index_ = node_index;
75 converter_ = converter;
76 }
77
Alex Perrycb7da4b2019-08-28 19:35:56 -070078 // Schedule an event with a callback function
79 // Returns an iterator to the event
Austin Schuh8bd96322020-02-13 21:18:22 -080080 Token Schedule(monotonic_clock::time_point time,
Alex Perrycb7da4b2019-08-28 19:35:56 -070081 std::function<void()> callback);
82
Austin Schuh39788ff2019-12-01 18:22:57 -080083 // Schedules a callback when the event scheduler starts.
84 void ScheduleOnRun(std::function<void()> callback) {
85 on_run_.emplace_back(std::move(callback));
86 }
87
Alex Perrycb7da4b2019-08-28 19:35:56 -070088 Token InvalidToken() { return events_list_.end(); }
89
90 // Deschedule an event by its iterator
91 void Deschedule(Token token);
92
Austin Schuh8bd96322020-02-13 21:18:22 -080093 // Runs the OnRun callbacks.
94 void RunOnRun();
Alex Perrycb7da4b2019-08-28 19:35:56 -070095
Austin Schuh8bd96322020-02-13 21:18:22 -080096 // Returns true if events are being handled.
97 inline bool is_running() const;
Alex Perrycb7da4b2019-08-28 19:35:56 -070098
Austin Schuh8bd96322020-02-13 21:18:22 -080099 // Returns the timestamp of the next event to trigger.
100 aos::monotonic_clock::time_point OldestEvent();
101 // Handles the next event.
102 void CallOldestEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700103
Austin Schuh8bd96322020-02-13 21:18:22 -0800104 // Converts a time to the distributed clock for scheduling and cross-node time
105 // measurement.
106 distributed_clock::time_point ToDistributedClock(
107 monotonic_clock::time_point time) const {
Austin Schuh87dd3832021-01-01 23:07:31 -0800108 return converter_->ToDistributedClock(node_index_, time);
Austin Schuh8bd96322020-02-13 21:18:22 -0800109 }
110
111 // Takes the distributed time and converts it to the monotonic clock for this
112 // node.
113 monotonic_clock::time_point FromDistributedClock(
114 distributed_clock::time_point time) const {
Austin Schuh87dd3832021-01-01 23:07:31 -0800115 return converter_->FromDistributedClock(node_index_, time);
Austin Schuh8bd96322020-02-13 21:18:22 -0800116 }
117
118 // Returns the current monotonic time on this node calculated from the
119 // distributed clock.
120 inline monotonic_clock::time_point monotonic_now() const;
121
Alex Perrycb7da4b2019-08-28 19:35:56 -0700122 private:
Austin Schuh8bd96322020-02-13 21:18:22 -0800123 friend class EventSchedulerScheduler;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700124 // Current execution time.
Austin Schuhbe69cf32020-08-27 11:38:33 -0700125 monotonic_clock::time_point monotonic_now_ = monotonic_clock::epoch();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700126
Austin Schuh8bd96322020-02-13 21:18:22 -0800127 // List of functions to run (once) when running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800128 std::vector<std::function<void()>> on_run_;
129
Alex Perrycb7da4b2019-08-28 19:35:56 -0700130 // Multimap holding times to run functions. These are stored in order, and
131 // the order is the callback tree.
132 ChannelType events_list_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800133
134 // Pointer to the actual scheduler.
135 EventSchedulerScheduler *scheduler_scheduler_ = nullptr;
Austin Schuh87dd3832021-01-01 23:07:31 -0800136
137 // Node index handle to be handed back to the TimeConverter. This lets the
138 // same time converter be used for all the nodes, and the node index
139 // distinguish which one.
140 size_t node_index_ = 0;
141
142 // Converts time by doing nothing to it.
143 class UnityConverter final : public TimeConverter {
144 public:
145 distributed_clock::time_point ToDistributedClock(
146 size_t /*node_index*/, monotonic_clock::time_point time) override {
147 return distributed_clock::epoch() + time.time_since_epoch();
148 }
149
150 monotonic_clock::time_point FromDistributedClock(
151 size_t /*node_index*/, distributed_clock::time_point time) override {
152 return monotonic_clock::epoch() + time.time_since_epoch();
153 }
154 };
155
156 UnityConverter unity_converter_;
157
158 TimeConverter *converter_ = &unity_converter_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159};
160
Austin Schuh8bd96322020-02-13 21:18:22 -0800161// We need a heap of heaps...
162//
163// Events in a node have a very well defined progression of time. It is linear
164// and well represented by the monotonic clock.
165//
166// Events across nodes don't follow this well. Time skews between the two nodes
167// all the time. We also don't know the function ahead of time which converts
168// from each node's monotonic clock to the distributed clock (our unified base
169// time which is likely the average time between nodes).
170//
171// This pushes us towards merge sort. Sorting each node's events with a heap
172// like we used to be doing, and then sorting each of those nodes independently.
173class EventSchedulerScheduler {
174 public:
175 // Adds an event scheduler to the list.
176 void AddEventScheduler(EventScheduler *scheduler);
177
178 // Runs until there are no more events or Exit is called.
179 void Run();
180
181 // Stops running.
182 void Exit() { is_running_ = false; }
183
184 bool is_running() const { return is_running_; }
185
186 // Runs for a duration on the distributed clock. Time on the distributed
187 // clock should be very representative of time on each node, but won't be
188 // exactly the same.
189 void RunFor(distributed_clock::duration duration);
190
191 // Returns the current distributed time.
192 distributed_clock::time_point distributed_now() const { return now_; }
193
194 private:
195 // Handles running the OnRun functions.
196 void RunOnRun() {
197 CHECK(!is_running_);
198 is_running_ = true;
199 for (EventScheduler *scheduler : schedulers_) {
200 scheduler->RunOnRun();
201 }
202 }
203
204 // Returns the next event time and scheduler on which to run it.
205 std::tuple<distributed_clock::time_point, EventScheduler *> OldestEvent();
206
207 // True if we are running.
208 bool is_running_ = false;
209 // The current time.
210 distributed_clock::time_point now_ = distributed_clock::epoch();
211 // List of schedulers to run in sync.
212 std::vector<EventScheduler *> schedulers_;
213};
214
215inline monotonic_clock::time_point EventScheduler::monotonic_now() const {
Austin Schuh87dd3832021-01-01 23:07:31 -0800216 return FromDistributedClock(scheduler_scheduler_->distributed_now());
Austin Schuh8bd96322020-02-13 21:18:22 -0800217}
218
219inline bool EventScheduler::is_running() const {
220 return scheduler_scheduler_->is_running();
221}
222
Alex Perrycb7da4b2019-08-28 19:35:56 -0700223} // namespace aos
224
225#endif // AOS_EVENTS_EVENT_SCHEDULER_H_