blob: 9d5d11feb475799581139edd93df94805f0d3c55 [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();
James Kuszmaul94ca5132022-07-19 09:11:08 -0700123 // Disables statistics sent by the simulated message gateway, and prevents
124 // EnableStatistcs from ever being called again (used by LogReader).
125 void PermanentlyDisableStatistics();
Austin Schuh48205e62021-11-12 14:13:18 -0800126 // Enables the messages sent by the simulated message gateway.
127 void EnableStatistics();
Austin Schuh4c3b9702020-08-30 11:34:55 -0700128
Austin Schuh2928ebe2021-02-07 22:10:27 -0800129 // Calls SkipTimingReport() on all EventLoops used as part of the
130 // infrastructure. This may improve the performance of long-simulated-duration
131 // tests.
132 void SkipTimingReport();
133
Austin Schuhe33c08d2022-02-03 18:15:21 -0800134 // Re-enables application creation for the duration of fn. This is mostly to
135 // allow use cases like log reading to create applications after the node
136 // starts up without stopping execution.
137 void AllowApplicationCreationDuring(std::function<void()> fn);
138
James Kuszmaulb67409b2022-06-20 16:25:03 -0700139 // Sets the realtime replay rate. A value of 1.0 will cause the scheduler to
140 // try to play events in realtime. 0.5 will run at half speed. Use infinity
141 // (the default) to run as fast as possible. This can be changed during
142 // run-time.
143 void SetRealtimeReplayRate(double replay_rate);
144
145 // Access to the internal scheduler's epoll object for realtime replay.
146 internal::EPoll *scheduler_epoll() { return scheduler_scheduler_.epoll(); }
147
Austin Schuhac0771c2020-01-07 18:36:30 -0800148 private:
Austin Schuhc0b0f722020-12-12 18:36:06 -0800149 friend class NodeEventLoopFactory;
150
Austin Schuhac0771c2020-01-07 18:36:30 -0800151 const Configuration *const configuration_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800152 EventSchedulerScheduler scheduler_scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800153
154 std::chrono::nanoseconds send_delay_ = std::chrono::microseconds(50);
155 std::chrono::nanoseconds network_delay_ = std::chrono::microseconds(100);
156
Austin Schuh58646e22021-08-23 23:51:46 -0700157 std::unique_ptr<message_bridge::SimulatedMessageBridge> bridge_;
158
Austin Schuhac0771c2020-01-07 18:36:30 -0800159 std::vector<std::unique_ptr<NodeEventLoopFactory>> node_factories_;
160
161 std::vector<const Node *> nodes_;
162};
163
164// This class holds all the state required to be a single node.
165class NodeEventLoopFactory {
166 public:
Austin Schuh057d29f2021-08-21 23:05:15 -0700167 ~NodeEventLoopFactory();
168
James Kuszmaul890c2492022-04-06 14:59:31 -0700169 // Whether a given event loop should have its senders checked for messages
170 // being sent too fast. Should only be used by the LogReader or other highly
171 // specialized applications that need to be able to bypass normal behaviors.
172 enum class CheckSentTooFast { kNo, kYes };
173 // Whether the created EventLoop should be the only one allowed to send on all
174 // of its channels. Mostly useful for the LogReader, to allow us to confirm
175 // whether the LogReader is conflicting with the output of any applications
176 // being run in replay.
177 enum class ExclusiveSenders { kNo, kYes };
178 struct EventLoopOptions {
179 CheckSentTooFast check_sent_too_fast;
180 ExclusiveSenders exclusive_senders;
James Kuszmaul94ca5132022-07-19 09:11:08 -0700181 // per_channel_exclusivity is used to list any exceptions to the overall
182 // exclusive_senders policy for this event loop.
183 std::vector<std::pair<const aos::Channel *, ExclusiveSenders>>
184 per_channel_exclusivity;
James Kuszmaul890c2492022-04-06 14:59:31 -0700185 };
186
187 // Takes the name for the event loop and a struct of options for selecting
188 // what checks to run for the event loop in question.
189 std::unique_ptr<EventLoop> MakeEventLoop(
190 std::string_view name,
James Kuszmaul94ca5132022-07-19 09:11:08 -0700191 EventLoopOptions options = EventLoopOptions{
192 CheckSentTooFast::kYes, ExclusiveSenders::kNo, {}});
Austin Schuh7d87b672019-12-01 20:23:49 -0800193
Austin Schuh217a9782019-12-21 23:02:50 -0800194 // Returns the node that this factory is running as, or nullptr if this is a
195 // single node setup.
196 const Node *node() const { return node_; }
197
Austin Schuh92547522019-12-28 14:33:43 -0800198 // Sets realtime clock to realtime_now for a given monotonic clock.
199 void SetRealtimeOffset(monotonic_clock::time_point monotonic_now,
200 realtime_clock::time_point realtime_now) {
Austin Schuhac0771c2020-01-07 18:36:30 -0800201 realtime_offset_ =
202 realtime_now.time_since_epoch() - monotonic_now.time_since_epoch();
Austin Schuh92547522019-12-28 14:33:43 -0800203 }
204
Austin Schuhac0771c2020-01-07 18:36:30 -0800205 // Returns the current time on both clocks.
206 inline monotonic_clock::time_point monotonic_now() const;
207 inline realtime_clock::time_point realtime_now() const;
Austin Schuh58646e22021-08-23 23:51:46 -0700208 inline distributed_clock::time_point distributed_now() const;
Austin Schuh39788ff2019-12-01 18:22:57 -0800209
Austin Schuhfaec5e12020-11-05 17:39:55 -0800210 const Configuration *configuration() const {
211 return factory_->configuration();
212 }
213
Austin Schuh58646e22021-08-23 23:51:46 -0700214 // Starts the node up by calling the OnStartup handlers. These get called
215 // every time a node is started.
216
217 // Called when a node has started. This is typically when a log file starts
218 // for a node.
219 void OnStartup(std::function<void()> &&fn);
220
221 // Called when a node shuts down. These get called every time a node is shut
222 // down. All applications are destroyed right after the last OnShutdown
223 // callback is called.
224 void OnShutdown(std::function<void()> &&fn);
225
226 // Starts an application if the configuration says it should be started on
227 // this node. name is the name of the application. args are the constructor
228 // args for the Main class. Returns a pointer to the class that was started
229 // if it was started, or nullptr.
230 template <class Main, class... Args>
Austin Schuh60e77942022-05-16 17:48:24 -0700231 Main *MaybeStart(std::string_view name, Args &&...args);
Austin Schuh58646e22021-08-23 23:51:46 -0700232
233 // Starts an application regardless of if the config says to or not. name is
234 // the name of the application, and args are the constructor args for the
235 // application. Returns a pointer to the class that was started.
236 template <class Main, class... Args>
Austin Schuh60e77942022-05-16 17:48:24 -0700237 Main *AlwaysStart(std::string_view name, Args &&...args);
Austin Schuh58646e22021-08-23 23:51:46 -0700238
Austin Schuh898f4972020-01-11 17:21:25 -0800239 // Returns the simulated network delay for messages forwarded between nodes.
240 std::chrono::nanoseconds network_delay() const {
241 return factory_->network_delay();
242 }
243 // Returns the simulated send delay for all messages sent within a single
244 // node.
245 std::chrono::nanoseconds send_delay() const { return factory_->send_delay(); }
246
Austin Schuh58646e22021-08-23 23:51:46 -0700247 size_t boot_count() const { return scheduler_.boot_count(); }
248
Austin Schuh8bd96322020-02-13 21:18:22 -0800249 // TODO(austin): Private for the following?
250
Austin Schuhac0771c2020-01-07 18:36:30 -0800251 // Converts a time to the distributed clock for scheduling and cross-node time
252 // measurement.
Austin Schuh87dd3832021-01-01 23:07:31 -0800253 // Note: converting time too far in the future can cause problems when
254 // replaying logs. Only convert times in the present or near past.
Austin Schuhac0771c2020-01-07 18:36:30 -0800255 inline distributed_clock::time_point ToDistributedClock(
256 monotonic_clock::time_point time) const;
Austin Schuh58646e22021-08-23 23:51:46 -0700257 inline logger::BootTimestamp FromDistributedClock(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700258 distributed_clock::time_point time) const;
Austin Schuhac0771c2020-01-07 18:36:30 -0800259
Austin Schuh87dd3832021-01-01 23:07:31 -0800260 // Sets the class used to convert time. This pointer must out-live the
261 // SimulatedEventLoopFactory.
262 void SetTimeConverter(TimeConverter *time_converter) {
263 scheduler_.SetTimeConverter(
264 configuration::GetNodeIndex(factory_->configuration(), node_),
265 time_converter);
Austin Schuhcde938c2020-02-02 17:30:07 -0800266 }
267
Austin Schuh20ac95d2020-12-05 17:24:19 -0800268 // Returns the boot UUID for this node.
Austin Schuh58646e22021-08-23 23:51:46 -0700269 const UUID &boot_uuid() {
270 if (boot_uuid_ == UUID::Zero()) {
271 boot_uuid_ = scheduler_.boot_uuid();
272 }
273 return boot_uuid_;
274 }
Austin Schuh20ac95d2020-12-05 17:24:19 -0800275
Austin Schuhc0b0f722020-12-12 18:36:06 -0800276 // Stops forwarding messages to the other node, and reports disconnected in
277 // the ServerStatistics message for this node, and the ClientStatistics for
278 // the other node.
279 void Disconnect(const Node *other);
280 // Resumes forwarding messages.
281 void Connect(const Node *other);
282
Austin Schuh48205e62021-11-12 14:13:18 -0800283 // Disables the messages sent by the simulated message gateway.
284 void DisableStatistics();
285 // Enables the messages sent by the simulated message gateway.
286 void EnableStatistics();
287
Austin Schuhac0771c2020-01-07 18:36:30 -0800288 private:
289 friend class SimulatedEventLoopFactory;
Austin Schuh057d29f2021-08-21 23:05:15 -0700290 NodeEventLoopFactory(EventSchedulerScheduler *scheduler_scheduler,
291 SimulatedEventLoopFactory *factory, const Node *node);
Austin Schuhac0771c2020-01-07 18:36:30 -0800292
Austin Schuh48205e62021-11-12 14:13:18 -0800293 // Skips timing reports on all event loops on this node.
294 void SkipTimingReport();
295
Austin Schuh58646e22021-08-23 23:51:46 -0700296 // Helpers to restart.
297 void ScheduleStartup();
298 void Startup();
299 void Shutdown();
300
Austin Schuh8bd96322020-02-13 21:18:22 -0800301 EventScheduler scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800302 SimulatedEventLoopFactory *const factory_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800303
Austin Schuh58646e22021-08-23 23:51:46 -0700304 UUID boot_uuid_ = UUID::Zero();
Austin Schuh20ac95d2020-12-05 17:24:19 -0800305
Austin Schuh217a9782019-12-21 23:02:50 -0800306 const Node *const node_;
307
Austin Schuh48205e62021-11-12 14:13:18 -0800308 bool skip_timing_report_ = false;
309
Austin Schuh057d29f2021-08-21 23:05:15 -0700310 std::vector<SimulatedEventLoop *> event_loops_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800311
Austin Schuhac0771c2020-01-07 18:36:30 -0800312 std::chrono::nanoseconds realtime_offset_ = std::chrono::seconds(0);
313
314 // Map from name, type to queue.
315 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> channels_;
316
317 // pid so we get unique timing reports.
Austin Schuh39788ff2019-12-01 18:22:57 -0800318 pid_t tid_ = 0;
Austin Schuh58646e22021-08-23 23:51:46 -0700319
320 // True if we are started.
321 bool started_ = false;
322
323 std::vector<std::function<void()>> pending_on_startup_;
324 std::vector<std::function<void()>> on_startup_;
325 std::vector<std::function<void()>> on_shutdown_;
326
327 // Base class for an application to start. This shouldn't be used directly.
328 struct Application {
329 Application(NodeEventLoopFactory *node_factory, std::string_view name)
330 : event_loop(node_factory->MakeEventLoop(name)) {}
331 virtual ~Application() {}
332
333 std::unique_ptr<EventLoop> event_loop;
334 };
335
336 // Subclass to do type erasure for the base class. Holds an instance of a
337 // specific class. Use SimulationStarter instead.
338 template <typename Main>
339 struct TypedApplication : public Application {
340 // Constructs an Application by delegating the arguments used to construct
341 // the event loop to Application and the rest of the args to the actual
342 // application.
343 template <class... Args>
344 TypedApplication(NodeEventLoopFactory *node_factory, std::string_view name,
Austin Schuh60e77942022-05-16 17:48:24 -0700345 Args &&...args)
Austin Schuh58646e22021-08-23 23:51:46 -0700346 : Application(node_factory, name),
347 main(event_loop.get(), std::forward<Args>(args)...) {
348 VLOG(1) << node_factory->scheduler_.distributed_now() << " "
349 << (node_factory->node() == nullptr
350 ? ""
351 : node_factory->node()->name()->str() + " ")
352 << node_factory->monotonic_now() << " Starting Application \""
353 << name << "\"";
354 }
355 ~TypedApplication() override {}
356
357 Main main;
358 };
359
360 std::vector<std::unique_ptr<Application>> applications_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700361};
362
Austin Schuh58646e22021-08-23 23:51:46 -0700363template <class Main, class... Args>
Austin Schuh60e77942022-05-16 17:48:24 -0700364Main *NodeEventLoopFactory::MaybeStart(std::string_view name, Args &&...args) {
Austin Schuh58646e22021-08-23 23:51:46 -0700365 const aos::Application *application =
366 configuration::GetApplication(configuration(), node(), name);
367
368 if (application != nullptr) {
369 return AlwaysStart<Main>(name, std::forward<Args>(args)...);
370 }
371 return nullptr;
372}
373
374template <class Main, class... Args>
Austin Schuh60e77942022-05-16 17:48:24 -0700375Main *NodeEventLoopFactory::AlwaysStart(std::string_view name, Args &&...args) {
Austin Schuh58646e22021-08-23 23:51:46 -0700376 std::unique_ptr<TypedApplication<Main>> app =
377 std::make_unique<TypedApplication<Main>>(this, name,
378 std::forward<Args>(args)...);
379 Main *main_ptr = &app->main;
380 applications_.emplace_back(std::move(app));
381 return main_ptr;
382}
383
Austin Schuhac0771c2020-01-07 18:36:30 -0800384inline monotonic_clock::time_point NodeEventLoopFactory::monotonic_now() const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800385 // TODO(austin): Confirm that time never goes backwards?
Austin Schuhbe69cf32020-08-27 11:38:33 -0700386 return scheduler_.monotonic_now();
Austin Schuhac0771c2020-01-07 18:36:30 -0800387}
388
389inline realtime_clock::time_point NodeEventLoopFactory::realtime_now() const {
390 return realtime_clock::time_point(monotonic_now().time_since_epoch() +
391 realtime_offset_);
392}
393
Austin Schuh58646e22021-08-23 23:51:46 -0700394inline distributed_clock::time_point NodeEventLoopFactory::distributed_now()
395 const {
396 return scheduler_.distributed_now();
397}
398
399inline logger::BootTimestamp NodeEventLoopFactory::FromDistributedClock(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700400 distributed_clock::time_point time) const {
401 return scheduler_.FromDistributedClock(time);
402}
403
Austin Schuhac0771c2020-01-07 18:36:30 -0800404inline distributed_clock::time_point NodeEventLoopFactory::ToDistributedClock(
405 monotonic_clock::time_point time) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800406 return scheduler_.ToDistributedClock(time);
Austin Schuhac0771c2020-01-07 18:36:30 -0800407}
408
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409} // namespace aos
410
411#endif // AOS_EVENTS_SIMULATED_EVENT_LOOP_H_