blob: 884367d338f78d930701fb62977610ef6f77c2d0 [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 }
141 CHECK(status_fetchers_[node_name].get() != nullptr)
142 << ": No status available for node " << node_name;
143 if (is_multi_node) {
144 node_offsets.push_back(builder.fbb()->CreateString(node_name));
145 }
146 const ApplicationStatus *last_status =
147 CHECK_NOTNULL(FindApplicationStatus(*status_fetchers_[node_name],
148 command.application));
149 current_commands_[node_name].push_back(CommandStatus{
150 .expected_state = ExpectedStateForCommand(command.command),
151 .application = std::string(command.application),
152 .old_id = std::nullopt});
153 // If we are restarting, then we need to track what the current ID of the
154 // process is to ensure that it actually got restarted. For just starting,
155 // we leave the application running and so don't care.
156 if (command.command == Command::RESTART && last_status->has_id()) {
157 current_commands_[node_name].back().old_id = last_status->id();
158 }
159 }
160 flatbuffers::Offset<
161 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
162 nodes_offset;
163 if (is_multi_node) {
164 nodes_offset = builder.fbb()->CreateVector(node_offsets);
165 }
166 auto command_builder = builder.MakeBuilder<StarterRpc>();
167 command_builder.add_command(command.command);
168 command_builder.add_name(application_offset);
169 if (is_multi_node) {
170 command_builder.add_nodes(nodes_offset);
171 }
milind1f1dca32021-07-03 13:50:07 -0700172 builder.CheckOk(builder.Send(command_builder.Finish()));
James Kuszmaul293b2172021-11-10 16:20:48 -0800173 }
174
175 timeout_timer_->Setup(event_loop_->monotonic_now() + timeout);
176}
177
178bool StarterClient::CheckCommandsSucceeded() {
179 if (current_commands_.empty()) {
180 return false;
181 }
182
183 for (auto &pair : status_fetchers_) {
184 pair.second.Fetch();
185 }
186
187 bool succeeded = true;
188
189 for (const auto &pair : current_commands_) {
190 if (pair.second.empty()) {
191 continue;
192 }
193 CHECK(status_fetchers_[pair.first].get() != nullptr)
194 << ": No status available for node " << pair.first;
195 const Status &status = *status_fetchers_[pair.first];
196 for (const auto &command : pair.second) {
197 const ApplicationStatus *application_status =
198 CHECK_NOTNULL(FindApplicationStatus(status, command.application));
199 if (application_status->state() == command.expected_state) {
200 if (command.expected_state == State::RUNNING &&
201 application_status->id() == command.old_id) {
202 succeeded = false;
203 }
204 } else {
205 succeeded = false;
206 }
207 }
208 }
209 return succeeded;
210}
211
212void StarterClient::Timeout() {
213 // Clear commands prior to calling handlers to allow the handler to call
214 // SendCommands() again if desired.
215 current_commands_.clear();
216 if (timeout_handler_) {
217 timeout_handler_();
218 }
219}
220
221void StarterClient::Succeed() {
222 // Clear commands prior to calling handlers to allow the handler to call
223 // SendCommands() again if desired.
224 current_commands_.clear();
225 if (success_handler_) {
226 success_handler_();
227 }
228 timeout_timer_->Disable();
229}
230
231bool SendCommandBlocking(aos::starter::Command command, std::string_view name,
232 const aos::Configuration *config,
233 std::chrono::milliseconds timeout,
234 std::vector<const aos::Node *> nodes) {
235 return SendCommandBlocking({{command, name, nodes}}, config, timeout);
236}
237
238bool SendCommandBlocking(const std::vector<ApplicationCommand> &commands,
239 const aos::Configuration *config,
240 std::chrono::milliseconds timeout) {
Tyler Chatowa79419d2020-08-12 20:12:11 -0700241 aos::ShmEventLoop event_loop(config);
242 event_loop.SkipAosLog();
243
James Kuszmaul293b2172021-11-10 16:20:48 -0800244 StarterClient client(&event_loop);
Tyler Chatowa79419d2020-08-12 20:12:11 -0700245
Austin Schuhe4b748a2021-10-16 14:19:58 -0700246 // Wait until event loop starts to send all commands so the watcher is ready
James Kuszmaul293b2172021-11-10 16:20:48 -0800247 event_loop.OnRun([&commands, &client, timeout]() {
248 client.SendCommands(commands, timeout);
Tyler Chatowa79419d2020-08-12 20:12:11 -0700249 });
250
251 // If still waiting after timeout milliseconds, exit the loop
James Kuszmaul293b2172021-11-10 16:20:48 -0800252 client.SetTimeoutHandler([&event_loop]() { event_loop.Exit(); });
Tyler Chatowa79419d2020-08-12 20:12:11 -0700253
Tyler Chatowa79419d2020-08-12 20:12:11 -0700254 bool success = false;
Tyler Chatowa79419d2020-08-12 20:12:11 -0700255
James Kuszmaul293b2172021-11-10 16:20:48 -0800256 client.SetSuccessHandler([&event_loop, &success]() {
257 success = true;
258 event_loop.Exit();
Austin Schuhe4b748a2021-10-16 14:19:58 -0700259 });
Tyler Chatowa79419d2020-08-12 20:12:11 -0700260
261 event_loop.Run();
262
263 return success;
264}
265
James Kuszmaul2ca441b2022-01-07 18:16:23 -0800266const std::optional<
267 std::pair<aos::monotonic_clock::time_point,
268 FlatbufferDetachedBuffer<aos::starter::ApplicationStatus>>>
James Kuszmaule4bb0a22022-01-07 18:14:43 -0800269GetStatus(std::string_view name, const Configuration *config,
270 const aos::Node *node) {
Tyler Chatowa79419d2020-08-12 20:12:11 -0700271 ShmEventLoop event_loop(config);
272 event_loop.SkipAosLog();
273
James Kuszmaul293b2172021-11-10 16:20:48 -0800274 auto status_fetcher = event_loop.MakeFetcher<aos::starter::Status>(
275 StatusChannelForNode(config, node)->name()->string_view());
Tyler Chatowa79419d2020-08-12 20:12:11 -0700276 status_fetcher.Fetch();
James Kuszmaule4bb0a22022-01-07 18:14:43 -0800277 if (status_fetcher.get() != nullptr) {
278 const aos::starter::ApplicationStatus *status =
279 FindApplicationStatus(*status_fetcher, name);
280 if (status != nullptr) {
James Kuszmaul2ca441b2022-01-07 18:16:23 -0800281 return std::make_pair(status_fetcher.context().monotonic_remote_time,
282 aos::CopyFlatBuffer(status));
James Kuszmaule4bb0a22022-01-07 18:14:43 -0800283 }
284 }
285 return std::nullopt;
Tyler Chatowa79419d2020-08-12 20:12:11 -0700286}
287
James Kuszmaul293b2172021-11-10 16:20:48 -0800288std::optional<std::pair<aos::monotonic_clock::time_point,
289 const aos::FlatbufferVector<aos::starter::Status>>>
290GetStarterStatus(const aos::Configuration *config, const aos::Node *node) {
Philipp Schrader08537492021-01-23 16:17:55 -0800291 ShmEventLoop event_loop(config);
292 event_loop.SkipAosLog();
293
James Kuszmaul293b2172021-11-10 16:20:48 -0800294 auto status_fetcher = event_loop.MakeFetcher<aos::starter::Status>(
295 StatusChannelForNode(config, node)->name()->string_view());
Philipp Schrader08537492021-01-23 16:17:55 -0800296 status_fetcher.Fetch();
James Kuszmaul293b2172021-11-10 16:20:48 -0800297 return (status_fetcher.get() == nullptr)
298 ? std::nullopt
299 : std::make_optional(std::make_pair(
300 status_fetcher.context().monotonic_remote_time,
301 status_fetcher.CopyFlatBuffer()));
Philipp Schrader08537492021-01-23 16:17:55 -0800302}
303
Tyler Chatowa79419d2020-08-12 20:12:11 -0700304} // namespace starter
305} // namespace aos