blob: 38d519d021869a7248ab3522d394d633dcbf98d3 [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.");
Pallavi Madhukaraa17d242023-12-20 13:42:41 -080022DECLARE_bool(enable_ftrace);
Austin Schuh816a1162023-05-31 16:29:47 -070023
Stephan Pleinesf63bde82024-01-13 15:59:33 -080024namespace aos::starter {
Tyler Chatowa79419d2020-08-12 20:12:11 -070025
James Kuszmaul293b2172021-11-10 16:20:48 -080026const aos::Channel *StatusChannelForNode(const aos::Configuration *config,
27 const aos::Node *node) {
28 return configuration::GetChannel<Status>(config, "/aos", "", node);
29}
30const aos::Channel *StarterRpcChannelForNode(const aos::Configuration *config,
31 const aos::Node *node) {
32 return configuration::GetChannel<StarterRpc>(config, "/aos", "", node);
33}
34
Tyler Chatowa79419d2020-08-12 20:12:11 -070035Starter::Starter(const aos::Configuration *event_loop_config)
36 : config_msg_(event_loop_config),
37 event_loop_(event_loop_config),
38 status_sender_(event_loop_.MakeSender<aos::starter::Status>("/aos")),
James Kuszmaul2c10e052023-08-09 10:22:36 -070039 status_timer_(event_loop_.AddPhasedLoop(
40 [this](int elapsed_cycles) {
41 ServiceTimingReportFetcher(elapsed_cycles);
42 SendStatus();
43 status_count_ = 0;
44 },
45 std::chrono::milliseconds(1000))),
Austin Schuh59398d32023-05-03 08:10:55 -070046 cleanup_timer_(event_loop_.AddTimer([this] {
47 event_loop_.Exit();
48 LOG(INFO) << "Starter event loop exit finished.";
49 })),
Austin Schuhfc304942021-10-16 14:20:05 -070050 max_status_count_(
51 event_loop_.GetChannel<aos::starter::Status>("/aos")->frequency() -
52 1),
James Kuszmaul8544c492023-07-31 15:00:38 -070053 timing_report_fetcher_(
54 event_loop_.MakeFetcher<aos::timing::Report>("/aos")),
Austin Schuh4d275fc2022-09-16 15:42:45 -070055 shm_base_(FLAGS_shm_base),
Tyler Chatowa79419d2020-08-12 20:12:11 -070056 listener_(&event_loop_,
James Kuszmaul6295a642022-03-22 15:23:59 -070057 [this](signalfd_siginfo signal) { OnSignal(signal); }),
58 top_(&event_loop_) {
Tyler Chatowa79419d2020-08-12 20:12:11 -070059 event_loop_.SkipAosLog();
60
James Kuszmaul293b2172021-11-10 16:20:48 -080061 if (!aos::configuration::MultiNode(config_msg_)) {
62 event_loop_.MakeWatcher(
63 "/aos",
64 [this](const aos::starter::StarterRpc &cmd) { HandleStarterRpc(cmd); });
65 } else {
66 for (const aos::Node *node : aos::configuration::GetNodes(config_msg_)) {
67 const Channel *channel = StarterRpcChannelForNode(config_msg_, node);
68 CHECK(channel != nullptr) << ": Failed to find channel /aos for "
69 << StarterRpc::GetFullyQualifiedName() << " on "
70 << node->name()->string_view();
71 if (!aos::configuration::ChannelIsReadableOnNode(channel,
72 event_loop_.node())) {
73 LOG(INFO) << "StarterRpc channel "
74 << aos::configuration::StrippedChannelToString(channel)
75 << " is not readable on "
76 << event_loop_.node()->name()->string_view();
77 } else {
78 event_loop_.MakeWatcher(channel->name()->string_view(),
79 [this](const aos::starter::StarterRpc &cmd) {
80 HandleStarterRpc(cmd);
81 });
82 }
Tyler Chatowa79419d2020-08-12 20:12:11 -070083 }
James Kuszmaul293b2172021-11-10 16:20:48 -080084 }
Tyler Chatowa79419d2020-08-12 20:12:11 -070085
Austin Schuh4d275fc2022-09-16 15:42:45 -070086 // Catalogue all the applications for this node, so we can keep an eye on
87 // them.
Tyler Chatowa79419d2020-08-12 20:12:11 -070088 if (config_msg_->has_applications()) {
89 const flatbuffers::Vector<flatbuffers::Offset<aos::Application>>
90 *applications = config_msg_->applications();
Ravago Jones7e2dd322020-11-21 15:58:58 -080091
92 if (aos::configuration::MultiNode(config_msg_)) {
93 std::string_view current_node = event_loop_.node()->name()->string_view();
94 for (const aos::Application *application : *applications) {
Austin Schuh228609b2023-03-21 15:43:11 -070095 CHECK(application->has_nodes())
96 << ": Missing nodes on " << aos::FlatbufferToJson(application);
Ravago Jones7e2dd322020-11-21 15:58:58 -080097 for (const flatbuffers::String *node : *application->nodes()) {
98 if (node->string_view() == current_node) {
99 AddApplication(application);
100 break;
101 }
102 }
103 }
104 } else {
105 for (const aos::Application *application : *applications) {
106 AddApplication(application);
107 }
Tyler Chatowa79419d2020-08-12 20:12:11 -0700108 }
109 }
Austin Schuh4d275fc2022-09-16 15:42:45 -0700110
111 // Catalogue all the intranode channels for this node, and create
112 // MemoryMappedQueues for each one to allocate the shared memory before
113 // spawning any shasta process.
114 if (config_msg_->has_channels()) {
Austin Schuh816a1162023-05-31 16:29:47 -0700115 LOG(INFO) << "Starting to initialize shared memory.";
Austin Schuh4d275fc2022-09-16 15:42:45 -0700116 const aos::Node *this_node = event_loop_.node();
Austin Schuh816a1162023-05-31 16:29:47 -0700117 std::vector<const aos::Channel *> channels_to_construct;
Austin Schuh4d275fc2022-09-16 15:42:45 -0700118 for (const aos::Channel *channel : *config_msg_->channels()) {
119 if (aos::configuration::ChannelIsReadableOnNode(channel, this_node)) {
Austin Schuh816a1162023-05-31 16:29:47 -0700120 if (FLAGS_queue_initialization_threads == 0) {
121 AddChannel(channel);
122 } else {
123 channels_to_construct.push_back(channel);
124 }
Austin Schuh4d275fc2022-09-16 15:42:45 -0700125 }
126 }
Austin Schuh816a1162023-05-31 16:29:47 -0700127
128 if (FLAGS_queue_initialization_threads != 0) {
129 std::mutex pool_mutex;
130 std::vector<std::thread> threads;
131 threads.reserve(FLAGS_queue_initialization_threads);
132 for (size_t i = 0; i < FLAGS_queue_initialization_threads; ++i) {
133 threads.emplace_back([this, &pool_mutex, &channels_to_construct]() {
134 while (true) {
135 const aos::Channel *channel;
136 {
137 std::unique_lock<std::mutex> locker(pool_mutex);
138 if (channels_to_construct.empty()) {
139 return;
140 }
141 channel = channels_to_construct.back();
142 channels_to_construct.pop_back();
143 }
144 AddChannel(channel);
145 }
146 });
147 }
148 for (size_t i = 0; i < FLAGS_queue_initialization_threads; ++i) {
149 threads[i].join();
150 }
151 }
152 LOG(INFO) << "Starting applications.";
Austin Schuh4d275fc2022-09-16 15:42:45 -0700153 }
Tyler Chatowa79419d2020-08-12 20:12:11 -0700154}
155
James Kuszmaul293b2172021-11-10 16:20:48 -0800156void Starter::HandleStarterRpc(const StarterRpc &command) {
157 if (!command.has_command() || !command.has_name() || exiting_) {
158 return;
159 }
160
161 LOG(INFO) << "Received " << aos::FlatbufferToJson(&command);
162
163 if (command.has_nodes()) {
164 CHECK(aos::configuration::MultiNode(config_msg_));
165 bool relevant_to_this_node = false;
166 for (const flatbuffers::String *node : *command.nodes()) {
167 if (node->string_view() == event_loop_.node()->name()->string_view()) {
168 relevant_to_this_node = true;
169 }
170 }
171 if (!relevant_to_this_node) {
172 return;
173 }
174 }
175 // If not populated, restart regardless of node.
176
177 auto search = applications_.find(command.name()->str());
178 if (search != applications_.end()) {
179 // If an applicatione exists by the given name, dispatch the command
180 search->second.HandleCommand(command.command());
181 }
182}
183
James Kuszmaul6295a642022-03-22 15:23:59 -0700184void Starter::HandleStateChange() {
185 std::set<pid_t> all_pids;
186 for (const auto &pair : applications_) {
187 if (pair.second.get_pid() > 0 &&
188 pair.second.status() != aos::starter::State::STOPPED) {
189 all_pids.insert(pair.second.get_pid());
190 }
191 }
192 top_.set_track_pids(all_pids);
193
Austin Schuhfc304942021-10-16 14:20:05 -0700194 if (status_count_ < max_status_count_) {
195 SendStatus();
196 ++status_count_;
197 } else {
198 VLOG(1) << "That's enough " << status_count_ << " " << max_status_count_;
199 }
200}
201
Tyler Chatowa79419d2020-08-12 20:12:11 -0700202void Starter::Cleanup() {
203 if (exiting_) {
204 return;
205 }
206 exiting_ = true;
207 for (auto &application : applications_) {
208 application.second.Terminate();
209 }
Philipp Schradera6712522023-07-05 20:25:11 -0700210 cleanup_timer_->Schedule(event_loop_.monotonic_now() +
211 std::chrono::milliseconds(1500));
Tyler Chatowa79419d2020-08-12 20:12:11 -0700212}
213
214void Starter::OnSignal(signalfd_siginfo info) {
Tyler Chatowa79419d2020-08-12 20:12:11 -0700215 if (info.ssi_signo == SIGCHLD) {
216 // SIGCHLD messages can be collapsed if multiple are received, so all
217 // applications must check their status.
Pallavi Madhukaraa17d242023-12-20 13:42:41 -0800218 if (FLAGS_enable_ftrace) {
219 ftrace_.FormatMessage("SIGCHLD");
220 ftrace_.TurnOffOrDie();
221 }
222
Tyler Chatowa79419d2020-08-12 20:12:11 -0700223 for (auto iter = applications_.begin(); iter != applications_.end();) {
224 if (iter->second.MaybeHandleSignal()) {
225 iter = applications_.erase(iter);
226 } else {
227 ++iter;
228 }
229 }
230
231 if (exiting_ && applications_.empty()) {
232 event_loop_.Exit();
233 }
Austin Schuh3204b332021-10-16 14:20:10 -0700234 } else {
235 LOG(INFO) << "Received signal '" << strsignal(info.ssi_signo) << "'";
236
237 if (std::find(kStarterDeath.begin(), kStarterDeath.end(), info.ssi_signo) !=
238 kStarterDeath.end()) {
239 LOG(WARNING) << "Starter shutting down";
240 Cleanup();
241 }
Tyler Chatowa79419d2020-08-12 20:12:11 -0700242 }
243}
244
245Application *Starter::AddApplication(const aos::Application *application) {
James Kuszmaul6295a642022-03-22 15:23:59 -0700246 auto [iter, success] = applications_.try_emplace(
247 application->name()->str(), application, &event_loop_,
248 [this]() { HandleStateChange(); });
Tyler Chatowa79419d2020-08-12 20:12:11 -0700249 if (success) {
James Kuszmauld42edb42022-01-07 18:00:16 -0800250 // We should be catching and handling SIGCHLD correctly in the starter, so
251 // don't leave in the crutch for polling for the child process status (this
252 // is less about efficiency, and more about making sure bit rot doesn't
253 // result in the signal handling breaking).
254 iter->second.DisableChildDeathPolling();
Tyler Chatowa79419d2020-08-12 20:12:11 -0700255 return &(iter->second);
256 }
257 return nullptr;
258}
259
260void Starter::Run() {
Tyler Chatow03fdb2a2020-12-26 18:39:36 -0800261#ifdef AOS_ARCHITECTURE_arm_frc
262 PCHECK(setuid(0) == 0) << "Failed to change user to root";
263#endif
264
Tyler Chatowa79419d2020-08-12 20:12:11 -0700265 for (auto &application : applications_) {
Austin Schuh5f79a5a2021-10-12 17:46:50 -0700266 if (application.second.autostart()) {
267 application.second.Start();
268 }
Tyler Chatowa79419d2020-08-12 20:12:11 -0700269 }
270
271 event_loop_.Run();
272}
273
James Kuszmaul2c10e052023-08-09 10:22:36 -0700274void Starter::ServiceTimingReportFetcher(int elapsed_cycles) {
275 // If there is any chance that it has been longer than one cycle since we last
276 // serviced the fetcher, call Fetch(). This reduces the chances that the
277 // fetcher falls behind when the system is under heavy load. Dropping a few
278 // timing report messages when the system is under stress is fine.
279 if (timing_report_fetcher_.get() == nullptr || elapsed_cycles > 1) {
280 timing_report_fetcher_.Fetch();
281 }
James Kuszmaul8544c492023-07-31 15:00:38 -0700282 while (timing_report_fetcher_.FetchNext()) {
283 for (auto &application : applications_) {
284 application.second.ObserveTimingReport(
285 timing_report_fetcher_.context().monotonic_event_time,
286 timing_report_fetcher_.get());
287 }
288 }
289}
290
Tyler Chatowa79419d2020-08-12 20:12:11 -0700291void Starter::SendStatus() {
292 aos::Sender<aos::starter::Status>::Builder builder =
293 status_sender_.MakeBuilder();
294
295 std::vector<flatbuffers::Offset<aos::starter::ApplicationStatus>> statuses;
296
297 for (auto &application : applications_) {
James Kuszmaul6295a642022-03-22 15:23:59 -0700298 statuses.push_back(application.second.PopulateStatus(builder.fbb(), &top_));
Tyler Chatowa79419d2020-08-12 20:12:11 -0700299 }
300
301 auto statuses_fbs = builder.fbb()->CreateVector(statuses);
302
303 aos::starter::Status::Builder status_builder(*builder.fbb());
304 status_builder.add_statuses(statuses_fbs);
milind1f1dca32021-07-03 13:50:07 -0700305 builder.CheckOk(builder.Send(status_builder.Finish()));
Tyler Chatowa79419d2020-08-12 20:12:11 -0700306}
307
Austin Schuh4d275fc2022-09-16 15:42:45 -0700308void Starter::AddChannel(const aos::Channel *channel) {
309 CHECK_NOTNULL(channel);
Austin Schuh816a1162023-05-31 16:29:47 -0700310 std::unique_ptr<aos::ipc_lib::MemoryMappedQueue> queue =
311 std::make_unique<aos::ipc_lib::MemoryMappedQueue>(
312 shm_base_, FLAGS_permissions, event_loop_.configuration(), channel);
313
314 {
315 std::unique_lock<std::mutex> locker(queue_mutex_);
316 shm_queues_.emplace_back(std::move(queue));
317 }
Austin Schuh4d275fc2022-09-16 15:42:45 -0700318 VLOG(1) << "Created MemoryMappedQueue for "
319 << aos::configuration::StrippedChannelToString(channel) << " under "
320 << shm_base_;
321}
322
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800323} // namespace aos::starter