blob: f981ef28b90f1bcf135193c4223a075646a0b874 [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;
Austin Schuhb7c8d2a2021-07-19 19:22:12 -070061
62 // Called whenever time passes this point and we can forget about it.
63 virtual void ObserveTimePassed(distributed_clock::time_point time) = 0;
Austin Schuha9abc032021-01-01 16:46:19 -080064};
65
Austin Schuh8bd96322020-02-13 21:18:22 -080066class EventSchedulerScheduler;
67
Alex Perrycb7da4b2019-08-28 19:35:56 -070068class EventScheduler {
69 public:
70 using ChannelType =
Austin Schuh8bd96322020-02-13 21:18:22 -080071 std::multimap<monotonic_clock::time_point, std::function<void()>>;
Alex Perrycb7da4b2019-08-28 19:35:56 -070072 using Token = ChannelType::iterator;
73
Austin Schuh87dd3832021-01-01 23:07:31 -080074 // Sets the time converter in use for this scheduler (and the corresponding
75 // node index)
76 void SetTimeConverter(size_t node_index, TimeConverter *converter) {
77 node_index_ = node_index;
78 converter_ = converter;
79 }
80
Alex Perrycb7da4b2019-08-28 19:35:56 -070081 // Schedule an event with a callback function
82 // Returns an iterator to the event
Austin Schuh8bd96322020-02-13 21:18:22 -080083 Token Schedule(monotonic_clock::time_point time,
Alex Perrycb7da4b2019-08-28 19:35:56 -070084 std::function<void()> callback);
85
Austin Schuh39788ff2019-12-01 18:22:57 -080086 // Schedules a callback when the event scheduler starts.
87 void ScheduleOnRun(std::function<void()> callback) {
88 on_run_.emplace_back(std::move(callback));
89 }
90
Alex Perrycb7da4b2019-08-28 19:35:56 -070091 Token InvalidToken() { return events_list_.end(); }
92
93 // Deschedule an event by its iterator
94 void Deschedule(Token token);
95
Austin Schuh8bd96322020-02-13 21:18:22 -080096 // Runs the OnRun callbacks.
97 void RunOnRun();
Alex Perrycb7da4b2019-08-28 19:35:56 -070098
Austin Schuh8bd96322020-02-13 21:18:22 -080099 // Returns true if events are being handled.
100 inline bool is_running() const;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700101
Austin Schuh8bd96322020-02-13 21:18:22 -0800102 // Returns the timestamp of the next event to trigger.
103 aos::monotonic_clock::time_point OldestEvent();
104 // Handles the next event.
105 void CallOldestEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700106
Austin Schuh8bd96322020-02-13 21:18:22 -0800107 // Converts a time to the distributed clock for scheduling and cross-node time
108 // measurement.
109 distributed_clock::time_point ToDistributedClock(
110 monotonic_clock::time_point time) const {
Austin Schuh87dd3832021-01-01 23:07:31 -0800111 return converter_->ToDistributedClock(node_index_, time);
Austin Schuh8bd96322020-02-13 21:18:22 -0800112 }
113
114 // Takes the distributed time and converts it to the monotonic clock for this
115 // node.
116 monotonic_clock::time_point FromDistributedClock(
117 distributed_clock::time_point time) const {
Austin Schuh87dd3832021-01-01 23:07:31 -0800118 return converter_->FromDistributedClock(node_index_, time);
Austin Schuh8bd96322020-02-13 21:18:22 -0800119 }
120
121 // Returns the current monotonic time on this node calculated from the
122 // distributed clock.
123 inline monotonic_clock::time_point monotonic_now() const;
124
Alex Perrycb7da4b2019-08-28 19:35:56 -0700125 private:
Austin Schuh8bd96322020-02-13 21:18:22 -0800126 friend class EventSchedulerScheduler;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700127 // Current execution time.
Austin Schuhbe69cf32020-08-27 11:38:33 -0700128 monotonic_clock::time_point monotonic_now_ = monotonic_clock::epoch();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700129
Austin Schuh8bd96322020-02-13 21:18:22 -0800130 // List of functions to run (once) when running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800131 std::vector<std::function<void()>> on_run_;
132
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133 // Multimap holding times to run functions. These are stored in order, and
134 // the order is the callback tree.
135 ChannelType events_list_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800136
137 // Pointer to the actual scheduler.
138 EventSchedulerScheduler *scheduler_scheduler_ = nullptr;
Austin Schuh87dd3832021-01-01 23:07:31 -0800139
140 // Node index handle to be handed back to the TimeConverter. This lets the
141 // same time converter be used for all the nodes, and the node index
142 // distinguish which one.
143 size_t node_index_ = 0;
144
145 // Converts time by doing nothing to it.
146 class UnityConverter final : public TimeConverter {
147 public:
148 distributed_clock::time_point ToDistributedClock(
149 size_t /*node_index*/, monotonic_clock::time_point time) override {
150 return distributed_clock::epoch() + time.time_since_epoch();
151 }
152
153 monotonic_clock::time_point FromDistributedClock(
154 size_t /*node_index*/, distributed_clock::time_point time) override {
155 return monotonic_clock::epoch() + time.time_since_epoch();
156 }
Austin Schuhb7c8d2a2021-07-19 19:22:12 -0700157
158 void ObserveTimePassed(distributed_clock::time_point /*time*/) override {}
Austin Schuh87dd3832021-01-01 23:07:31 -0800159 };
160
161 UnityConverter unity_converter_;
162
163 TimeConverter *converter_ = &unity_converter_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164};
165
Austin Schuh8bd96322020-02-13 21:18:22 -0800166// We need a heap of heaps...
167//
168// Events in a node have a very well defined progression of time. It is linear
169// and well represented by the monotonic clock.
170//
171// Events across nodes don't follow this well. Time skews between the two nodes
172// all the time. We also don't know the function ahead of time which converts
173// from each node's monotonic clock to the distributed clock (our unified base
174// time which is likely the average time between nodes).
175//
176// This pushes us towards merge sort. Sorting each node's events with a heap
177// like we used to be doing, and then sorting each of those nodes independently.
178class EventSchedulerScheduler {
179 public:
180 // Adds an event scheduler to the list.
181 void AddEventScheduler(EventScheduler *scheduler);
182
183 // Runs until there are no more events or Exit is called.
184 void Run();
185
186 // Stops running.
187 void Exit() { is_running_ = false; }
188
189 bool is_running() const { return is_running_; }
190
191 // Runs for a duration on the distributed clock. Time on the distributed
192 // clock should be very representative of time on each node, but won't be
193 // exactly the same.
194 void RunFor(distributed_clock::duration duration);
195
196 // Returns the current distributed time.
197 distributed_clock::time_point distributed_now() const { return now_; }
198
199 private:
200 // Handles running the OnRun functions.
201 void RunOnRun() {
202 CHECK(!is_running_);
203 is_running_ = true;
204 for (EventScheduler *scheduler : schedulers_) {
205 scheduler->RunOnRun();
206 }
207 }
208
209 // Returns the next event time and scheduler on which to run it.
210 std::tuple<distributed_clock::time_point, EventScheduler *> OldestEvent();
211
212 // True if we are running.
213 bool is_running_ = false;
214 // The current time.
215 distributed_clock::time_point now_ = distributed_clock::epoch();
216 // List of schedulers to run in sync.
217 std::vector<EventScheduler *> schedulers_;
218};
219
220inline monotonic_clock::time_point EventScheduler::monotonic_now() const {
Austin Schuh87dd3832021-01-01 23:07:31 -0800221 return FromDistributedClock(scheduler_scheduler_->distributed_now());
Austin Schuh8bd96322020-02-13 21:18:22 -0800222}
223
224inline bool EventScheduler::is_running() const {
225 return scheduler_scheduler_->is_running();
226}
227
Alex Perrycb7da4b2019-08-28 19:35:56 -0700228} // namespace aos
229
230#endif // AOS_EVENTS_EVENT_SCHEDULER_H_