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 void 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;
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;
139 }
140
141 if (!fs::is_directory(helperSysLogPath)) {
142 LOG(ERROR) << helperSystemLogDir << " is not a directory";
143 return;
144 }
145
146 {
147 // Dumping system logs
148 ::grpc::ClientContext context;
149 auto reader = mGrpcStub->GetSystemLogs(&context, ::google::protobuf::Empty());
150 dumpRemoteLogs(reader.get(), helperSysLogPath / "system_log");
151 }
152
153 // Request for service list every time to allow the service list to change on the server side.
154 // Also the getAvailableServices() may fail and return an empty list (e.g., failure on the
155 // server side), and it should not affect the future queries
156 const auto availableServices = getAvailableServices();
157
158 // Dumping service logs
159 for (const auto& service : availableServices) {
160 ::grpc::ClientContext context;
161 dumpstate_proto::ServiceLogRequest request;
162 request.set_service_name(service);
163 auto reader = mGrpcStub->GetServiceLogs(&context, request);
164 dumpRemoteLogs(reader.get(), helperSysLogPath / service);
165 }
166
167 tryDumpDirAsTar(textFd, binFd, helperSystemLogDir);
168
169 if (fs::remove_all(helperSysLogPath, error) == static_cast<std::uintmax_t>(-1)) {
170 LOG(ERROR) << "Failed to clear the dumping log directory " << helperSystemLogDir << ": "
171 << error;
172 }
173 }
174
isHealthy()175 bool DumpstateDevice::isHealthy() {
176 // Check that we can get services back from the remote end
177 // This check will not work if the server actually works but is
178 // not exporting any services. This seems like a corner case
179 // but it's worth pointing out.
180 return (getAvailableServices().size() > 0);
181 }
182
getAvailableServices()183 std::vector<std::string> DumpstateDevice::getAvailableServices() {
184 ::grpc::ClientContext context;
185 dumpstate_proto::ServiceNameList servicesProto;
186 auto grpc_status =
187 mGrpcStub->GetAvailableServices(&context, ::google::protobuf::Empty(), &servicesProto);
188 if (!grpc_status.ok()) {
189 LOG(ERROR) << "Failed to get available services from the server: "
190 << grpc_status.error_message();
191 return {};
192 }
193
194 std::vector<std::string> services;
195 for (auto& service : servicesProto.service_names()) {
196 services.emplace_back(service);
197 }
198 return services;
199 }
200
DumpstateDevice(const std::string & addr)201 DumpstateDevice::DumpstateDevice(const std::string& addr)
202 : mServiceAddr(addr),
203 mGrpcChannel(::grpc::CreateChannel(mServiceAddr, getChannelCredentials())),
204 mGrpcStub(dumpstate_proto::DumpstateServer::NewStub(mGrpcChannel)) {}
205
206 // Methods from ::android::hardware::dumpstate::V1_0::IDumpstateDevice follow.
dumpstateBoard(const hidl_handle & handle)207 Return<void> DumpstateDevice::dumpstateBoard(const hidl_handle& handle) {
208 // Ignore return value, just return an empty status.
209 dumpstateBoard_1_1(handle, DumpstateMode::DEFAULT, 30 * 1000 /* timeoutMillis */);
210 return Void();
211 }
212
213 // Methods from ::android::hardware::dumpstate::V1_1::IDumpstateDevice follow.
dumpstateBoard_1_1(const hidl_handle & handle,const DumpstateMode,const uint64_t)214 Return<DumpstateStatus> DumpstateDevice::dumpstateBoard_1_1(const hidl_handle& handle,
215 const DumpstateMode /* mode */,
216 const uint64_t /* timeoutMillis */) {
217 if (handle == nullptr || handle->numFds < 1) {
218 LOG(ERROR) << "No FDs";
219 return DumpstateStatus::ILLEGAL_ARGUMENT;
220 }
221
222 const int textFd = handle->data[0];
223 const int binFd = handle->numFds >= 2 ? handle->data[1] : -1;
224
225 dumpHelperSystem(textFd, binFd);
226
227 return DumpstateStatus::OK;
228 }
229
setVerboseLoggingEnabled(const bool enable)230 Return<void> DumpstateDevice::setVerboseLoggingEnabled(const bool enable) {
231 android::base::SetProperty(VENDOR_VERBOSE_LOGGING_ENABLED_PROPERTY, enable ? "true" : "false");
232 return Void();
233 }
234
getVerboseLoggingEnabled()235 Return<bool> DumpstateDevice::getVerboseLoggingEnabled() {
236 return android::base::GetBoolProperty(VENDOR_VERBOSE_LOGGING_ENABLED_PROPERTY, false);
237 }
238
makeVirtualizationDumpstateDevice(const std::string & addr)239 sp<DumpstateDevice> makeVirtualizationDumpstateDevice(const std::string& addr) {
240 return new DumpstateDevice(addr);
241 }
242
243 } // namespace android::hardware::dumpstate::V1_1::implementation
244