1 /*
2 * Copyright (C) 2017 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 <android-base/logging.h>
18 #include <android-base/strings.h>
19 #include <build/version.h>
20 #include <fruit/fruit.h>
21 #include <gflags/gflags.h>
22 #include <unistd.h>
23
24 #include <fstream>
25 #include <memory>
26 #include <string>
27 #include <utility>
28 #include <vector>
29
30 #include "common/libs/fs/shared_buf.h"
31 #include "common/libs/fs/shared_fd.h"
32 #include "common/libs/utils/environment.h"
33 #include "common/libs/utils/files.h"
34 #include "common/libs/utils/size_utils.h"
35 #include "common/libs/utils/subprocess.h"
36 #include "common/libs/utils/tee_logging.h"
37 #include "host/commands/run_cvd/boot_state_machine.h"
38 #include "host/commands/run_cvd/launch/launch.h"
39 #include "host/commands/run_cvd/reporting.h"
40 #include "host/commands/run_cvd/server_loop.h"
41 #include "host/commands/run_cvd/validate.h"
42 #include "host/libs/command_util/runner/defs.h"
43 #include "host/libs/config/adb/adb.h"
44 #include "host/libs/config/config_flag.h"
45 #include "host/libs/config/config_fragment.h"
46 #include "host/libs/config/custom_actions.h"
47 #include "host/libs/config/cuttlefish_config.h"
48 #include "host/libs/config/fastboot/fastboot.h"
49 #include "host/libs/config/inject.h"
50 #include "host/libs/metrics/metrics_receiver.h"
51 #include "host/libs/process_monitor/process_monitor.h"
52 #include "host/libs/vm_manager/vm_manager.h"
53
54 namespace cuttlefish {
55
56 namespace {
57
58 class CuttlefishEnvironment : public DiagnosticInformation {
59 public:
INJECT(CuttlefishEnvironment (const CuttlefishConfig::InstanceSpecific & instance))60 INJECT(
61 CuttlefishEnvironment(const CuttlefishConfig::InstanceSpecific& instance))
62 : instance_(instance) {}
63
64 // DiagnosticInformation
Diagnostics() const65 std::vector<std::string> Diagnostics() const override {
66 auto config_path = instance_.PerInstancePath("cuttlefish_config.json");
67 return {
68 "Launcher log: " + instance_.launcher_log_path(),
69 "Instance configuration: " + config_path,
70 // TODO(rammuthiah) replace this with a more thorough cvd host package
71 // version scheme. Currently this only reports the Build NUmber of run_cvd
72 // and it is possible for other host binaries to be from different versions.
73 "Launcher Build ID: " + android::build::GetBuildNumber(),
74 };
75 }
76
77 private:
78 const CuttlefishConfig::InstanceSpecific& instance_;
79 };
80
81 class InstanceLifecycle : public LateInjected {
82 public:
INJECT(InstanceLifecycle (const CuttlefishConfig & config,ServerLoop & server_loop))83 INJECT(InstanceLifecycle(const CuttlefishConfig& config,
84 ServerLoop& server_loop))
85 : config_(config), server_loop_(server_loop) {}
86
LateInject(fruit::Injector<> & injector)87 Result<void> LateInject(fruit::Injector<>& injector) override {
88 config_fragments_ = injector.getMultibindings<ConfigFragment>();
89 setup_features_ = injector.getMultibindings<SetupFeature>();
90 diagnostics_ = injector.getMultibindings<DiagnosticInformation>();
91 return {};
92 }
93
Run()94 Result<void> Run() {
95 for (auto& fragment : config_fragments_) {
96 CF_EXPECT(config_.LoadFragment(*fragment));
97 }
98
99 // One of the setup features can consume most output, so print this early.
100 DiagnosticInformation::PrintAll(diagnostics_);
101
102 CF_EXPECT(SetupFeature::RunSetup(setup_features_));
103
104 CF_EXPECT(server_loop_.Run());
105
106 return {};
107 }
108
109 private:
110 const CuttlefishConfig& config_;
111 ServerLoop& server_loop_;
112 std::vector<ConfigFragment*> config_fragments_;
113 std::vector<SetupFeature*> setup_features_;
114 std::vector<DiagnosticInformation*> diagnostics_;
115 };
116
runCvdComponent(const CuttlefishConfig * config,const CuttlefishConfig::EnvironmentSpecific * environment,const CuttlefishConfig::InstanceSpecific * instance)117 fruit::Component<> runCvdComponent(
118 const CuttlefishConfig* config,
119 const CuttlefishConfig::EnvironmentSpecific* environment,
120 const CuttlefishConfig::InstanceSpecific* instance) {
121 // WARNING: The install order indirectly controls the order that processes
122 // are started and stopped. The start order shouldn't matter, but if the stop
123 // order is inccorect, then some processes may crash on shutdown. For
124 // example, vhost-user processes must be stopped *after* VMM processes (so,
125 // sort vhost-user before VMM in this list).
126 return fruit::createComponent()
127 .addMultibinding<DiagnosticInformation, CuttlefishEnvironment>()
128 .addMultibinding<InstanceLifecycle, InstanceLifecycle>()
129 .addMultibinding<LateInjected, InstanceLifecycle>()
130 .bindInstance(*config)
131 .bindInstance(*instance)
132 .bindInstance(*environment)
133 #ifdef __linux__
134 .install(AutoCmd<AutomotiveProxyService>::Component)
135 .install(AutoCmd<ModemSimulator>::Component)
136 .install(AutoCmd<TombstoneReceiver>::Component)
137 .install(McuComponent)
138 .install(VhostDeviceVsockComponent)
139 .install(WmediumdServerComponent)
140 .install(launchStreamerComponent)
141 .install(AutoCmd<VhalProxyServer>::Component)
142 #endif
143 .install(AdbConfigComponent)
144 .install(AdbConfigFragmentComponent)
145 .install(FastbootConfigComponent)
146 .install(FastbootConfigFragmentComponent)
147 .install(bootStateMachineComponent)
148 .install(AutoCmd<CasimirControlServer>::Component)
149 .install(AutoCmd<ScreenRecordingServer>::Component)
150 .install(ConfigFlagPlaceholder)
151 .install(CustomActionsComponent)
152 .install(LaunchAdbComponent)
153 .install(LaunchFastbootComponent)
154 .install(AutoCmd<BluetoothConnector>::Component)
155 .install(AutoCmd<NfcConnector>::Component)
156 .install(AutoCmd<UwbConnector>::Component)
157 .install(AutoCmd<ConsoleForwarder>::Component)
158 .install(AutoDiagnostic<ConsoleInfo>::Component)
159 .install(ControlEnvProxyServerComponent)
160 .install(AutoCmd<EchoServer>::Component)
161 .install(AutoCmd<GnssGrpcProxyServer>::Component)
162 .install(AutoCmd<LogcatReceiver>::Component)
163 .install(AutoDiagnostic<LogcatInfo>::Component)
164 .install(KernelLogMonitorComponent)
165 .install(AutoCmd<MetricsService>::Component)
166 .install(OpenwrtControlServerComponent)
167 .install(AutoCmd<Pica>::Component)
168 .install(RootCanalComponent)
169 .install(AutoCmd<Casimir>::Component)
170 .install(NetsimServerComponent)
171 .install(AutoSnapshotControlFiles::Component)
172 .install(AutoCmd<SecureEnv>::Component)
173 .install(serverLoopComponent)
174 .install(WebRtcControllerComponent)
175 .install(AutoSetup<ValidateTapDevices>::Component)
176 .install(AutoSetup<ValidateHostConfiguration>::Component)
177 .install(AutoSetup<ValidateHostKernel>::Component)
178 #ifdef __linux__
179 // OpenWrtComponent spawns a VMM and so has similar install order
180 // requirements to VmManagerComponent.
181 .install(OpenWrtComponent)
182 #endif
183 .install(vm_manager::VmManagerComponent);
184 }
185
StdinValid()186 Result<void> StdinValid() {
187 CF_EXPECT(!isatty(0),
188 "stdin was a tty, expected to be passed the output of a"
189 " previous stage. Did you mean to run launch_cvd?");
190 CF_EXPECT(errno != EBADF,
191 "stdin was not a valid file descriptor, expected to be passed the "
192 "output of assemble_cvd. Did you mean to run launch_cvd?");
193 return {};
194 }
195
ConfigureLogs(const CuttlefishConfig & config,const CuttlefishConfig::InstanceSpecific & instance)196 void ConfigureLogs(const CuttlefishConfig& config,
197 const CuttlefishConfig::InstanceSpecific& instance) {
198 auto log_path = instance.launcher_log_path();
199
200 if (!FileHasContent(log_path)) {
201 std::ofstream launcher_log_ofstream(log_path.c_str());
202 auto assembly_path = config.AssemblyPath("assemble_cvd.log");
203 std::ifstream assembly_log_ifstream(assembly_path);
204 if (assembly_log_ifstream) {
205 auto assemble_log = ReadFile(assembly_path);
206 launcher_log_ofstream << assemble_log;
207 }
208 }
209 std::string prefix;
210 if (config.Instances().size() > 1) {
211 prefix = instance.instance_name() + ": ";
212 }
213 ::android::base::SetLogger(LogToStderrAndFiles({log_path}, prefix));
214 }
215
216 } // namespace
217
RunCvdMain(int argc,char ** argv)218 Result<void> RunCvdMain(int argc, char** argv) {
219 setenv("ANDROID_LOG_TAGS", "*:v", /* overwrite */ 0);
220 ::android::base::InitLogging(argv, android::base::StderrLogger);
221 google::ParseCommandLineFlags(&argc, &argv, false);
222
223 CF_EXPECT(StdinValid(), "Invalid stdin");
224 auto config = CF_EXPECT(CuttlefishConfig::Get());
225 auto environment = config->ForDefaultEnvironment();
226 auto instance = config->ForDefaultInstance();
227 ConfigureLogs(*config, instance);
228
229 fruit::Injector<> injector(runCvdComponent, config, &environment, &instance);
230
231 for (auto& late_injected : injector.getMultibindings<LateInjected>()) {
232 CF_EXPECT(late_injected->LateInject(injector));
233 }
234
235 if (config->enable_metrics() == cuttlefish::CuttlefishConfig::Answer::kYes) {
236 MetricsReceiver::LogMetricsVMStart();
237 }
238
239 auto instance_bindings = injector.getMultibindings<InstanceLifecycle>();
240 CF_EXPECT(instance_bindings.size() == 1);
241 CF_EXPECT(instance_bindings[0]->Run()); // Should not return
242
243 return CF_ERR("The server loop returned, it should never happen!!");
244 }
245
246 } // namespace cuttlefish
247
main(int argc,char ** argv)248 int main(int argc, char** argv) {
249 auto result = cuttlefish::RunCvdMain(argc, argv);
250 if (result.ok()) {
251 return 0;
252 }
253 LOG(ERROR) << result.error().FormatForEnv();
254 abort();
255 }
256