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