1 /*
2  * Copyright (C) 2021 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 <cstdint>
18 #include <cstdlib>
19 #include <iostream>
20 
21 #include <android-base/logging.h>
22 #include <gflags/gflags.h>
23 
24 #include "common/libs/fs/shared_fd.h"
25 #include "common/libs/utils/result.h"
26 #include "host/libs/command_util/runner/defs.h"
27 #include "host/libs/command_util/util.h"
28 #include "host/libs/config/cuttlefish_config.h"
29 
30 DEFINE_int32(instance_num, cuttlefish::GetInstance(),
31              "Which instance to restart.");
32 
33 DEFINE_int32(
34     wait_for_launcher, 30,
35     "How many seconds to wait for the launcher to respond to the status "
36     "command. A value of zero means wait indefinitely.");
37 
38 DEFINE_int32(boot_timeout, 1000, "How many seconds to wait for the device to "
39                                  "reboot.");
40 
41 namespace cuttlefish {
42 namespace {
43 
RestartCvdMain()44 Result<void> RestartCvdMain() {
45   const CuttlefishConfig* config =
46       CF_EXPECT(CuttlefishConfig::Get(), "Failed to obtain config object");
47   SharedFD monitor_socket = CF_EXPECT(
48       GetLauncherMonitor(*config, FLAGS_instance_num, FLAGS_wait_for_launcher));
49 
50   LOG(INFO) << "Requesting restart";
51   CF_EXPECT(RunLauncherAction(monitor_socket, LauncherAction::kRestart,
52                               FLAGS_wait_for_launcher));
53 
54   LOG(INFO) << "Waiting for device to boot up again";
55   CF_EXPECT(WaitForRead(monitor_socket, FLAGS_boot_timeout));
56   RunnerExitCodes boot_exit_code = CF_EXPECT(ReadExitCode(monitor_socket));
57   CF_EXPECT(boot_exit_code != RunnerExitCodes::kVirtualDeviceBootFailed,
58             "Boot failed");
59   CF_EXPECT(boot_exit_code == RunnerExitCodes::kSuccess,
60             "Unknown response" << static_cast<int>(boot_exit_code));
61 
62   LOG(INFO) << "Restart successful";
63   return {};
64 }
65 
66 } // namespace
67 } // namespace cuttlefish
68 
main(int argc,char ** argv)69 int main(int argc, char** argv) {
70   ::android::base::InitLogging(argv, android::base::StderrLogger);
71   google::ParseCommandLineFlags(&argc, &argv, true);
72 
73   cuttlefish::Result<void> result = cuttlefish::RestartCvdMain();
74 
75   if (!result.ok()) {
76     LOG(ERROR) << result.error().FormatForEnv();
77     return EXIT_FAILURE;
78   }
79   return EXIT_SUCCESS;
80 }
81