blob: e6ba4bf5df6303ef669b35d3e8bbab30e3506eab [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_SIMULATED_EVENT_LOOP_H_
2#define AOS_EVENTS_SIMULATED_EVENT_LOOP_H_
3
4#include <algorithm>
Brian Silverman601b9722020-06-18 14:33:43 -07005#include <functional>
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <map>
7#include <memory>
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08008#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07009#include <unordered_set>
10#include <utility>
11#include <vector>
12
13#include "absl/container/btree_map.h"
14#include "aos/events/event_loop.h"
15#include "aos/events/event_scheduler.h"
Austin Schuhe1dafe42020-01-06 21:12:03 -080016#include "aos/events/simple_channel.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070017#include "aos/flatbuffer_merge.h"
18#include "aos/flatbuffers.h"
19#include "aos/ipc_lib/index.h"
Austin Schuh4385b142021-03-14 21:31:13 -070020#include "aos/uuid.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "glog/logging.h"
22
23namespace aos {
24
25// Class for simulated fetchers.
26class SimulatedChannel;
27
Austin Schuhac0771c2020-01-07 18:36:30 -080028class NodeEventLoopFactory;
Austin Schuh057d29f2021-08-21 23:05:15 -070029class SimulatedEventLoop;
Austin Schuh898f4972020-01-11 17:21:25 -080030namespace message_bridge {
31class SimulatedMessageBridge;
32}
Austin Schuhac0771c2020-01-07 18:36:30 -080033
34// There are 2 concepts needed to support multi-node simulations.
35// 1) The node. This is implemented with NodeEventLoopFactory.
36// 2) The "robot" which runs multiple nodes. This is implemented with
37// SimulatedEventLoopFactory.
38//
39// To make things easier, SimulatedEventLoopFactory takes an optional Node
40// argument if you want to make event loops without interacting with the
41// NodeEventLoopFactory object.
42//
43// The basic flow goes something like as follows:
44//
45// SimulatedEventLoopFactory factory(config);
46// const Node *pi1 = configuration::GetNode(factory.configuration(), "pi1");
47// std::unique_ptr<EventLoop> event_loop = factory.MakeEventLoop("ping", pi1);
48//
49// Or
50//
51// SimulatedEventLoopFactory factory(config);
52// const Node *pi1 = configuration::GetNode(factory.configuration(), "pi1");
53// NodeEventLoopFactory *pi1_factory = factory.GetNodeEventLoopFactory(pi1);
54// std::unique_ptr<EventLoop> event_loop = pi1_factory.MakeEventLoop("ping");
55//
56// The distributed_clock is used to be the base time. NodeEventLoopFactory has
57// all the information needed to adjust both the realtime and monotonic clocks
58// relative to the distributed_clock.
Alex Perrycb7da4b2019-08-28 19:35:56 -070059class SimulatedEventLoopFactory {
60 public:
61 // Constructs a SimulatedEventLoopFactory with the provided configuration.
62 // This configuration must remain in scope for the lifetime of the factory and
63 // all sub-objects.
64 SimulatedEventLoopFactory(const Configuration *configuration);
65 ~SimulatedEventLoopFactory();
66
Austin Schuh58646e22021-08-23 23:51:46 -070067 SimulatedEventLoopFactory(const SimulatedEventLoopFactory &) = delete;
68 SimulatedEventLoopFactory &operator=(const SimulatedEventLoopFactory &) =
69 delete;
70 SimulatedEventLoopFactory(SimulatedEventLoopFactory &&) = delete;
71 SimulatedEventLoopFactory &operator=(SimulatedEventLoopFactory &&) = delete;
72
Austin Schuhac0771c2020-01-07 18:36:30 -080073 // Creates an event loop. If running in a multi-node environment, node needs
74 // to point to the node to create this event loop on.
75 ::std::unique_ptr<EventLoop> MakeEventLoop(std::string_view name,
76 const Node *node = nullptr);
77
78 // Returns the NodeEventLoopFactory for the provided node. The returned
79 // NodeEventLoopFactory is owned by the SimulatedEventLoopFactory and has a
80 // lifetime identical to the factory.
81 NodeEventLoopFactory *GetNodeEventLoopFactory(const Node *node);
Austin Schuh057d29f2021-08-21 23:05:15 -070082 NodeEventLoopFactory *GetNodeEventLoopFactory(std::string_view node);
Alex Perrycb7da4b2019-08-28 19:35:56 -070083
Austin Schuh87dd3832021-01-01 23:07:31 -080084 // Sets the time converter for all nodes.
85 void SetTimeConverter(TimeConverter *time_converter);
86
Austin Schuh58646e22021-08-23 23:51:46 -070087 // Starts executing the event loops unconditionally until Exit is called or
88 // all the nodes have shut down.
Alex Perrycb7da4b2019-08-28 19:35:56 -070089 void Run();
90 // Executes the event loops for a duration.
Austin Schuhac0771c2020-01-07 18:36:30 -080091 void RunFor(distributed_clock::duration duration);
Alex Perrycb7da4b2019-08-28 19:35:56 -070092
93 // Stops executing all event loops. Meant to be called from within an event
94 // loop handler.
Austin Schuh8fb315a2020-11-19 22:33:58 -080095 void Exit();
Alex Perrycb7da4b2019-08-28 19:35:56 -070096
Austin Schuhac0771c2020-01-07 18:36:30 -080097 const std::vector<const Node *> &nodes() const { return nodes_; }
98
99 // Sets the simulated send delay for all messages sent within a single node.
Austin Schuh7d87b672019-12-01 20:23:49 -0800100 void set_send_delay(std::chrono::nanoseconds send_delay);
Austin Schuhac0771c2020-01-07 18:36:30 -0800101 std::chrono::nanoseconds send_delay() const { return send_delay_; }
102
103 // Sets the simulated network delay for messages forwarded between nodes.
Brian Silvermana7c62052020-04-28 16:52:27 -0700104 void set_network_delay(std::chrono::nanoseconds network_delay) {
105 network_delay_ = network_delay;
106 }
Austin Schuhac0771c2020-01-07 18:36:30 -0800107 std::chrono::nanoseconds network_delay() const { return network_delay_; }
108
109 // Returns the clock used to synchronize the nodes.
110 distributed_clock::time_point distributed_now() const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800111 return scheduler_scheduler_.distributed_now();
Austin Schuhac0771c2020-01-07 18:36:30 -0800112 }
113
114 // Returns the configuration used for everything.
115 const Configuration *configuration() const { return configuration_; }
116
Austin Schuh6f3babe2020-01-26 20:34:50 -0800117 // Disables forwarding for this channel. This should be used very rarely only
118 // for things like the logger.
119 void DisableForwarding(const Channel *channel);
120
Austin Schuh4c3b9702020-08-30 11:34:55 -0700121 // Disables the messages sent by the simulated message gateway.
122 void DisableStatistics();
Austin Schuh48205e62021-11-12 14:13:18 -0800123 // Enables the messages sent by the simulated message gateway.
124 void EnableStatistics();
Austin Schuh4c3b9702020-08-30 11:34:55 -0700125
Austin Schuh2928ebe2021-02-07 22:10:27 -0800126 // Calls SkipTimingReport() on all EventLoops used as part of the
127 // infrastructure. This may improve the performance of long-simulated-duration
128 // tests.
129 void SkipTimingReport();
130
Austin Schuhe33c08d2022-02-03 18:15:21 -0800131 // Re-enables application creation for the duration of fn. This is mostly to
132 // allow use cases like log reading to create applications after the node
133 // starts up without stopping execution.
134 void AllowApplicationCreationDuring(std::function<void()> fn);
135
James Kuszmaulb67409b2022-06-20 16:25:03 -0700136 // Sets the realtime replay rate. A value of 1.0 will cause the scheduler to
137 // try to play events in realtime. 0.5 will run at half speed. Use infinity
138 // (the default) to run as fast as possible. This can be changed during
139 // run-time.
140 void SetRealtimeReplayRate(double replay_rate);
141
142 // Access to the internal scheduler's epoll object for realtime replay.
143 internal::EPoll *scheduler_epoll() { return scheduler_scheduler_.epoll(); }
144
Austin Schuhac0771c2020-01-07 18:36:30 -0800145 private:
Austin Schuhc0b0f722020-12-12 18:36:06 -0800146 friend class NodeEventLoopFactory;
147
Austin Schuhac0771c2020-01-07 18:36:30 -0800148 const Configuration *const configuration_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800149 EventSchedulerScheduler scheduler_scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800150
151 std::chrono::nanoseconds send_delay_ = std::chrono::microseconds(50);
152 std::chrono::nanoseconds network_delay_ = std::chrono::microseconds(100);
153
Austin Schuh58646e22021-08-23 23:51:46 -0700154 std::unique_ptr<message_bridge::SimulatedMessageBridge> bridge_;
155
Austin Schuhac0771c2020-01-07 18:36:30 -0800156 std::vector<std::unique_ptr<NodeEventLoopFactory>> node_factories_;
157
158 std::vector<const Node *> nodes_;
159};
160
161// This class holds all the state required to be a single node.
162class NodeEventLoopFactory {
163 public:
Austin Schuh057d29f2021-08-21 23:05:15 -0700164 ~NodeEventLoopFactory();
165
James Kuszmaul890c2492022-04-06 14:59:31 -0700166 // Whether a given event loop should have its senders checked for messages
167 // being sent too fast. Should only be used by the LogReader or other highly
168 // specialized applications that need to be able to bypass normal behaviors.
169 enum class CheckSentTooFast { kNo, kYes };
170 // Whether the created EventLoop should be the only one allowed to send on all
171 // of its channels. Mostly useful for the LogReader, to allow us to confirm
172 // whether the LogReader is conflicting with the output of any applications
173 // being run in replay.
174 enum class ExclusiveSenders { kNo, kYes };
175 struct EventLoopOptions {
176 CheckSentTooFast check_sent_too_fast;
177 ExclusiveSenders exclusive_senders;
178 };
179
180 // Takes the name for the event loop and a struct of options for selecting
181 // what checks to run for the event loop in question.
182 std::unique_ptr<EventLoop> MakeEventLoop(
183 std::string_view name,
184 EventLoopOptions options = EventLoopOptions{CheckSentTooFast::kYes,
185 ExclusiveSenders::kNo});
Austin Schuh7d87b672019-12-01 20:23:49 -0800186
Austin Schuh217a9782019-12-21 23:02:50 -0800187 // Returns the node that this factory is running as, or nullptr if this is a
188 // single node setup.
189 const Node *node() const { return node_; }
190
Austin Schuh92547522019-12-28 14:33:43 -0800191 // Sets realtime clock to realtime_now for a given monotonic clock.
192 void SetRealtimeOffset(monotonic_clock::time_point monotonic_now,
193 realtime_clock::time_point realtime_now) {
Austin Schuhac0771c2020-01-07 18:36:30 -0800194 realtime_offset_ =
195 realtime_now.time_since_epoch() - monotonic_now.time_since_epoch();
Austin Schuh92547522019-12-28 14:33:43 -0800196 }
197
Austin Schuhac0771c2020-01-07 18:36:30 -0800198 // Returns the current time on both clocks.
199 inline monotonic_clock::time_point monotonic_now() const;
200 inline realtime_clock::time_point realtime_now() const;
Austin Schuh58646e22021-08-23 23:51:46 -0700201 inline distributed_clock::time_point distributed_now() const;
Austin Schuh39788ff2019-12-01 18:22:57 -0800202
Austin Schuhfaec5e12020-11-05 17:39:55 -0800203 const Configuration *configuration() const {
204 return factory_->configuration();
205 }
206
Austin Schuh58646e22021-08-23 23:51:46 -0700207 // Starts the node up by calling the OnStartup handlers. These get called
208 // every time a node is started.
209
210 // Called when a node has started. This is typically when a log file starts
211 // for a node.
212 void OnStartup(std::function<void()> &&fn);
213
214 // Called when a node shuts down. These get called every time a node is shut
215 // down. All applications are destroyed right after the last OnShutdown
216 // callback is called.
217 void OnShutdown(std::function<void()> &&fn);
218
219 // Starts an application if the configuration says it should be started on
220 // this node. name is the name of the application. args are the constructor
221 // args for the Main class. Returns a pointer to the class that was started
222 // if it was started, or nullptr.
223 template <class Main, class... Args>
Austin Schuh60e77942022-05-16 17:48:24 -0700224 Main *MaybeStart(std::string_view name, Args &&...args);
Austin Schuh58646e22021-08-23 23:51:46 -0700225
226 // Starts an application regardless of if the config says to or not. name is
227 // the name of the application, and args are the constructor args for the
228 // application. Returns a pointer to the class that was started.
229 template <class Main, class... Args>
Austin Schuh60e77942022-05-16 17:48:24 -0700230 Main *AlwaysStart(std::string_view name, Args &&...args);
Austin Schuh58646e22021-08-23 23:51:46 -0700231
Austin Schuh898f4972020-01-11 17:21:25 -0800232 // Returns the simulated network delay for messages forwarded between nodes.
233 std::chrono::nanoseconds network_delay() const {
234 return factory_->network_delay();
235 }
236 // Returns the simulated send delay for all messages sent within a single
237 // node.
238 std::chrono::nanoseconds send_delay() const { return factory_->send_delay(); }
239
Austin Schuh58646e22021-08-23 23:51:46 -0700240 size_t boot_count() const { return scheduler_.boot_count(); }
241
Austin Schuh8bd96322020-02-13 21:18:22 -0800242 // TODO(austin): Private for the following?
243
Austin Schuhac0771c2020-01-07 18:36:30 -0800244 // Converts a time to the distributed clock for scheduling and cross-node time
245 // measurement.
Austin Schuh87dd3832021-01-01 23:07:31 -0800246 // Note: converting time too far in the future can cause problems when
247 // replaying logs. Only convert times in the present or near past.
Austin Schuhac0771c2020-01-07 18:36:30 -0800248 inline distributed_clock::time_point ToDistributedClock(
249 monotonic_clock::time_point time) const;
Austin Schuh58646e22021-08-23 23:51:46 -0700250 inline logger::BootTimestamp FromDistributedClock(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700251 distributed_clock::time_point time) const;
Austin Schuhac0771c2020-01-07 18:36:30 -0800252
Austin Schuh87dd3832021-01-01 23:07:31 -0800253 // Sets the class used to convert time. This pointer must out-live the
254 // SimulatedEventLoopFactory.
255 void SetTimeConverter(TimeConverter *time_converter) {
256 scheduler_.SetTimeConverter(
257 configuration::GetNodeIndex(factory_->configuration(), node_),
258 time_converter);
Austin Schuhcde938c2020-02-02 17:30:07 -0800259 }
260
Austin Schuh20ac95d2020-12-05 17:24:19 -0800261 // Returns the boot UUID for this node.
Austin Schuh58646e22021-08-23 23:51:46 -0700262 const UUID &boot_uuid() {
263 if (boot_uuid_ == UUID::Zero()) {
264 boot_uuid_ = scheduler_.boot_uuid();
265 }
266 return boot_uuid_;
267 }
Austin Schuh20ac95d2020-12-05 17:24:19 -0800268
Austin Schuhc0b0f722020-12-12 18:36:06 -0800269 // Stops forwarding messages to the other node, and reports disconnected in
270 // the ServerStatistics message for this node, and the ClientStatistics for
271 // the other node.
272 void Disconnect(const Node *other);
273 // Resumes forwarding messages.
274 void Connect(const Node *other);
275
Austin Schuh48205e62021-11-12 14:13:18 -0800276 // Disables the messages sent by the simulated message gateway.
277 void DisableStatistics();
278 // Enables the messages sent by the simulated message gateway.
279 void EnableStatistics();
280
Austin Schuhac0771c2020-01-07 18:36:30 -0800281 private:
282 friend class SimulatedEventLoopFactory;
Austin Schuh057d29f2021-08-21 23:05:15 -0700283 NodeEventLoopFactory(EventSchedulerScheduler *scheduler_scheduler,
284 SimulatedEventLoopFactory *factory, const Node *node);
Austin Schuhac0771c2020-01-07 18:36:30 -0800285
Austin Schuh48205e62021-11-12 14:13:18 -0800286 // Skips timing reports on all event loops on this node.
287 void SkipTimingReport();
288
Austin Schuh58646e22021-08-23 23:51:46 -0700289 // Helpers to restart.
290 void ScheduleStartup();
291 void Startup();
292 void Shutdown();
293
Austin Schuh8bd96322020-02-13 21:18:22 -0800294 EventScheduler scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800295 SimulatedEventLoopFactory *const factory_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800296
Austin Schuh58646e22021-08-23 23:51:46 -0700297 UUID boot_uuid_ = UUID::Zero();
Austin Schuh20ac95d2020-12-05 17:24:19 -0800298
Austin Schuh217a9782019-12-21 23:02:50 -0800299 const Node *const node_;
300
Austin Schuh48205e62021-11-12 14:13:18 -0800301 bool skip_timing_report_ = false;
302
Austin Schuh057d29f2021-08-21 23:05:15 -0700303 std::vector<SimulatedEventLoop *> event_loops_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800304
Austin Schuhac0771c2020-01-07 18:36:30 -0800305 std::chrono::nanoseconds realtime_offset_ = std::chrono::seconds(0);
306
307 // Map from name, type to queue.
308 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> channels_;
309
310 // pid so we get unique timing reports.
Austin Schuh39788ff2019-12-01 18:22:57 -0800311 pid_t tid_ = 0;
Austin Schuh58646e22021-08-23 23:51:46 -0700312
313 // True if we are started.
314 bool started_ = false;
315
316 std::vector<std::function<void()>> pending_on_startup_;
317 std::vector<std::function<void()>> on_startup_;
318 std::vector<std::function<void()>> on_shutdown_;
319
320 // Base class for an application to start. This shouldn't be used directly.
321 struct Application {
322 Application(NodeEventLoopFactory *node_factory, std::string_view name)
323 : event_loop(node_factory->MakeEventLoop(name)) {}
324 virtual ~Application() {}
325
326 std::unique_ptr<EventLoop> event_loop;
327 };
328
329 // Subclass to do type erasure for the base class. Holds an instance of a
330 // specific class. Use SimulationStarter instead.
331 template <typename Main>
332 struct TypedApplication : public Application {
333 // Constructs an Application by delegating the arguments used to construct
334 // the event loop to Application and the rest of the args to the actual
335 // application.
336 template <class... Args>
337 TypedApplication(NodeEventLoopFactory *node_factory, std::string_view name,
Austin Schuh60e77942022-05-16 17:48:24 -0700338 Args &&...args)
Austin Schuh58646e22021-08-23 23:51:46 -0700339 : Application(node_factory, name),
340 main(event_loop.get(), std::forward<Args>(args)...) {
341 VLOG(1) << node_factory->scheduler_.distributed_now() << " "
342 << (node_factory->node() == nullptr
343 ? ""
344 : node_factory->node()->name()->str() + " ")
345 << node_factory->monotonic_now() << " Starting Application \""
346 << name << "\"";
347 }
348 ~TypedApplication() override {}
349
350 Main main;
351 };
352
353 std::vector<std::unique_ptr<Application>> applications_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354};
355
Austin Schuh58646e22021-08-23 23:51:46 -0700356template <class Main, class... Args>
Austin Schuh60e77942022-05-16 17:48:24 -0700357Main *NodeEventLoopFactory::MaybeStart(std::string_view name, Args &&...args) {
Austin Schuh58646e22021-08-23 23:51:46 -0700358 const aos::Application *application =
359 configuration::GetApplication(configuration(), node(), name);
360
361 if (application != nullptr) {
362 return AlwaysStart<Main>(name, std::forward<Args>(args)...);
363 }
364 return nullptr;
365}
366
367template <class Main, class... Args>
Austin Schuh60e77942022-05-16 17:48:24 -0700368Main *NodeEventLoopFactory::AlwaysStart(std::string_view name, Args &&...args) {
Austin Schuh58646e22021-08-23 23:51:46 -0700369 std::unique_ptr<TypedApplication<Main>> app =
370 std::make_unique<TypedApplication<Main>>(this, name,
371 std::forward<Args>(args)...);
372 Main *main_ptr = &app->main;
373 applications_.emplace_back(std::move(app));
374 return main_ptr;
375}
376
Austin Schuhac0771c2020-01-07 18:36:30 -0800377inline monotonic_clock::time_point NodeEventLoopFactory::monotonic_now() const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800378 // TODO(austin): Confirm that time never goes backwards?
Austin Schuhbe69cf32020-08-27 11:38:33 -0700379 return scheduler_.monotonic_now();
Austin Schuhac0771c2020-01-07 18:36:30 -0800380}
381
382inline realtime_clock::time_point NodeEventLoopFactory::realtime_now() const {
383 return realtime_clock::time_point(monotonic_now().time_since_epoch() +
384 realtime_offset_);
385}
386
Austin Schuh58646e22021-08-23 23:51:46 -0700387inline distributed_clock::time_point NodeEventLoopFactory::distributed_now()
388 const {
389 return scheduler_.distributed_now();
390}
391
392inline logger::BootTimestamp NodeEventLoopFactory::FromDistributedClock(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700393 distributed_clock::time_point time) const {
394 return scheduler_.FromDistributedClock(time);
395}
396
Austin Schuhac0771c2020-01-07 18:36:30 -0800397inline distributed_clock::time_point NodeEventLoopFactory::ToDistributedClock(
398 monotonic_clock::time_point time) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800399 return scheduler_.ToDistributedClock(time);
Austin Schuhac0771c2020-01-07 18:36:30 -0800400}
401
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402} // namespace aos
403
404#endif // AOS_EVENTS_SIMULATED_EVENT_LOOP_H_