1 //
2 // Copyright (C) 2019 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 #include <iostream>
17 #include <sstream>
18 #include <fstream>
19
20 #include <gflags/gflags.h>
21 #include <android-base/logging.h>
22
23 #include "common/libs/fs/shared_buf.h"
24 #include "common/libs/fs/shared_fd.h"
25 #include "common/libs/utils/subprocess.h"
26 #include "host/commands/launch/filesystem_explorer.h"
27 #include "host/libs/config/cuttlefish_config.h"
28 #include "host/libs/config/fetcher_config.h"
29
30 #include "flag_forwarder.h"
31
32 /**
33 * If stdin is a tty, that means a user is invoking launch_cvd on the command
34 * line and wants automatic file detection for assemble_cvd.
35 *
36 * If stdin is not a tty, that means launch_cvd is being passed a list of files
37 * and that list should be forwarded to assemble_cvd.
38 *
39 * Controllable with a flag for extraordinary scenarios such as running from a
40 * daemon which closes its own stdin.
41 */
42 DEFINE_bool(run_file_discovery, true,
43 "Whether to run file discovery or get input files from stdin.");
44 DEFINE_int32(num_instances, 1, "Number of Android guests to launch");
45 DEFINE_string(report_anonymous_usage_stats, "", "Report anonymous usage "
46 "statistics for metrics collection and analysis.");
47 DEFINE_int32(base_instance_num,
48 cuttlefish::GetInstance(),
49 "The instance number of the device created. When `-num_instances N`"
50 " is used, N instance numbers are claimed starting at this number.");
51 DEFINE_string(verbosity, "INFO", "Console logging verbosity. Options are VERBOSE,"
52 "DEBUG,INFO,WARNING,ERROR");
53
54 namespace {
55
56 std::string kAssemblerBin = cuttlefish::DefaultHostArtifactsPath("bin/assemble_cvd");
57 std::string kRunnerBin = cuttlefish::DefaultHostArtifactsPath("bin/run_cvd");
58
StartAssembler(cuttlefish::SharedFD assembler_stdin,cuttlefish::SharedFD assembler_stdout,const std::vector<std::string> & argv)59 cuttlefish::Subprocess StartAssembler(cuttlefish::SharedFD assembler_stdin,
60 cuttlefish::SharedFD assembler_stdout,
61 const std::vector<std::string>& argv) {
62 cuttlefish::Command assemble_cmd(kAssemblerBin);
63 for (const auto& arg : argv) {
64 assemble_cmd.AddParameter(arg);
65 }
66 if (assembler_stdin->IsOpen()) {
67 assemble_cmd.RedirectStdIO(cuttlefish::Subprocess::StdIOChannel::kStdIn, assembler_stdin);
68 }
69 assemble_cmd.RedirectStdIO(cuttlefish::Subprocess::StdIOChannel::kStdOut, assembler_stdout);
70 return assemble_cmd.Start();
71 }
72
StartRunner(cuttlefish::SharedFD runner_stdin,const std::vector<std::string> & argv)73 cuttlefish::Subprocess StartRunner(cuttlefish::SharedFD runner_stdin,
74 const std::vector<std::string>& argv) {
75 cuttlefish::Command run_cmd(kRunnerBin);
76 for (const auto& arg : argv) {
77 run_cmd.AddParameter(arg);
78 }
79 run_cmd.RedirectStdIO(cuttlefish::Subprocess::StdIOChannel::kStdIn, runner_stdin);
80 return run_cmd.Start();
81 }
82
WriteFiles(cuttlefish::FetcherConfig fetcher_config,cuttlefish::SharedFD out)83 void WriteFiles(cuttlefish::FetcherConfig fetcher_config, cuttlefish::SharedFD out) {
84 std::stringstream output_streambuf;
85 for (const auto& file : fetcher_config.get_cvd_files()) {
86 output_streambuf << file.first << "\n";
87 }
88 std::string output_string = output_streambuf.str();
89 int written = cuttlefish::WriteAll(out, output_string);
90 if (written < 0) {
91 LOG(FATAL) << "Could not write file report (" << strerror(out->GetErrno())
92 << ")";
93 }
94 }
95
ValidateMetricsConfirmation(std::string use_metrics)96 std::string ValidateMetricsConfirmation(std::string use_metrics) {
97 if (use_metrics == "") {
98 if (cuttlefish::CuttlefishConfig::ConfigExists()) {
99 auto config = cuttlefish::CuttlefishConfig::Get();
100 if (config) {
101 if (config->enable_metrics() == cuttlefish::CuttlefishConfig::kYes) {
102 use_metrics = "y";
103 } else if (config->enable_metrics() == cuttlefish::CuttlefishConfig::kNo) {
104 use_metrics = "n";
105 }
106 }
107 }
108 }
109 char ch = !use_metrics.empty() ? tolower(use_metrics.at(0)) : -1;
110 if (ch != 'n') {
111 std::cout << "===================================================================\n";
112 std::cout << "NOTICE:\n\n";
113 std::cout << "We collect usage statistics in accordance with our\n"
114 "Content Licenses (https://source.android.com/setup/start/licenses),\n"
115 "Contributor License Agreement (https://cla.developers.google.com/),\n"
116 "Privacy Policy (https://policies.google.com/privacy) and\n"
117 "Terms of Service (https://policies.google.com/terms).\n";
118 std::cout << "===================================================================\n\n";
119 if (use_metrics.empty()) {
120 std::cout << "Do you accept anonymous usage statistics reporting (Y/n)?: ";
121 }
122 }
123 for (;;) {
124 switch (ch) {
125 case 0:
126 case '\r':
127 case '\n':
128 case 'y':
129 return "y";
130 case 'n':
131 return "n";
132 default:
133 std::cout << "Must accept/reject anonymous usage statistics reporting (Y/n): ";
134 FALLTHROUGH_INTENDED;
135 case -1:
136 std::cin.get(ch);
137 ch = tolower(ch);
138 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
139 }
140 }
141 return "";
142 }
143 } // namespace
144
main(int argc,char ** argv)145 int main(int argc, char** argv) {
146 ::android::base::InitLogging(argv, android::base::StderrLogger);
147
148 FlagForwarder forwarder({kAssemblerBin, kRunnerBin});
149
150 gflags::ParseCommandLineNonHelpFlags(&argc, &argv, false);
151
152 forwarder.UpdateFlagDefaults();
153
154 gflags::HandleCommandLineHelpFlags();
155
156 setenv("CF_CONSOLE_SEVERITY", FLAGS_verbosity.c_str(), /* replace */ false);
157
158 auto use_metrics = FLAGS_report_anonymous_usage_stats;
159 FLAGS_report_anonymous_usage_stats = ValidateMetricsConfirmation(use_metrics);
160
161 cuttlefish::SharedFD assembler_stdout, assembler_stdout_capture;
162 cuttlefish::SharedFD::Pipe(&assembler_stdout_capture, &assembler_stdout);
163
164 cuttlefish::SharedFD launcher_report, assembler_stdin;
165 bool should_generate_report = FLAGS_run_file_discovery;
166 if (should_generate_report) {
167 cuttlefish::SharedFD::Pipe(&assembler_stdin, &launcher_report);
168 }
169
170 auto instance_num_str = std::to_string(FLAGS_base_instance_num);
171 setenv("CUTTLEFISH_INSTANCE", instance_num_str.c_str(), /* overwrite */ 0);
172
173 // SharedFDs are std::move-d in to avoid dangling references.
174 // Removing the std::move will probably make run_cvd hang as its stdin never closes.
175 auto assemble_proc = StartAssembler(std::move(assembler_stdin),
176 std::move(assembler_stdout),
177 forwarder.ArgvForSubprocess(kAssemblerBin));
178
179 if (should_generate_report) {
180 WriteFiles(AvailableFilesReport(), std::move(launcher_report));
181 }
182
183 std::string assembler_output;
184 if (cuttlefish::ReadAll(assembler_stdout_capture, &assembler_output) < 0) {
185 int error_num = errno;
186 LOG(ERROR) << "Read error getting output from assemble_cvd: " << strerror(error_num);
187 return -1;
188 }
189
190 auto assemble_ret = assemble_proc.Wait();
191 if (assemble_ret != 0) {
192 LOG(ERROR) << "assemble_cvd returned " << assemble_ret;
193 return assemble_ret;
194 } else {
195 LOG(DEBUG) << "assemble_cvd exited successfully.";
196 }
197
198 std::vector<cuttlefish::Subprocess> runners;
199 for (int i = 0; i < FLAGS_num_instances; i++) {
200 cuttlefish::SharedFD runner_stdin_in, runner_stdin_out;
201 cuttlefish::SharedFD::Pipe(&runner_stdin_out, &runner_stdin_in);
202 std::string instance_name = std::to_string(i + FLAGS_base_instance_num);
203 setenv("CUTTLEFISH_INSTANCE", instance_name.c_str(), /* overwrite */ 1);
204
205 auto run_proc = StartRunner(std::move(runner_stdin_out),
206 forwarder.ArgvForSubprocess(kRunnerBin));
207 runners.push_back(std::move(run_proc));
208 if (cuttlefish::WriteAll(runner_stdin_in, assembler_output) < 0) {
209 int error_num = errno;
210 LOG(ERROR) << "Could not write to run_cvd: " << strerror(error_num);
211 return -1;
212 }
213 }
214
215 bool run_cvd_failure = false;
216 for (auto& run_proc : runners) {
217 auto run_ret = run_proc.Wait();
218 if (run_ret != 0) {
219 run_cvd_failure = true;
220 LOG(ERROR) << "run_cvd returned " << run_ret;
221 } else {
222 LOG(DEBUG) << "run_cvd exited successfully.";
223 }
224 }
225 return run_cvd_failure ? -1 : 0;
226 }
227