blob: 8242d6c5b0cff466019fc34793623fd02a31b46d [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;
Brian Silvermane1fe2512022-08-14 23:18:50 -070030class SimulatedFactoryExitHandle;
Austin Schuh898f4972020-01-11 17:21:25 -080031namespace message_bridge {
32class SimulatedMessageBridge;
33}
Austin Schuhac0771c2020-01-07 18:36:30 -080034
35// There are 2 concepts needed to support multi-node simulations.
36// 1) The node. This is implemented with NodeEventLoopFactory.
37// 2) The "robot" which runs multiple nodes. This is implemented with
38// SimulatedEventLoopFactory.
39//
40// To make things easier, SimulatedEventLoopFactory takes an optional Node
41// argument if you want to make event loops without interacting with the
42// NodeEventLoopFactory object.
43//
44// The basic flow goes something like as follows:
45//
46// SimulatedEventLoopFactory factory(config);
47// const Node *pi1 = configuration::GetNode(factory.configuration(), "pi1");
48// std::unique_ptr<EventLoop> event_loop = factory.MakeEventLoop("ping", pi1);
49//
50// Or
51//
52// SimulatedEventLoopFactory factory(config);
53// const Node *pi1 = configuration::GetNode(factory.configuration(), "pi1");
54// NodeEventLoopFactory *pi1_factory = factory.GetNodeEventLoopFactory(pi1);
55// std::unique_ptr<EventLoop> event_loop = pi1_factory.MakeEventLoop("ping");
56//
57// The distributed_clock is used to be the base time. NodeEventLoopFactory has
58// all the information needed to adjust both the realtime and monotonic clocks
59// relative to the distributed_clock.
Alex Perrycb7da4b2019-08-28 19:35:56 -070060class SimulatedEventLoopFactory {
61 public:
62 // Constructs a SimulatedEventLoopFactory with the provided configuration.
63 // This configuration must remain in scope for the lifetime of the factory and
64 // all sub-objects.
65 SimulatedEventLoopFactory(const Configuration *configuration);
66 ~SimulatedEventLoopFactory();
67
Austin Schuh58646e22021-08-23 23:51:46 -070068 SimulatedEventLoopFactory(const SimulatedEventLoopFactory &) = delete;
69 SimulatedEventLoopFactory &operator=(const SimulatedEventLoopFactory &) =
70 delete;
71 SimulatedEventLoopFactory(SimulatedEventLoopFactory &&) = delete;
72 SimulatedEventLoopFactory &operator=(SimulatedEventLoopFactory &&) = delete;
73
Austin Schuhac0771c2020-01-07 18:36:30 -080074 // Creates an event loop. If running in a multi-node environment, node needs
75 // to point to the node to create this event loop on.
76 ::std::unique_ptr<EventLoop> MakeEventLoop(std::string_view name,
77 const Node *node = nullptr);
78
79 // Returns the NodeEventLoopFactory for the provided node. The returned
80 // NodeEventLoopFactory is owned by the SimulatedEventLoopFactory and has a
81 // lifetime identical to the factory.
82 NodeEventLoopFactory *GetNodeEventLoopFactory(const Node *node);
Austin Schuh057d29f2021-08-21 23:05:15 -070083 NodeEventLoopFactory *GetNodeEventLoopFactory(std::string_view node);
Alex Perrycb7da4b2019-08-28 19:35:56 -070084
Austin Schuh87dd3832021-01-01 23:07:31 -080085 // Sets the time converter for all nodes.
86 void SetTimeConverter(TimeConverter *time_converter);
87
Austin Schuh58646e22021-08-23 23:51:46 -070088 // Starts executing the event loops unconditionally until Exit is called or
89 // all the nodes have shut down.
Alex Perrycb7da4b2019-08-28 19:35:56 -070090 void Run();
91 // Executes the event loops for a duration.
Austin Schuhac0771c2020-01-07 18:36:30 -080092 void RunFor(distributed_clock::duration duration);
Alex Perrycb7da4b2019-08-28 19:35:56 -070093
94 // Stops executing all event loops. Meant to be called from within an event
95 // loop handler.
Austin Schuh8fb315a2020-11-19 22:33:58 -080096 void Exit();
Alex Perrycb7da4b2019-08-28 19:35:56 -070097
Brian Silvermane1fe2512022-08-14 23:18:50 -070098 std::unique_ptr<ExitHandle> MakeExitHandle();
99
Austin Schuhac0771c2020-01-07 18:36:30 -0800100 const std::vector<const Node *> &nodes() const { return nodes_; }
101
102 // Sets the simulated send delay for all messages sent within a single node.
Austin Schuh7d87b672019-12-01 20:23:49 -0800103 void set_send_delay(std::chrono::nanoseconds send_delay);
Austin Schuhac0771c2020-01-07 18:36:30 -0800104 std::chrono::nanoseconds send_delay() const { return send_delay_; }
105
106 // Sets the simulated network delay for messages forwarded between nodes.
Brian Silvermana7c62052020-04-28 16:52:27 -0700107 void set_network_delay(std::chrono::nanoseconds network_delay) {
108 network_delay_ = network_delay;
109 }
Austin Schuhac0771c2020-01-07 18:36:30 -0800110 std::chrono::nanoseconds network_delay() const { return network_delay_; }
111
112 // Returns the clock used to synchronize the nodes.
113 distributed_clock::time_point distributed_now() const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800114 return scheduler_scheduler_.distributed_now();
Austin Schuhac0771c2020-01-07 18:36:30 -0800115 }
116
117 // Returns the configuration used for everything.
118 const Configuration *configuration() const { return configuration_; }
119
Austin Schuh6f3babe2020-01-26 20:34:50 -0800120 // Disables forwarding for this channel. This should be used very rarely only
121 // for things like the logger.
122 void DisableForwarding(const Channel *channel);
123
Austin Schuh4c3b9702020-08-30 11:34:55 -0700124 // Disables the messages sent by the simulated message gateway.
125 void DisableStatistics();
James Kuszmaul94ca5132022-07-19 09:11:08 -0700126 // Disables statistics sent by the simulated message gateway, and prevents
127 // EnableStatistcs from ever being called again (used by LogReader).
128 void PermanentlyDisableStatistics();
Austin Schuh48205e62021-11-12 14:13:18 -0800129 // Enables the messages sent by the simulated message gateway.
130 void EnableStatistics();
Austin Schuh4c3b9702020-08-30 11:34:55 -0700131
Austin Schuh2928ebe2021-02-07 22:10:27 -0800132 // Calls SkipTimingReport() on all EventLoops used as part of the
133 // infrastructure. This may improve the performance of long-simulated-duration
134 // tests.
135 void SkipTimingReport();
136
Austin Schuhe33c08d2022-02-03 18:15:21 -0800137 // Re-enables application creation for the duration of fn. This is mostly to
138 // allow use cases like log reading to create applications after the node
139 // starts up without stopping execution.
140 void AllowApplicationCreationDuring(std::function<void()> fn);
141
James Kuszmaulb67409b2022-06-20 16:25:03 -0700142 // Sets the realtime replay rate. A value of 1.0 will cause the scheduler to
143 // try to play events in realtime. 0.5 will run at half speed. Use infinity
144 // (the default) to run as fast as possible. This can be changed during
145 // run-time.
146 void SetRealtimeReplayRate(double replay_rate);
147
148 // Access to the internal scheduler's epoll object for realtime replay.
149 internal::EPoll *scheduler_epoll() { return scheduler_scheduler_.epoll(); }
150
Austin Schuhac0771c2020-01-07 18:36:30 -0800151 private:
Austin Schuhc0b0f722020-12-12 18:36:06 -0800152 friend class NodeEventLoopFactory;
Brian Silvermane1fe2512022-08-14 23:18:50 -0700153 friend class SimulatedFactoryExitHandle;
Austin Schuhc0b0f722020-12-12 18:36:06 -0800154
Austin Schuhac0771c2020-01-07 18:36:30 -0800155 const Configuration *const configuration_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800156 EventSchedulerScheduler scheduler_scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800157
158 std::chrono::nanoseconds send_delay_ = std::chrono::microseconds(50);
159 std::chrono::nanoseconds network_delay_ = std::chrono::microseconds(100);
160
Austin Schuh58646e22021-08-23 23:51:46 -0700161 std::unique_ptr<message_bridge::SimulatedMessageBridge> bridge_;
162
Austin Schuhac0771c2020-01-07 18:36:30 -0800163 std::vector<std::unique_ptr<NodeEventLoopFactory>> node_factories_;
164
165 std::vector<const Node *> nodes_;
Brian Silvermane1fe2512022-08-14 23:18:50 -0700166
167 int exit_handle_count_ = 0;
Austin Schuhac0771c2020-01-07 18:36:30 -0800168};
169
170// This class holds all the state required to be a single node.
171class NodeEventLoopFactory {
172 public:
Austin Schuh057d29f2021-08-21 23:05:15 -0700173 ~NodeEventLoopFactory();
174
James Kuszmaul890c2492022-04-06 14:59:31 -0700175 // Whether a given event loop should have its senders checked for messages
176 // being sent too fast. Should only be used by the LogReader or other highly
177 // specialized applications that need to be able to bypass normal behaviors.
178 enum class CheckSentTooFast { kNo, kYes };
179 // Whether the created EventLoop should be the only one allowed to send on all
180 // of its channels. Mostly useful for the LogReader, to allow us to confirm
181 // whether the LogReader is conflicting with the output of any applications
182 // being run in replay.
183 enum class ExclusiveSenders { kNo, kYes };
184 struct EventLoopOptions {
185 CheckSentTooFast check_sent_too_fast;
186 ExclusiveSenders exclusive_senders;
James Kuszmaul94ca5132022-07-19 09:11:08 -0700187 // per_channel_exclusivity is used to list any exceptions to the overall
188 // exclusive_senders policy for this event loop.
189 std::vector<std::pair<const aos::Channel *, ExclusiveSenders>>
190 per_channel_exclusivity;
James Kuszmaul890c2492022-04-06 14:59:31 -0700191 };
192
193 // Takes the name for the event loop and a struct of options for selecting
194 // what checks to run for the event loop in question.
195 std::unique_ptr<EventLoop> MakeEventLoop(
196 std::string_view name,
James Kuszmaul94ca5132022-07-19 09:11:08 -0700197 EventLoopOptions options = EventLoopOptions{
198 CheckSentTooFast::kYes, ExclusiveSenders::kNo, {}});
Austin Schuh7d87b672019-12-01 20:23:49 -0800199
Austin Schuh217a9782019-12-21 23:02:50 -0800200 // Returns the node that this factory is running as, or nullptr if this is a
201 // single node setup.
202 const Node *node() const { return node_; }
203
Austin Schuh92547522019-12-28 14:33:43 -0800204 // Sets realtime clock to realtime_now for a given monotonic clock.
205 void SetRealtimeOffset(monotonic_clock::time_point monotonic_now,
206 realtime_clock::time_point realtime_now) {
Austin Schuhac0771c2020-01-07 18:36:30 -0800207 realtime_offset_ =
208 realtime_now.time_since_epoch() - monotonic_now.time_since_epoch();
Austin Schuh92547522019-12-28 14:33:43 -0800209 }
210
Austin Schuhac0771c2020-01-07 18:36:30 -0800211 // Returns the current time on both clocks.
212 inline monotonic_clock::time_point monotonic_now() const;
213 inline realtime_clock::time_point realtime_now() const;
Austin Schuh58646e22021-08-23 23:51:46 -0700214 inline distributed_clock::time_point distributed_now() const;
Austin Schuh39788ff2019-12-01 18:22:57 -0800215
Austin Schuhfaec5e12020-11-05 17:39:55 -0800216 const Configuration *configuration() const {
217 return factory_->configuration();
218 }
219
Austin Schuh58646e22021-08-23 23:51:46 -0700220 // Starts the node up by calling the OnStartup handlers. These get called
221 // every time a node is started.
222
James Kuszmaul82c3b512023-07-08 20:25:41 -0700223 // Called when a node has started. This will most commonly be at the monotonic
224 // clock epoch. In log replay, this will occur prior to any messages
225 // (including "fetched" messages) being replayed for that node.
226 // Called on every boot.
Austin Schuh58646e22021-08-23 23:51:46 -0700227 void OnStartup(std::function<void()> &&fn);
228
229 // Called when a node shuts down. These get called every time a node is shut
230 // down. All applications are destroyed right after the last OnShutdown
231 // callback is called.
232 void OnShutdown(std::function<void()> &&fn);
233
234 // Starts an application if the configuration says it should be started on
235 // this node. name is the name of the application. args are the constructor
236 // args for the Main class. Returns a pointer to the class that was started
237 // if it was started, or nullptr.
238 template <class Main, class... Args>
James Kuszmaul80d6c422023-01-06 14:16:04 -0800239 Main *MaybeStart(std::string_view name, Args &&... args);
Austin Schuh58646e22021-08-23 23:51:46 -0700240
241 // Starts an application regardless of if the config says to or not. name is
242 // the name of the application, and args are the constructor args for the
243 // application. Returns a pointer to the class that was started.
244 template <class Main, class... Args>
James Kuszmaul80d6c422023-01-06 14:16:04 -0800245 Main *AlwaysStart(std::string_view name, Args &&... args);
Austin Schuh58646e22021-08-23 23:51:46 -0700246
Austin Schuh898f4972020-01-11 17:21:25 -0800247 // Returns the simulated network delay for messages forwarded between nodes.
248 std::chrono::nanoseconds network_delay() const {
249 return factory_->network_delay();
250 }
251 // Returns the simulated send delay for all messages sent within a single
252 // node.
253 std::chrono::nanoseconds send_delay() const { return factory_->send_delay(); }
254
Austin Schuh58646e22021-08-23 23:51:46 -0700255 size_t boot_count() const { return scheduler_.boot_count(); }
256
James Kuszmaul80d6c422023-01-06 14:16:04 -0800257 bool is_running() const { return scheduler_.is_running(); }
258
Austin Schuh8bd96322020-02-13 21:18:22 -0800259 // TODO(austin): Private for the following?
260
Austin Schuhac0771c2020-01-07 18:36:30 -0800261 // Converts a time to the distributed clock for scheduling and cross-node time
262 // measurement.
Austin Schuh87dd3832021-01-01 23:07:31 -0800263 // Note: converting time too far in the future can cause problems when
264 // replaying logs. Only convert times in the present or near past.
Austin Schuhac0771c2020-01-07 18:36:30 -0800265 inline distributed_clock::time_point ToDistributedClock(
266 monotonic_clock::time_point time) const;
Austin Schuh58646e22021-08-23 23:51:46 -0700267 inline logger::BootTimestamp FromDistributedClock(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700268 distributed_clock::time_point time) const;
Austin Schuhac0771c2020-01-07 18:36:30 -0800269
Austin Schuh87dd3832021-01-01 23:07:31 -0800270 // Sets the class used to convert time. This pointer must out-live the
271 // SimulatedEventLoopFactory.
272 void SetTimeConverter(TimeConverter *time_converter) {
273 scheduler_.SetTimeConverter(
274 configuration::GetNodeIndex(factory_->configuration(), node_),
275 time_converter);
Austin Schuhcde938c2020-02-02 17:30:07 -0800276 }
277
Austin Schuh20ac95d2020-12-05 17:24:19 -0800278 // Returns the boot UUID for this node.
Austin Schuh58646e22021-08-23 23:51:46 -0700279 const UUID &boot_uuid() {
280 if (boot_uuid_ == UUID::Zero()) {
281 boot_uuid_ = scheduler_.boot_uuid();
282 }
283 return boot_uuid_;
284 }
Austin Schuh20ac95d2020-12-05 17:24:19 -0800285
Austin Schuhc0b0f722020-12-12 18:36:06 -0800286 // Stops forwarding messages to the other node, and reports disconnected in
287 // the ServerStatistics message for this node, and the ClientStatistics for
288 // the other node.
289 void Disconnect(const Node *other);
290 // Resumes forwarding messages.
291 void Connect(const Node *other);
292
Austin Schuh48205e62021-11-12 14:13:18 -0800293 // Disables the messages sent by the simulated message gateway.
294 void DisableStatistics();
295 // Enables the messages sent by the simulated message gateway.
296 void EnableStatistics();
297
Austin Schuhac0771c2020-01-07 18:36:30 -0800298 private:
299 friend class SimulatedEventLoopFactory;
Austin Schuh057d29f2021-08-21 23:05:15 -0700300 NodeEventLoopFactory(EventSchedulerScheduler *scheduler_scheduler,
301 SimulatedEventLoopFactory *factory, const Node *node);
Austin Schuhac0771c2020-01-07 18:36:30 -0800302
Austin Schuh48205e62021-11-12 14:13:18 -0800303 // Skips timing reports on all event loops on this node.
304 void SkipTimingReport();
305
Austin Schuh58646e22021-08-23 23:51:46 -0700306 // Helpers to restart.
307 void ScheduleStartup();
308 void Startup();
309 void Shutdown();
310
Austin Schuh8bd96322020-02-13 21:18:22 -0800311 EventScheduler scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800312 SimulatedEventLoopFactory *const factory_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800313
Austin Schuh58646e22021-08-23 23:51:46 -0700314 UUID boot_uuid_ = UUID::Zero();
Austin Schuh20ac95d2020-12-05 17:24:19 -0800315
Austin Schuh217a9782019-12-21 23:02:50 -0800316 const Node *const node_;
317
Austin Schuh48205e62021-11-12 14:13:18 -0800318 bool skip_timing_report_ = false;
319
Austin Schuh057d29f2021-08-21 23:05:15 -0700320 std::vector<SimulatedEventLoop *> event_loops_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800321
Austin Schuhac0771c2020-01-07 18:36:30 -0800322 std::chrono::nanoseconds realtime_offset_ = std::chrono::seconds(0);
323
324 // Map from name, type to queue.
325 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> channels_;
326
327 // pid so we get unique timing reports.
Austin Schuh39788ff2019-12-01 18:22:57 -0800328 pid_t tid_ = 0;
Austin Schuh58646e22021-08-23 23:51:46 -0700329
330 // True if we are started.
331 bool started_ = false;
332
333 std::vector<std::function<void()>> pending_on_startup_;
334 std::vector<std::function<void()>> on_startup_;
335 std::vector<std::function<void()>> on_shutdown_;
336
337 // Base class for an application to start. This shouldn't be used directly.
338 struct Application {
339 Application(NodeEventLoopFactory *node_factory, std::string_view name)
340 : event_loop(node_factory->MakeEventLoop(name)) {}
341 virtual ~Application() {}
342
343 std::unique_ptr<EventLoop> event_loop;
344 };
345
346 // Subclass to do type erasure for the base class. Holds an instance of a
347 // specific class. Use SimulationStarter instead.
348 template <typename Main>
349 struct TypedApplication : public Application {
350 // Constructs an Application by delegating the arguments used to construct
351 // the event loop to Application and the rest of the args to the actual
352 // application.
353 template <class... Args>
354 TypedApplication(NodeEventLoopFactory *node_factory, std::string_view name,
James Kuszmaul80d6c422023-01-06 14:16:04 -0800355 Args &&... args)
Austin Schuh58646e22021-08-23 23:51:46 -0700356 : Application(node_factory, name),
357 main(event_loop.get(), std::forward<Args>(args)...) {
358 VLOG(1) << node_factory->scheduler_.distributed_now() << " "
359 << (node_factory->node() == nullptr
360 ? ""
361 : node_factory->node()->name()->str() + " ")
362 << node_factory->monotonic_now() << " Starting Application \""
363 << name << "\"";
364 }
365 ~TypedApplication() override {}
366
367 Main main;
368 };
369
370 std::vector<std::unique_ptr<Application>> applications_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700371};
372
Austin Schuh58646e22021-08-23 23:51:46 -0700373template <class Main, class... Args>
James Kuszmaul80d6c422023-01-06 14:16:04 -0800374Main *NodeEventLoopFactory::MaybeStart(std::string_view name, Args &&... args) {
Austin Schuh58646e22021-08-23 23:51:46 -0700375 const aos::Application *application =
376 configuration::GetApplication(configuration(), node(), name);
377
378 if (application != nullptr) {
379 return AlwaysStart<Main>(name, std::forward<Args>(args)...);
380 }
381 return nullptr;
382}
383
384template <class Main, class... Args>
James Kuszmaul80d6c422023-01-06 14:16:04 -0800385Main *NodeEventLoopFactory::AlwaysStart(std::string_view name,
386 Args &&... args) {
Austin Schuh58646e22021-08-23 23:51:46 -0700387 std::unique_ptr<TypedApplication<Main>> app =
388 std::make_unique<TypedApplication<Main>>(this, name,
389 std::forward<Args>(args)...);
390 Main *main_ptr = &app->main;
391 applications_.emplace_back(std::move(app));
392 return main_ptr;
393}
394
Austin Schuhac0771c2020-01-07 18:36:30 -0800395inline monotonic_clock::time_point NodeEventLoopFactory::monotonic_now() const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800396 // TODO(austin): Confirm that time never goes backwards?
Austin Schuhbe69cf32020-08-27 11:38:33 -0700397 return scheduler_.monotonic_now();
Austin Schuhac0771c2020-01-07 18:36:30 -0800398}
399
400inline realtime_clock::time_point NodeEventLoopFactory::realtime_now() const {
401 return realtime_clock::time_point(monotonic_now().time_since_epoch() +
402 realtime_offset_);
403}
404
Austin Schuh58646e22021-08-23 23:51:46 -0700405inline distributed_clock::time_point NodeEventLoopFactory::distributed_now()
406 const {
407 return scheduler_.distributed_now();
408}
409
410inline logger::BootTimestamp NodeEventLoopFactory::FromDistributedClock(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700411 distributed_clock::time_point time) const {
412 return scheduler_.FromDistributedClock(time);
413}
414
Austin Schuhac0771c2020-01-07 18:36:30 -0800415inline distributed_clock::time_point NodeEventLoopFactory::ToDistributedClock(
416 monotonic_clock::time_point time) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800417 return scheduler_.ToDistributedClock(time);
Austin Schuhac0771c2020-01-07 18:36:30 -0800418}
419
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420} // namespace aos
421
422#endif // AOS_EVENTS_SIMULATED_EVENT_LOOP_H_