• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 "DumpstateDevice.h"
18 
19 #include <DumpstateUtil.h>
20 #include <android-base/file.h>
21 #include <android-base/logging.h>
22 #include <android-base/properties.h>
23 
24 #include <fstream>
25 #include <string>
26 
27 using android::base::GetProperty;
28 using android::os::dumpstate::CommandOptions;
29 using android::os::dumpstate::DumpFileToFd;
30 using std::chrono::duration_cast;
31 using std::chrono::seconds;
32 using std::literals::chrono_literals::operator""s;
33 
34 namespace fs = android::hardware::automotive::filesystem;
35 
36 static constexpr const char* VENDOR_VERBOSE_LOGGING_ENABLED_PROPERTY =
37         "persist.vendor.verbose_logging_enabled";
38 
39 static constexpr const char* VENDOR_HELPER_SYSTEM_LOG_LOC_PROPERTY =
40         "ro.vendor.helpersystem.log_loc";
41 
42 static constexpr const char* BOOT_HYPERVISOR_VERSION_PROPERTY =
43         "ro.boot.hypervisor.version";
44 
45 namespace aidl::android::hardware::dumpstate::implementation {
46 
getChannelCredentials()47 static std::shared_ptr<::grpc::ChannelCredentials> getChannelCredentials() {
48     // TODO(chenhaosjtuacm): get secured credentials here
49     return ::grpc::InsecureChannelCredentials();
50 }
51 
dumpDirAsText(int textFd,const fs::path & dirToDump)52 static void dumpDirAsText(int textFd, const fs::path& dirToDump) {
53     for (const auto& fileEntry : fs::recursive_directory_iterator(dirToDump)) {
54         if (!fileEntry.is_regular_file()) {
55             continue;
56         }
57 
58         DumpFileToFd(textFd, "Helper System Log", fileEntry.path());
59     }
60 }
61 
tryDumpDirAsTar(int textFd,int binFd,const fs::path & dirToDump)62 static void tryDumpDirAsTar(int textFd, int binFd, const fs::path& dirToDump) {
63     if (!fs::is_directory(dirToDump)) {
64         LOG(ERROR) << "'" << dirToDump << "'"
65                    << " is not a valid directory to dump";
66         return;
67     }
68 
69     if (binFd < 0) {
70         LOG(WARNING) << "No binary dumped file, fallback to text mode";
71         return dumpDirAsText(textFd, dirToDump);
72     }
73 
74     TemporaryFile tempTarFile;
75     constexpr auto kTarTimeout = 20s;
76 
77     RunCommandToFd(
78             textFd, "TAR LOG", {"/vendor/bin/tar", "cvf", tempTarFile.path, dirToDump.c_str()},
79             CommandOptions::WithTimeout(duration_cast<seconds>(kTarTimeout).count()).Build());
80 
81     std::vector<uint8_t> buffer(65536);
82     while (true) {
83         ssize_t bytes_read = TEMP_FAILURE_RETRY(read(tempTarFile.fd, buffer.data(), buffer.size()));
84 
85         if (bytes_read == 0) {
86             break;
87         } else if (bytes_read < 0) {
88             PLOG(DEBUG) << "Error reading temporary tar file(" << tempTarFile.path << ")";
89             break;
90         }
91 
92         ssize_t result = TEMP_FAILURE_RETRY(write(binFd, buffer.data(), bytes_read));
93 
94         if (result != bytes_read) {
95             LOG(DEBUG) << "Failed to write " << bytes_read
96                        << " bytes, actually written: " << result;
97             break;
98         }
99     }
100 }
101 
dumpRemoteLogs(::grpc::ClientReaderInterface<dumpstate_proto::DumpstateBuffer> * grpcReader,const fs::path & dumpPath)102 bool DumpstateDevice::dumpRemoteLogs(
103         ::grpc::ClientReaderInterface<dumpstate_proto::DumpstateBuffer>* grpcReader,
104         const fs::path& dumpPath) {
105     dumpstate_proto::DumpstateBuffer logStreamBuffer;
106     std::fstream logFile(dumpPath, std::fstream::out | std::fstream::binary);
107 
108     if (!logFile.is_open()) {
109         LOG(ERROR) << "Failed to open file " << dumpPath;
110         return false;
111     }
112 
113     while (grpcReader->Read(&logStreamBuffer)) {
114         const auto& writeBuffer = logStreamBuffer.buffer();
115         logFile.write(writeBuffer.c_str(), writeBuffer.size());
116     }
117     auto grpcStatus = grpcReader->Finish();
118     if (!grpcStatus.ok()) {
119         LOG(ERROR) << __func__ << ": GRPC GetCommandOutput Failed: " << grpcStatus.error_message();
120         return false;
121     }
122 
123     return true;
124 }
125 
dumpString(const std::string & text,const fs::path & dumpPath)126 bool DumpstateDevice::dumpString(const std::string& text, const fs::path& dumpPath) {
127     std::fstream logFile(dumpPath, std::fstream::out | std::fstream::binary);
128 
129     if (!logFile.is_open()) {
130         LOG(ERROR) << "Failed to open file " << dumpPath;
131         return false;
132     }
133 
134     logFile.write(text.c_str(), text.size());
135 
136     return true;
137 }
138 
dumpHelperSystem(int textFd,int binFd)139 bool DumpstateDevice::dumpHelperSystem(int textFd, int binFd) {
140     std::string helperSystemLogDir =
141             ::android::base::GetProperty(VENDOR_HELPER_SYSTEM_LOG_LOC_PROPERTY, "");
142 
143     if (helperSystemLogDir.empty()) {
144         LOG(ERROR) << "Helper system log location '" << VENDOR_HELPER_SYSTEM_LOG_LOC_PROPERTY
145                    << "' not set";
146         return false;
147     }
148 
149     std::error_code error;
150 
151     auto helperSysLogPath = fs::path(helperSystemLogDir);
152     if (!fs::create_directories(helperSysLogPath, error)) {
153         LOG(ERROR) << "Failed to create the dumping log directory " << helperSystemLogDir << ": "
154                    << error;
155         return false;
156     }
157 
158     if (!fs::is_directory(helperSysLogPath)) {
159         LOG(ERROR) << helperSystemLogDir << " is not a directory";
160         return false;
161     }
162 
163     if (!isHealthy()) {
164         LOG(ERROR) << "Failed to connect to the dumpstate server";
165         return false;
166     }
167 
168     // When start dumping, we always return success to keep dumped logs
169     // even if some of them are failed
170 
171     {
172         // Dumping system logs
173         ::grpc::ClientContext context;
174         auto reader = mGrpcStub->GetSystemLogs(&context, ::google::protobuf::Empty());
175         dumpRemoteLogs(reader.get(), helperSysLogPath / "system_log");
176     }
177 
178     {
179         // Dumping host system info
180         const std::string hyp =
181                 "Host version information: " +
182                 GetProperty(BOOT_HYPERVISOR_VERSION_PROPERTY, "missing/unavailable");
183         dumpString(hyp, helperSysLogPath / "host_info");
184     }
185 
186     // Request for service list every time to allow the service list to change on the server side.
187     // Also the getAvailableServices() may fail and return an empty list (e.g., failure on the
188     // server side), and it should not affect the future queries
189     const auto availableServices = getAvailableServices();
190 
191     // Dumping service logs
192     for (const auto& service : availableServices) {
193         ::grpc::ClientContext context;
194         dumpstate_proto::ServiceLogRequest request;
195         request.set_service_name(service);
196         auto reader = mGrpcStub->GetServiceLogs(&context, request);
197         dumpRemoteLogs(reader.get(), helperSysLogPath / service);
198     }
199 
200     tryDumpDirAsTar(textFd, binFd, helperSystemLogDir);
201 
202     if (fs::remove_all(helperSysLogPath, error) == static_cast<std::uintmax_t>(-1)) {
203         LOG(ERROR) << "Failed to clear the dumping log directory " << helperSystemLogDir << ": "
204                    << error;
205     }
206     return true;
207 }
208 
isHealthy()209 bool DumpstateDevice::isHealthy() {
210     // Check that we can get services back from the remote end
211     // This check will not work if the server actually works but is
212     // not exporting any services. This seems like a corner case
213     // but it's worth pointing out.
214     return (getAvailableServices().size() > 0);
215 }
216 
getAvailableServices()217 std::vector<std::string> DumpstateDevice::getAvailableServices() {
218     ::grpc::ClientContext context;
219     dumpstate_proto::ServiceNameList servicesProto;
220     auto grpc_status =
221             mGrpcStub->GetAvailableServices(&context, ::google::protobuf::Empty(), &servicesProto);
222     if (!grpc_status.ok()) {
223         LOG(ERROR) << "Failed to get available services from the server: "
224                    << grpc_status.error_message();
225         return {};
226     }
227 
228     std::vector<std::string> services;
229     for (auto& service : servicesProto.service_names()) {
230         services.emplace_back(service);
231     }
232     return services;
233 }
234 
DumpstateDevice(const std::string & addr)235 DumpstateDevice::DumpstateDevice(const std::string& addr)
236     : mServiceAddr(addr),
237       mGrpcChannel(::grpc::CreateChannel(mServiceAddr, getChannelCredentials())),
238       mGrpcStub(dumpstate_proto::DumpstateServer::NewStub(mGrpcChannel)) {}
239 
dumpstateBoard(const std::vector<::ndk::ScopedFileDescriptor> & in_fds,IDumpstateDevice::DumpstateMode in_mode,int64_t in_timeoutMillis)240 ::ndk::ScopedAStatus DumpstateDevice::dumpstateBoard(
241         const std::vector<::ndk::ScopedFileDescriptor>& in_fds,
242         IDumpstateDevice::DumpstateMode in_mode, int64_t in_timeoutMillis) {
243     if (in_fds.size() < 1) {
244         return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT,
245                                                                 "No file descriptor");
246     }
247 
248     const int textFd = in_fds[0].get();
249     const int binFd = in_fds.size() >= 2 ? in_fds[1].get() : -1;
250 
251     if (!dumpHelperSystem(textFd, binFd)) {
252         // TODO(egranata,chenhaosjtuacm): provide more helpful info here
253         return ndk::ScopedAStatus::fromExceptionCodeWithMessage(
254                 EX_UNSUPPORTED_OPERATION, "Host system unable to gather required logs");
255     }
256 
257     return ndk::ScopedAStatus::ok();
258 }
259 
getVerboseLoggingEnabled(bool * _aidl_return)260 ::ndk::ScopedAStatus DumpstateDevice::getVerboseLoggingEnabled(bool* _aidl_return) {
261     if (_aidl_return)
262         *_aidl_return =
263                 ::android::base::GetBoolProperty(VENDOR_VERBOSE_LOGGING_ENABLED_PROPERTY, false);
264     return ndk::ScopedAStatus::ok();
265 }
266 
setVerboseLoggingEnabled(bool in_enable)267 ::ndk::ScopedAStatus DumpstateDevice::setVerboseLoggingEnabled(bool in_enable) {
268     ::android::base::SetProperty(VENDOR_VERBOSE_LOGGING_ENABLED_PROPERTY,
269                                  in_enable ? "true" : "false");
270     return ndk::ScopedAStatus::ok();
271 }
272 
273 }  // namespace aidl::android::hardware::dumpstate::implementation
274