1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <dirent.h>
18 #include <inttypes.h>
19 #include <limits.h>
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <signal.h>
29 
30 #include <algorithm>
31 #include <cstdlib>
32 #include <fstream>
33 #include <iomanip>
34 #include <memory>
35 #include <sstream>
36 #include <string>
37 #include <vector>
38 
39 #include <android-base/strings.h>
40 #include <gflags/gflags.h>
41 #include <android-base/logging.h>
42 
43 #include "common/libs/fs/shared_fd.h"
44 #include "common/libs/fs/shared_select.h"
45 #include "common/libs/utils/environment.h"
46 #include "host/commands/run_cvd/runner_defs.h"
47 #include "host/libs/config/cuttlefish_config.h"
48 #include "host/libs/vm_manager/vm_manager.h"
49 
50 DEFINE_int32(wait_for_launcher, 5,
51              "How many seconds to wait for the launcher to respond to the stop "
52              "command. A value of zero means wait indefinetly");
53 
54 namespace {
55 
FallbackPaths()56 std::set<std::string> FallbackPaths() {
57   std::set<std::string> paths;
58   std::string parent_path = cuttlefish::StringFromEnv("HOME", ".");
59   paths.insert(parent_path + "/cuttlefish_assembly");
60   paths.insert(parent_path + "/cuttlefish_assembly/*");
61 
62   std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(parent_path.c_str()), closedir);
63   for (auto entity = readdir(dir.get()); entity != nullptr; entity = readdir(dir.get())) {
64     std::string subdir(entity->d_name);
65     if (!android::base::StartsWith(subdir, "cuttlefish_runtime.")) {
66       continue;
67     }
68     auto instance_dir = parent_path + "/" + subdir;
69     // Add the instance directory
70     paths.insert(instance_dir);
71     // Add files in instance dir
72     paths.insert(instance_dir + "/*");
73     // Add files in the tombstone directory
74     paths.insert(instance_dir + "/tombstones/*");
75     // Add files in the internal directory
76     paths.insert(instance_dir + "/" + std::string(cuttlefish::kInternalDirName) + "/*");
77     // Add files in the shared directory
78     paths.insert(instance_dir + "/" + std::string(cuttlefish::kSharedDirName) + "/*");
79   }
80   return paths;
81 }
82 
PathsForInstance(const cuttlefish::CuttlefishConfig & config,const cuttlefish::CuttlefishConfig::InstanceSpecific instance)83 std::set<std::string> PathsForInstance(const cuttlefish::CuttlefishConfig& config,
84                                        const cuttlefish::CuttlefishConfig::InstanceSpecific instance) {
85   return {
86     config.assembly_dir(),
87     config.assembly_dir() + "/*",
88     instance.instance_dir(),
89     instance.PerInstancePath("*"),
90     instance.PerInstancePath("tombstones"),
91     instance.PerInstancePath("tombstones/*"),
92     instance.instance_internal_dir(),
93     instance.PerInstanceInternalPath("*"),
94     instance.PerInstancePath(cuttlefish::kSharedDirName),
95     instance.PerInstancePath(cuttlefish::kSharedDirName) + "/*",
96   };
97 }
98 
99 // Gets a set of the possible process groups of a previous launch
GetCandidateProcessGroups(const std::set<std::string> & paths)100 std::set<pid_t> GetCandidateProcessGroups(const std::set<std::string>& paths) {
101   std::stringstream cmd;
102   cmd << "lsof -t 2>/dev/null";
103   for (const auto& path : paths) {
104     cmd << " " << path;
105   }
106   std::string cmd_str = cmd.str();
107   std::shared_ptr<FILE> cmd_out(popen(cmd_str.c_str(), "r"), pclose);
108   if (!cmd_out) {
109     LOG(ERROR) << "Unable to execute '" << cmd_str << "': " << strerror(errno);
110     return {};
111   }
112   int64_t pid;
113   std::set<pid_t> ret{};
114   while(fscanf(cmd_out.get(), "%" PRId64, &pid) != EOF) {
115     pid_t pgid = getpgid(static_cast<pid_t>(pid));
116     if (pgid < 0) {
117       LOG(ERROR) << "Unable to get process group of " << pid << ": "
118                  << strerror(errno);
119       continue;
120     }
121     ret.insert(pgid);
122   }
123   // The process group of stop_cvd should not be killed
124   ret.erase(getpgrp());
125   return ret;
126 }
127 
FallBackStop(const std::set<std::string> & paths)128 int FallBackStop(const std::set<std::string>& paths) {
129   auto exit_code = 1; // Having to fallback is an error
130 
131   auto process_groups = GetCandidateProcessGroups(paths);
132   for (auto pgid: process_groups) {
133     LOG(INFO) << "Sending SIGKILL to process group " << pgid;
134     auto retval = killpg(pgid, SIGKILL);
135     if (retval < 0) {
136       LOG(ERROR) << "Failed to kill process group " << pgid << ": "
137                  << strerror(errno);
138       exit_code |= 4;
139     }
140   }
141 
142   return exit_code;
143 }
144 
CleanStopInstance(const cuttlefish::CuttlefishConfig::InstanceSpecific & instance)145 bool CleanStopInstance(const cuttlefish::CuttlefishConfig::InstanceSpecific& instance) {
146   auto monitor_path = instance.launcher_monitor_socket_path();
147   if (monitor_path.empty()) {
148     LOG(ERROR) << "No path to launcher monitor found";
149     return false;
150   }
151   auto monitor_socket = cuttlefish::SharedFD::SocketLocalClient(monitor_path.c_str(),
152                                                          false, SOCK_STREAM);
153   if (!monitor_socket->IsOpen()) {
154     LOG(ERROR) << "Unable to connect to launcher monitor at " << monitor_path
155                << ": " << monitor_socket->StrError();
156     return false;
157   }
158   auto request = cuttlefish::LauncherAction::kStop;
159   auto bytes_sent = monitor_socket->Send(&request, sizeof(request), 0);
160   if (bytes_sent < 0) {
161     LOG(ERROR) << "Error sending launcher monitor the stop command: "
162                << monitor_socket->StrError();
163     return false;
164   }
165   // Perform a select with a timeout to guard against launcher hanging
166   cuttlefish::SharedFDSet read_set;
167   read_set.Set(monitor_socket);
168   struct timeval timeout = {FLAGS_wait_for_launcher, 0};
169   int selected = cuttlefish::Select(&read_set, nullptr, nullptr,
170                              FLAGS_wait_for_launcher <= 0 ? nullptr : &timeout);
171   if (selected < 0){
172     LOG(ERROR) << "Failed communication with the launcher monitor: "
173                << strerror(errno);
174     return false;
175   }
176   if (selected == 0) {
177     LOG(ERROR) << "Timeout expired waiting for launcher monitor to respond";
178     return false;
179   }
180   cuttlefish::LauncherResponse response;
181   auto bytes_recv = monitor_socket->Recv(&response, sizeof(response), 0);
182   if (bytes_recv < 0) {
183     LOG(ERROR) << "Error receiving response from launcher monitor: "
184                << monitor_socket->StrError();
185     return false;
186   }
187   if (response != cuttlefish::LauncherResponse::kSuccess) {
188     LOG(ERROR) << "Received '" << static_cast<char>(response)
189                << "' response from launcher monitor";
190     return false;
191   }
192   LOG(INFO) << "Successfully stopped device " << instance.adb_ip_and_port();
193   return true;
194 }
195 
StopInstance(const cuttlefish::CuttlefishConfig & config,const cuttlefish::CuttlefishConfig::InstanceSpecific & instance)196 int StopInstance(const cuttlefish::CuttlefishConfig& config,
197                  const cuttlefish::CuttlefishConfig::InstanceSpecific& instance) {
198   bool res = CleanStopInstance(instance);
199   if (!res) {
200     return FallBackStop(PathsForInstance(config, instance));
201   }
202   return 0;
203 }
204 
205 }  // anonymous namespace
206 
main(int argc,char ** argv)207 int main(int argc, char** argv) {
208   ::android::base::InitLogging(argv, android::base::StderrLogger);
209   google::ParseCommandLineFlags(&argc, &argv, true);
210 
211   auto config = cuttlefish::CuttlefishConfig::Get();
212   if (!config) {
213     LOG(ERROR) << "Failed to obtain config object";
214     return FallBackStop(FallbackPaths());
215   }
216 
217   int ret = 0;
218   for (const auto& instance : config->Instances()) {
219     ret |= StopInstance(*config, instance);
220   }
221 
222   return ret;
223 }
224