blob: 5f14e21930bfd50b8096008b4b46d61e2f6826dc [file] [log] [blame]
Tyler Chatowa79419d2020-08-12 20:12:11 -07001#include "starter_rpc_lib.h"
2
3#include "aos/events/shm_event_loop.h"
4#include "aos/flatbuffer_merge.h"
James Kuszmaul293b2172021-11-10 16:20:48 -08005#include "aos/starter/starterd_lib.h"
milind1f1dca32021-07-03 13:50:07 -07006#include "glog/logging.h"
Tyler Chatowa79419d2020-08-12 20:12:11 -07007
8namespace aos {
9namespace starter {
10
James Kuszmaul293b2172021-11-10 16:20:48 -080011namespace {
12State ExpectedStateForCommand(Command command) {
13 switch (command) {
14 case Command::START:
15 case Command::RESTART:
16 return State::RUNNING;
17 case Command::STOP:
18 return State::STOPPED;
19 }
20 return State::STOPPED;
21}
22} // namespace
23
Tyler Chatowa79419d2020-08-12 20:12:11 -070024const aos::starter::ApplicationStatus *FindApplicationStatus(
25 const aos::starter::Status &status, std::string_view name) {
26 if (!status.has_statuses()) {
27 return nullptr;
28 }
29
30 auto statuses = status.statuses();
31
32 auto search =
33 std::find_if(statuses->begin(), statuses->end(),
34 [name](const aos::starter::ApplicationStatus *app_status) {
35 return app_status->has_name() &&
36 app_status->name()->string_view() == name;
37 });
38 if (search == statuses->end()) {
39 return nullptr;
40 }
41 return *search;
42}
43
Austin Schuhdae1e8d2022-03-26 15:09:31 -070044std::string_view FindApplication(const std::string_view name,
milind upadhyay4272f382021-04-07 18:03:08 -070045 const aos::Configuration *config) {
46 std::string_view app_name = name;
47 for (const auto app : *config->applications()) {
Austin Schuhdae1e8d2022-03-26 15:09:31 -070048 if (app->name()->string_view() == name) {
49 return name;
50 }
51 }
52 for (const auto app : *config->applications()) {
Milind Upadhyay7641ce82021-04-10 14:15:28 -070053 if (app->has_executable_name() &&
milind upadhyay4272f382021-04-07 18:03:08 -070054 app->executable_name()->string_view() == name) {
55 app_name = app->name()->string_view();
56 break;
57 }
58 }
59 return app_name;
60}
61
James Kuszmaul293b2172021-11-10 16:20:48 -080062StarterClient::StarterClient(EventLoop *event_loop)
63 : event_loop_(event_loop),
64 timeout_timer_(event_loop_->AddTimer([this]() { Timeout(); })),
65 cmd_sender_(event_loop_->MakeSender<StarterRpc>("/aos")) {
66 if (configuration::MultiNode(event_loop_->configuration())) {
67 for (const aos::Node *node :
68 configuration::GetNodes(event_loop_->configuration())) {
69 const Channel *channel =
70 StatusChannelForNode(event_loop_->configuration(), node);
71 CHECK(channel != nullptr) << ": Failed to find channel /aos for "
72 << Status::GetFullyQualifiedName() << " on "
73 << node->name()->string_view();
74 if (!configuration::ChannelIsReadableOnNode(channel,
75 event_loop_->node())) {
James Kuszmaul9d36a622021-11-10 16:48:00 -080076 VLOG(1) << "Status channel "
77 << configuration::StrippedChannelToString(channel)
78 << " is not readable on "
79 << event_loop_->node()->name()->string_view();
James Kuszmaul293b2172021-11-10 16:20:48 -080080 } else if (!configuration::ChannelIsReadableOnNode(
81 StarterRpcChannelForNode(event_loop_->configuration(),
82 event_loop_->node()),
83 node)) {
84 // Don't attempt to construct a status fetcher if the other node won't
85 // even be able to receive our commands.
James Kuszmaul9d36a622021-11-10 16:48:00 -080086 VLOG(1) << "StarterRpc channel for "
87 << event_loop_->node()->name()->string_view()
88 << " is not readable on " << node->name()->string_view();
James Kuszmaul293b2172021-11-10 16:20:48 -080089 } else {
90 status_fetchers_[node->name()->str()] =
91 event_loop_->MakeFetcher<Status>(channel->name()->string_view());
92 event_loop_->MakeNoArgWatcher<Status>(channel->name()->string_view(),
93 [this]() {
94 if (CheckCommandsSucceeded()) {
95 Succeed();
96 }
97 });
98 }
99 }
100 } else {
101 status_fetchers_[""] = event_loop_->MakeFetcher<Status>("/aos");
102 event_loop_->MakeNoArgWatcher<Status>("/aos", [this]() {
103 if (CheckCommandsSucceeded()) {
104 Succeed();
105 }
106 });
107 }
Austin Schuhe4b748a2021-10-16 14:19:58 -0700108}
109
James Kuszmaul293b2172021-11-10 16:20:48 -0800110void StarterClient::SendCommands(
111 const std::vector<ApplicationCommand> &commands,
112 monotonic_clock::duration timeout) {
113 CHECK(current_commands_.empty());
114 for (auto &pair : status_fetchers_) {
115 pair.second.Fetch();
116 }
117 const bool is_multi_node =
118 aos::configuration::MultiNode(event_loop_->configuration());
119 for (const auto &command : commands) {
120 auto builder = cmd_sender_.MakeBuilder();
121 const auto application_offset =
122 builder.fbb()->CreateString(command.application);
123 std::vector<flatbuffers::Offset<flatbuffers::String>> node_offsets;
124 CHECK(!command.nodes.empty())
125 << "At least one node must be specified for application "
126 << command.application;
127 for (const aos::Node *node : command.nodes) {
128 const std::string node_name((node == nullptr) ? "" : node->name()->str());
129 if (status_fetchers_.count(node_name) == 0) {
130 if (is_multi_node) {
131 LOG(FATAL) << "Node \"" << node_name
132 << "\" must be configured to both receive StarterRpc "
133 "messages from \""
134 << event_loop_->node()->name()->string_view()
135 << "\" as well as to send starter Status messages back.";
136 } else {
137 LOG(FATAL) << "On single-node configs, use an empty string for the "
138 "node name.";
139 }
140 }
James Kuszmaul43d70162023-03-04 18:25:14 -0800141 if (status_fetchers_[node_name].get() == nullptr) {
142 LOG(WARNING) << ": No status available for node " << node_name
143 << "; not executing commands for that node.";
144 continue;
145 }
James Kuszmaul293b2172021-11-10 16:20:48 -0800146 if (is_multi_node) {
147 node_offsets.push_back(builder.fbb()->CreateString(node_name));
148 }
149 const ApplicationStatus *last_status =
150 CHECK_NOTNULL(FindApplicationStatus(*status_fetchers_[node_name],
151 command.application));
152 current_commands_[node_name].push_back(CommandStatus{
153 .expected_state = ExpectedStateForCommand(command.command),
154 .application = std::string(command.application),
155 .old_id = std::nullopt});
156 // If we are restarting, then we need to track what the current ID of the
157 // process is to ensure that it actually got restarted. For just starting,
158 // we leave the application running and so don't care.
159 if (command.command == Command::RESTART && last_status->has_id()) {
160 current_commands_[node_name].back().old_id = last_status->id();
161 }
162 }
163 flatbuffers::Offset<
164 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
165 nodes_offset;
166 if (is_multi_node) {
167 nodes_offset = builder.fbb()->CreateVector(node_offsets);
168 }
169 auto command_builder = builder.MakeBuilder<StarterRpc>();
170 command_builder.add_command(command.command);
171 command_builder.add_name(application_offset);
172 if (is_multi_node) {
173 command_builder.add_nodes(nodes_offset);
174 }
milind1f1dca32021-07-03 13:50:07 -0700175 builder.CheckOk(builder.Send(command_builder.Finish()));
James Kuszmaul293b2172021-11-10 16:20:48 -0800176 }
177
178 timeout_timer_->Setup(event_loop_->monotonic_now() + timeout);
179}
180
181bool StarterClient::CheckCommandsSucceeded() {
182 if (current_commands_.empty()) {
183 return false;
184 }
185
186 for (auto &pair : status_fetchers_) {
187 pair.second.Fetch();
188 }
189
190 bool succeeded = true;
191
192 for (const auto &pair : current_commands_) {
193 if (pair.second.empty()) {
194 continue;
195 }
196 CHECK(status_fetchers_[pair.first].get() != nullptr)
197 << ": No status available for node " << pair.first;
198 const Status &status = *status_fetchers_[pair.first];
199 for (const auto &command : pair.second) {
200 const ApplicationStatus *application_status =
201 CHECK_NOTNULL(FindApplicationStatus(status, command.application));
202 if (application_status->state() == command.expected_state) {
203 if (command.expected_state == State::RUNNING &&
204 application_status->id() == command.old_id) {
205 succeeded = false;
206 }
207 } else {
208 succeeded = false;
209 }
210 }
211 }
212 return succeeded;
213}
214
215void StarterClient::Timeout() {
216 // Clear commands prior to calling handlers to allow the handler to call
217 // SendCommands() again if desired.
218 current_commands_.clear();
219 if (timeout_handler_) {
220 timeout_handler_();
221 }
222}
223
224void StarterClient::Succeed() {
225 // Clear commands prior to calling handlers to allow the handler to call
226 // SendCommands() again if desired.
227 current_commands_.clear();
Austin Schuh59398d32023-05-03 08:10:55 -0700228 // Clear the timer before calling success handler, in case the success
229 // handler needs to modify timeout handler.
230 timeout_timer_->Disable();
James Kuszmaul293b2172021-11-10 16:20:48 -0800231 if (success_handler_) {
232 success_handler_();
233 }
James Kuszmaul293b2172021-11-10 16:20:48 -0800234}
235
236bool SendCommandBlocking(aos::starter::Command command, std::string_view name,
237 const aos::Configuration *config,
238 std::chrono::milliseconds timeout,
239 std::vector<const aos::Node *> nodes) {
240 return SendCommandBlocking({{command, name, nodes}}, config, timeout);
241}
242
243bool SendCommandBlocking(const std::vector<ApplicationCommand> &commands,
244 const aos::Configuration *config,
245 std::chrono::milliseconds timeout) {
Tyler Chatowa79419d2020-08-12 20:12:11 -0700246 aos::ShmEventLoop event_loop(config);
247 event_loop.SkipAosLog();
248
James Kuszmaul293b2172021-11-10 16:20:48 -0800249 StarterClient client(&event_loop);
Tyler Chatowa79419d2020-08-12 20:12:11 -0700250
Austin Schuhe4b748a2021-10-16 14:19:58 -0700251 // Wait until event loop starts to send all commands so the watcher is ready
James Kuszmaul293b2172021-11-10 16:20:48 -0800252 event_loop.OnRun([&commands, &client, timeout]() {
253 client.SendCommands(commands, timeout);
Tyler Chatowa79419d2020-08-12 20:12:11 -0700254 });
255
256 // If still waiting after timeout milliseconds, exit the loop
James Kuszmaul293b2172021-11-10 16:20:48 -0800257 client.SetTimeoutHandler([&event_loop]() { event_loop.Exit(); });
Tyler Chatowa79419d2020-08-12 20:12:11 -0700258
Tyler Chatowa79419d2020-08-12 20:12:11 -0700259 bool success = false;
Tyler Chatowa79419d2020-08-12 20:12:11 -0700260
James Kuszmaul293b2172021-11-10 16:20:48 -0800261 client.SetSuccessHandler([&event_loop, &success]() {
262 success = true;
263 event_loop.Exit();
Austin Schuhe4b748a2021-10-16 14:19:58 -0700264 });
Tyler Chatowa79419d2020-08-12 20:12:11 -0700265
266 event_loop.Run();
267
268 return success;
269}
270
James Kuszmaul2ca441b2022-01-07 18:16:23 -0800271const std::optional<
272 std::pair<aos::monotonic_clock::time_point,
273 FlatbufferDetachedBuffer<aos::starter::ApplicationStatus>>>
James Kuszmaule4bb0a22022-01-07 18:14:43 -0800274GetStatus(std::string_view name, const Configuration *config,
275 const aos::Node *node) {
Tyler Chatowa79419d2020-08-12 20:12:11 -0700276 ShmEventLoop event_loop(config);
277 event_loop.SkipAosLog();
278
James Kuszmaul293b2172021-11-10 16:20:48 -0800279 auto status_fetcher = event_loop.MakeFetcher<aos::starter::Status>(
280 StatusChannelForNode(config, node)->name()->string_view());
Tyler Chatowa79419d2020-08-12 20:12:11 -0700281 status_fetcher.Fetch();
James Kuszmaule4bb0a22022-01-07 18:14:43 -0800282 if (status_fetcher.get() != nullptr) {
283 const aos::starter::ApplicationStatus *status =
284 FindApplicationStatus(*status_fetcher, name);
285 if (status != nullptr) {
James Kuszmaul2ca441b2022-01-07 18:16:23 -0800286 return std::make_pair(status_fetcher.context().monotonic_remote_time,
287 aos::CopyFlatBuffer(status));
James Kuszmaule4bb0a22022-01-07 18:14:43 -0800288 }
289 }
290 return std::nullopt;
Tyler Chatowa79419d2020-08-12 20:12:11 -0700291}
292
James Kuszmaul293b2172021-11-10 16:20:48 -0800293std::optional<std::pair<aos::monotonic_clock::time_point,
294 const aos::FlatbufferVector<aos::starter::Status>>>
295GetStarterStatus(const aos::Configuration *config, const aos::Node *node) {
Philipp Schrader08537492021-01-23 16:17:55 -0800296 ShmEventLoop event_loop(config);
297 event_loop.SkipAosLog();
298
James Kuszmaul293b2172021-11-10 16:20:48 -0800299 auto status_fetcher = event_loop.MakeFetcher<aos::starter::Status>(
300 StatusChannelForNode(config, node)->name()->string_view());
Philipp Schrader08537492021-01-23 16:17:55 -0800301 status_fetcher.Fetch();
James Kuszmaul293b2172021-11-10 16:20:48 -0800302 return (status_fetcher.get() == nullptr)
303 ? std::nullopt
304 : std::make_optional(std::make_pair(
305 status_fetcher.context().monotonic_remote_time,
306 status_fetcher.CopyFlatBuffer()));
Philipp Schrader08537492021-01-23 16:17:55 -0800307}
308
Tyler Chatowa79419d2020-08-12 20:12:11 -0700309} // namespace starter
310} // namespace aos