blob: 95210c0fb86648ef2b80ce16452b1ba5f1986278 [file] [log] [blame]
Philipp Schrader790cb542023-07-05 21:06:52 -07001#include "aos/starter/starterd_lib.h"
Tyler Chatowa79419d2020-08-12 20:12:11 -07002
Tyler Chatowa79419d2020-08-12 20:12:11 -07003#include <algorithm>
4#include <utility>
5
James Kuszmaul293b2172021-11-10 16:20:48 -08006#include "absl/strings/str_format.h"
Tyler Chatowa79419d2020-08-12 20:12:11 -07007#include "glog/logging.h"
8#include "glog/stl_logging.h"
9
Philipp Schrader790cb542023-07-05 21:06:52 -070010#include "aos/json_to_flatbuffer.h"
11
Austin Schuh4d275fc2022-09-16 15:42:45 -070012// FLAGS_shm_base is defined elsewhere, declare it here so it can be used
13// to override the shared memory folder for unit testing.
14DECLARE_string(shm_base);
15// FLAGS_permissions is defined elsewhere, declare it here so it can be used
16// to set the file permissions on the shared memory block.
17DECLARE_uint32(permissions);
18
Austin Schuh816a1162023-05-31 16:29:47 -070019DEFINE_uint32(queue_initialization_threads, 0,
20 "Number of threads to spin up to initialize the queue. 0 means "
21 "use the main thread.");
22
Stephan Pleinesf63bde82024-01-13 15:59:33 -080023namespace aos::starter {
Tyler Chatowa79419d2020-08-12 20:12:11 -070024
James Kuszmaul293b2172021-11-10 16:20:48 -080025const aos::Channel *StatusChannelForNode(const aos::Configuration *config,
26 const aos::Node *node) {
27 return configuration::GetChannel<Status>(config, "/aos", "", node);
28}
29const aos::Channel *StarterRpcChannelForNode(const aos::Configuration *config,
30 const aos::Node *node) {
31 return configuration::GetChannel<StarterRpc>(config, "/aos", "", node);
32}
33
Tyler Chatowa79419d2020-08-12 20:12:11 -070034Starter::Starter(const aos::Configuration *event_loop_config)
35 : config_msg_(event_loop_config),
36 event_loop_(event_loop_config),
37 status_sender_(event_loop_.MakeSender<aos::starter::Status>("/aos")),
James Kuszmaul2c10e052023-08-09 10:22:36 -070038 status_timer_(event_loop_.AddPhasedLoop(
39 [this](int elapsed_cycles) {
40 ServiceTimingReportFetcher(elapsed_cycles);
41 SendStatus();
42 status_count_ = 0;
43 },
44 std::chrono::milliseconds(1000))),
Austin Schuh59398d32023-05-03 08:10:55 -070045 cleanup_timer_(event_loop_.AddTimer([this] {
46 event_loop_.Exit();
47 LOG(INFO) << "Starter event loop exit finished.";
48 })),
Austin Schuhfc304942021-10-16 14:20:05 -070049 max_status_count_(
50 event_loop_.GetChannel<aos::starter::Status>("/aos")->frequency() -
51 1),
James Kuszmaul8544c492023-07-31 15:00:38 -070052 timing_report_fetcher_(
53 event_loop_.MakeFetcher<aos::timing::Report>("/aos")),
Austin Schuh4d275fc2022-09-16 15:42:45 -070054 shm_base_(FLAGS_shm_base),
Tyler Chatowa79419d2020-08-12 20:12:11 -070055 listener_(&event_loop_,
James Kuszmaul6295a642022-03-22 15:23:59 -070056 [this](signalfd_siginfo signal) { OnSignal(signal); }),
57 top_(&event_loop_) {
Tyler Chatowa79419d2020-08-12 20:12:11 -070058 event_loop_.SkipAosLog();
59
James Kuszmaul293b2172021-11-10 16:20:48 -080060 if (!aos::configuration::MultiNode(config_msg_)) {
61 event_loop_.MakeWatcher(
62 "/aos",
63 [this](const aos::starter::StarterRpc &cmd) { HandleStarterRpc(cmd); });
64 } else {
65 for (const aos::Node *node : aos::configuration::GetNodes(config_msg_)) {
66 const Channel *channel = StarterRpcChannelForNode(config_msg_, node);
67 CHECK(channel != nullptr) << ": Failed to find channel /aos for "
68 << StarterRpc::GetFullyQualifiedName() << " on "
69 << node->name()->string_view();
70 if (!aos::configuration::ChannelIsReadableOnNode(channel,
71 event_loop_.node())) {
72 LOG(INFO) << "StarterRpc channel "
73 << aos::configuration::StrippedChannelToString(channel)
74 << " is not readable on "
75 << event_loop_.node()->name()->string_view();
76 } else {
77 event_loop_.MakeWatcher(channel->name()->string_view(),
78 [this](const aos::starter::StarterRpc &cmd) {
79 HandleStarterRpc(cmd);
80 });
81 }
Tyler Chatowa79419d2020-08-12 20:12:11 -070082 }
James Kuszmaul293b2172021-11-10 16:20:48 -080083 }
Tyler Chatowa79419d2020-08-12 20:12:11 -070084
Austin Schuh4d275fc2022-09-16 15:42:45 -070085 // Catalogue all the applications for this node, so we can keep an eye on
86 // them.
Tyler Chatowa79419d2020-08-12 20:12:11 -070087 if (config_msg_->has_applications()) {
88 const flatbuffers::Vector<flatbuffers::Offset<aos::Application>>
89 *applications = config_msg_->applications();
Ravago Jones7e2dd322020-11-21 15:58:58 -080090
91 if (aos::configuration::MultiNode(config_msg_)) {
92 std::string_view current_node = event_loop_.node()->name()->string_view();
93 for (const aos::Application *application : *applications) {
Austin Schuh228609b2023-03-21 15:43:11 -070094 CHECK(application->has_nodes())
95 << ": Missing nodes on " << aos::FlatbufferToJson(application);
Ravago Jones7e2dd322020-11-21 15:58:58 -080096 for (const flatbuffers::String *node : *application->nodes()) {
97 if (node->string_view() == current_node) {
98 AddApplication(application);
99 break;
100 }
101 }
102 }
103 } else {
104 for (const aos::Application *application : *applications) {
105 AddApplication(application);
106 }
Tyler Chatowa79419d2020-08-12 20:12:11 -0700107 }
108 }
Austin Schuh4d275fc2022-09-16 15:42:45 -0700109
110 // Catalogue all the intranode channels for this node, and create
111 // MemoryMappedQueues for each one to allocate the shared memory before
112 // spawning any shasta process.
113 if (config_msg_->has_channels()) {
Austin Schuh816a1162023-05-31 16:29:47 -0700114 LOG(INFO) << "Starting to initialize shared memory.";
Austin Schuh4d275fc2022-09-16 15:42:45 -0700115 const aos::Node *this_node = event_loop_.node();
Austin Schuh816a1162023-05-31 16:29:47 -0700116 std::vector<const aos::Channel *> channels_to_construct;
Austin Schuh4d275fc2022-09-16 15:42:45 -0700117 for (const aos::Channel *channel : *config_msg_->channels()) {
118 if (aos::configuration::ChannelIsReadableOnNode(channel, this_node)) {
Austin Schuh816a1162023-05-31 16:29:47 -0700119 if (FLAGS_queue_initialization_threads == 0) {
120 AddChannel(channel);
121 } else {
122 channels_to_construct.push_back(channel);
123 }
Austin Schuh4d275fc2022-09-16 15:42:45 -0700124 }
125 }
Austin Schuh816a1162023-05-31 16:29:47 -0700126
127 if (FLAGS_queue_initialization_threads != 0) {
128 std::mutex pool_mutex;
129 std::vector<std::thread> threads;
130 threads.reserve(FLAGS_queue_initialization_threads);
131 for (size_t i = 0; i < FLAGS_queue_initialization_threads; ++i) {
132 threads.emplace_back([this, &pool_mutex, &channels_to_construct]() {
133 while (true) {
134 const aos::Channel *channel;
135 {
136 std::unique_lock<std::mutex> locker(pool_mutex);
137 if (channels_to_construct.empty()) {
138 return;
139 }
140 channel = channels_to_construct.back();
141 channels_to_construct.pop_back();
142 }
143 AddChannel(channel);
144 }
145 });
146 }
147 for (size_t i = 0; i < FLAGS_queue_initialization_threads; ++i) {
148 threads[i].join();
149 }
150 }
151 LOG(INFO) << "Starting applications.";
Austin Schuh4d275fc2022-09-16 15:42:45 -0700152 }
Tyler Chatowa79419d2020-08-12 20:12:11 -0700153}
154
James Kuszmaul293b2172021-11-10 16:20:48 -0800155void Starter::HandleStarterRpc(const StarterRpc &command) {
156 if (!command.has_command() || !command.has_name() || exiting_) {
157 return;
158 }
159
160 LOG(INFO) << "Received " << aos::FlatbufferToJson(&command);
161
162 if (command.has_nodes()) {
163 CHECK(aos::configuration::MultiNode(config_msg_));
164 bool relevant_to_this_node = false;
165 for (const flatbuffers::String *node : *command.nodes()) {
166 if (node->string_view() == event_loop_.node()->name()->string_view()) {
167 relevant_to_this_node = true;
168 }
169 }
170 if (!relevant_to_this_node) {
171 return;
172 }
173 }
174 // If not populated, restart regardless of node.
175
176 auto search = applications_.find(command.name()->str());
177 if (search != applications_.end()) {
178 // If an applicatione exists by the given name, dispatch the command
179 search->second.HandleCommand(command.command());
180 }
181}
182
James Kuszmaul6295a642022-03-22 15:23:59 -0700183void Starter::HandleStateChange() {
184 std::set<pid_t> all_pids;
185 for (const auto &pair : applications_) {
186 if (pair.second.get_pid() > 0 &&
187 pair.second.status() != aos::starter::State::STOPPED) {
188 all_pids.insert(pair.second.get_pid());
189 }
190 }
191 top_.set_track_pids(all_pids);
192
Austin Schuhfc304942021-10-16 14:20:05 -0700193 if (status_count_ < max_status_count_) {
194 SendStatus();
195 ++status_count_;
196 } else {
197 VLOG(1) << "That's enough " << status_count_ << " " << max_status_count_;
198 }
199}
200
Tyler Chatowa79419d2020-08-12 20:12:11 -0700201void Starter::Cleanup() {
202 if (exiting_) {
203 return;
204 }
205 exiting_ = true;
206 for (auto &application : applications_) {
207 application.second.Terminate();
208 }
Philipp Schradera6712522023-07-05 20:25:11 -0700209 cleanup_timer_->Schedule(event_loop_.monotonic_now() +
210 std::chrono::milliseconds(1500));
Tyler Chatowa79419d2020-08-12 20:12:11 -0700211}
212
213void Starter::OnSignal(signalfd_siginfo info) {
Tyler Chatowa79419d2020-08-12 20:12:11 -0700214 if (info.ssi_signo == SIGCHLD) {
215 // SIGCHLD messages can be collapsed if multiple are received, so all
216 // applications must check their status.
217 for (auto iter = applications_.begin(); iter != applications_.end();) {
218 if (iter->second.MaybeHandleSignal()) {
219 iter = applications_.erase(iter);
220 } else {
221 ++iter;
222 }
223 }
224
225 if (exiting_ && applications_.empty()) {
226 event_loop_.Exit();
227 }
Austin Schuh3204b332021-10-16 14:20:10 -0700228 } else {
229 LOG(INFO) << "Received signal '" << strsignal(info.ssi_signo) << "'";
230
231 if (std::find(kStarterDeath.begin(), kStarterDeath.end(), info.ssi_signo) !=
232 kStarterDeath.end()) {
233 LOG(WARNING) << "Starter shutting down";
234 Cleanup();
235 }
Tyler Chatowa79419d2020-08-12 20:12:11 -0700236 }
237}
238
239Application *Starter::AddApplication(const aos::Application *application) {
James Kuszmaul6295a642022-03-22 15:23:59 -0700240 auto [iter, success] = applications_.try_emplace(
241 application->name()->str(), application, &event_loop_,
242 [this]() { HandleStateChange(); });
Tyler Chatowa79419d2020-08-12 20:12:11 -0700243 if (success) {
James Kuszmauld42edb42022-01-07 18:00:16 -0800244 // We should be catching and handling SIGCHLD correctly in the starter, so
245 // don't leave in the crutch for polling for the child process status (this
246 // is less about efficiency, and more about making sure bit rot doesn't
247 // result in the signal handling breaking).
248 iter->second.DisableChildDeathPolling();
Tyler Chatowa79419d2020-08-12 20:12:11 -0700249 return &(iter->second);
250 }
251 return nullptr;
252}
253
254void Starter::Run() {
Tyler Chatow03fdb2a2020-12-26 18:39:36 -0800255#ifdef AOS_ARCHITECTURE_arm_frc
256 PCHECK(setuid(0) == 0) << "Failed to change user to root";
257#endif
258
Tyler Chatowa79419d2020-08-12 20:12:11 -0700259 for (auto &application : applications_) {
Austin Schuh5f79a5a2021-10-12 17:46:50 -0700260 if (application.second.autostart()) {
261 application.second.Start();
262 }
Tyler Chatowa79419d2020-08-12 20:12:11 -0700263 }
264
265 event_loop_.Run();
266}
267
James Kuszmaul2c10e052023-08-09 10:22:36 -0700268void Starter::ServiceTimingReportFetcher(int elapsed_cycles) {
269 // If there is any chance that it has been longer than one cycle since we last
270 // serviced the fetcher, call Fetch(). This reduces the chances that the
271 // fetcher falls behind when the system is under heavy load. Dropping a few
272 // timing report messages when the system is under stress is fine.
273 if (timing_report_fetcher_.get() == nullptr || elapsed_cycles > 1) {
274 timing_report_fetcher_.Fetch();
275 }
James Kuszmaul8544c492023-07-31 15:00:38 -0700276 while (timing_report_fetcher_.FetchNext()) {
277 for (auto &application : applications_) {
278 application.second.ObserveTimingReport(
279 timing_report_fetcher_.context().monotonic_event_time,
280 timing_report_fetcher_.get());
281 }
282 }
283}
284
Tyler Chatowa79419d2020-08-12 20:12:11 -0700285void Starter::SendStatus() {
286 aos::Sender<aos::starter::Status>::Builder builder =
287 status_sender_.MakeBuilder();
288
289 std::vector<flatbuffers::Offset<aos::starter::ApplicationStatus>> statuses;
290
291 for (auto &application : applications_) {
James Kuszmaul6295a642022-03-22 15:23:59 -0700292 statuses.push_back(application.second.PopulateStatus(builder.fbb(), &top_));
Tyler Chatowa79419d2020-08-12 20:12:11 -0700293 }
294
295 auto statuses_fbs = builder.fbb()->CreateVector(statuses);
296
297 aos::starter::Status::Builder status_builder(*builder.fbb());
298 status_builder.add_statuses(statuses_fbs);
milind1f1dca32021-07-03 13:50:07 -0700299 builder.CheckOk(builder.Send(status_builder.Finish()));
Tyler Chatowa79419d2020-08-12 20:12:11 -0700300}
301
Austin Schuh4d275fc2022-09-16 15:42:45 -0700302void Starter::AddChannel(const aos::Channel *channel) {
303 CHECK_NOTNULL(channel);
Austin Schuh816a1162023-05-31 16:29:47 -0700304 std::unique_ptr<aos::ipc_lib::MemoryMappedQueue> queue =
305 std::make_unique<aos::ipc_lib::MemoryMappedQueue>(
306 shm_base_, FLAGS_permissions, event_loop_.configuration(), channel);
307
308 {
309 std::unique_lock<std::mutex> locker(queue_mutex_);
310 shm_queues_.emplace_back(std::move(queue));
311 }
Austin Schuh4d275fc2022-09-16 15:42:45 -0700312 VLOG(1) << "Created MemoryMappedQueue for "
313 << aos::configuration::StrippedChannelToString(channel) << " under "
314 << shm_base_;
315}
316
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800317} // namespace aos::starter