blob: 7721bf404abeefedc3f295519ab9c8f0fb390e26 [file] [log] [blame]
Yu Shan7a5283f2022-10-25 18:01:05 -07001/*
2 * Copyright (C) 2022 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 "RemoteAccessService.h"
18
19#include <VehicleUtils.h>
20#include <aidl/android/hardware/automotive/vehicle/VehicleProperty.h>
Yu Shan194757d2023-04-19 11:44:35 -070021#include <android-base/parseint.h>
Yu Shan7a5283f2022-10-25 18:01:05 -070022#include <android-base/stringprintf.h>
23#include <android/binder_status.h>
24#include <grpc++/grpc++.h>
25#include <private/android_filesystem_config.h>
Yu Shan194757d2023-04-19 11:44:35 -070026#include <sys/stat.h>
Yu Shan7a5283f2022-10-25 18:01:05 -070027#include <utils/Log.h>
28#include <chrono>
Yu Shan194757d2023-04-19 11:44:35 -070029#include <fstream>
30#include <iostream>
Yu Shan7a5283f2022-10-25 18:01:05 -070031#include <thread>
32
33namespace android {
34namespace hardware {
35namespace automotive {
36namespace remoteaccess {
37
38namespace {
39
40using ::aidl::android::hardware::automotive::remoteaccess::ApState;
41using ::aidl::android::hardware::automotive::remoteaccess::IRemoteTaskCallback;
Yu Shan06ddbc62023-08-23 18:05:26 -070042using ::aidl::android::hardware::automotive::remoteaccess::ScheduleInfo;
Yu Shan7a5283f2022-10-25 18:01:05 -070043using ::aidl::android::hardware::automotive::vehicle::VehicleProperty;
Yu Shan95493682023-03-21 18:00:17 -070044using ::android::base::Error;
Yu Shan194757d2023-04-19 11:44:35 -070045using ::android::base::ParseInt;
Yu Shan95493682023-03-21 18:00:17 -070046using ::android::base::Result;
Yu Shan7a5283f2022-10-25 18:01:05 -070047using ::android::base::ScopedLockAssertion;
48using ::android::base::StringAppendF;
49using ::android::base::StringPrintf;
50using ::android::frameworks::automotive::vhal::IVhalClient;
51using ::android::hardware::automotive::vehicle::toInt;
52using ::grpc::ClientContext;
53using ::grpc::ClientReaderInterface;
54using ::grpc::Status;
55using ::grpc::StatusCode;
56using ::ndk::ScopedAStatus;
57
58const std::string WAKEUP_SERVICE_NAME = "com.google.vehicle.wakeup";
Eric Jeong6c3a1d82023-03-16 00:45:40 -070059const std::string PROCESSOR_ID = "application_processor";
Yu Shan7a5283f2022-10-25 18:01:05 -070060constexpr char COMMAND_SET_AP_STATE[] = "--set-ap-state";
61constexpr char COMMAND_START_DEBUG_CALLBACK[] = "--start-debug-callback";
62constexpr char COMMAND_STOP_DEBUG_CALLBACK[] = "--stop-debug-callback";
63constexpr char COMMAND_SHOW_TASK[] = "--show-task";
Eric Jeong6c3a1d82023-03-16 00:45:40 -070064constexpr char COMMAND_GET_VEHICLE_ID[] = "--get-vehicle-id";
Yu Shan95493682023-03-21 18:00:17 -070065constexpr char COMMAND_INJECT_TASK[] = "--inject-task";
Yu Shan194757d2023-04-19 11:44:35 -070066constexpr char COMMAND_INJECT_TASK_NEXT_REBOOT[] = "--inject-task-next-reboot";
Yu Shan95493682023-03-21 18:00:17 -070067constexpr char COMMAND_STATUS[] = "--status";
Yu Shan7a5283f2022-10-25 18:01:05 -070068
Yu Shan58ff0912023-05-12 18:00:59 -070069constexpr char DEBUG_TASK_FILE[] = "/data/vendor/remoteaccess/debugTask";
Yu Shan194757d2023-04-19 11:44:35 -070070
Yu Shan95493682023-03-21 18:00:17 -070071std::vector<uint8_t> stringToBytes(std::string_view s) {
Yu Shan7a5283f2022-10-25 18:01:05 -070072 const char* data = s.data();
73 return std::vector<uint8_t>(data, data + s.size());
74}
75
76ScopedAStatus rpcStatusToScopedAStatus(const Status& status, const std::string& errorMsg) {
77 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
78 status.error_code(), (errorMsg + ", error: " + status.error_message()).c_str());
79}
80
81std::string printBytes(const std::vector<uint8_t>& bytes) {
82 std::string s;
83 for (size_t i = 0; i < bytes.size(); i++) {
84 StringAppendF(&s, "%02x", bytes[i]);
85 }
86 return s;
87}
88
89bool checkBoolFlag(const char* flag) {
90 return !strcmp(flag, "1") || !strcmp(flag, "0");
91}
92
93void dprintErrorStatus(int fd, const char* detail, const ScopedAStatus& status) {
94 dprintf(fd, "%s, code: %d, error: %s\n", detail, status.getStatus(), status.getMessage());
95}
96
Yu Shan95493682023-03-21 18:00:17 -070097std::string boolToString(bool x) {
98 return x ? "true" : "false";
99}
100
Yu Shan7a5283f2022-10-25 18:01:05 -0700101} // namespace
102
103RemoteAccessService::RemoteAccessService(WakeupClient::StubInterface* grpcStub)
Yu Shan194757d2023-04-19 11:44:35 -0700104 : mGrpcStub(grpcStub) {
105 std::ifstream debugTaskFile;
106 debugTaskFile.open(DEBUG_TASK_FILE, std::ios::in);
107 if (!debugTaskFile.is_open()) {
108 ALOGD("No debug task available");
109 return;
110 }
111
112 char buffer[1024] = {};
113 debugTaskFile.getline(buffer, sizeof(buffer));
114 std::string clientId = std::string(buffer);
115 debugTaskFile.getline(buffer, sizeof(buffer));
116 std::string taskData = std::string(buffer);
117 int latencyInSec;
118 debugTaskFile >> latencyInSec;
119 debugTaskFile.close();
120
121 ALOGD("Task for client: %s, data: [%s], latency: %d\n", clientId.c_str(), taskData.c_str(),
122 latencyInSec);
123
124 mInjectDebugTaskThread = std::thread([this, clientId, taskData, latencyInSec] {
125 std::this_thread::sleep_for(std::chrono::seconds(latencyInSec));
126 if (auto result = deliverRemoteTaskThroughCallback(clientId, taskData); !result.ok()) {
127 ALOGE("Failed to inject debug task, clientID: %s, taskData: %s, error: %s",
128 clientId.c_str(), taskData.c_str(), result.error().message().c_str());
129 return;
130 }
131 ALOGD("Task for client: %s, data: [%s] successfully injected\n", clientId.c_str(),
132 taskData.c_str());
133 });
134}
Yu Shan7a5283f2022-10-25 18:01:05 -0700135
136RemoteAccessService::~RemoteAccessService() {
137 maybeStopTaskLoop();
Yu Shan194757d2023-04-19 11:44:35 -0700138 if (mInjectDebugTaskThread.joinable()) {
139 mInjectDebugTaskThread.join();
140 }
Yu Shan7a5283f2022-10-25 18:01:05 -0700141}
142
143void RemoteAccessService::maybeStartTaskLoop() {
144 std::lock_guard<std::mutex> lockGuard(mStartStopTaskLoopLock);
145 if (mTaskLoopRunning) {
146 return;
147 }
148
149 mThread = std::thread([this]() { runTaskLoop(); });
150
151 mTaskLoopRunning = true;
152}
153
154void RemoteAccessService::maybeStopTaskLoop() {
155 std::lock_guard<std::mutex> lockGuard(mStartStopTaskLoopLock);
156 if (!mTaskLoopRunning) {
157 return;
158 }
159
160 {
161 std::lock_guard<std::mutex> lockGuard(mLock);
162 // Try to stop the reading stream.
163 if (mGetRemoteTasksContext) {
164 mGetRemoteTasksContext->TryCancel();
Yu Shandf39d6e2022-12-02 17:01:57 -0800165 // Don't reset mGetRemoteTaskContext here since the read stream might still be affective
166 // and might still be using it. This will cause reader->Read to return false and
167 // mGetRemoteTasksContext will be cleared after reader->Finish() is called.
Yu Shan7a5283f2022-10-25 18:01:05 -0700168 }
169 mTaskWaitStopped = true;
170 mCv.notify_all();
171 }
172 if (mThread.joinable()) {
173 mThread.join();
174 }
175
176 mTaskLoopRunning = false;
177}
178
Yu Shan95493682023-03-21 18:00:17 -0700179void RemoteAccessService::updateGrpcConnected(bool connected) {
180 std::lock_guard<std::mutex> lockGuard(mLock);
181 mGrpcConnected = connected;
182}
183
184Result<void> RemoteAccessService::deliverRemoteTaskThroughCallback(const std::string& clientId,
185 std::string_view taskData) {
186 std::shared_ptr<IRemoteTaskCallback> callback;
187 {
188 std::lock_guard<std::mutex> lockGuard(mLock);
189 callback = mRemoteTaskCallback;
190 mClientIdToTaskCount[clientId] += 1;
191 }
192 if (callback == nullptr) {
193 return Error() << "No callback registered, task ignored";
194 }
195 ALOGD("Calling onRemoteTaskRequested callback for client ID: %s", clientId.c_str());
196 ScopedAStatus callbackStatus =
197 callback->onRemoteTaskRequested(clientId, stringToBytes(taskData));
198 if (!callbackStatus.isOk()) {
199 return Error() << "Failed to call onRemoteTaskRequested callback, status: "
200 << callbackStatus.getStatus()
201 << ", message: " << callbackStatus.getMessage();
202 }
203 return {};
204}
205
Yu Shan7a5283f2022-10-25 18:01:05 -0700206void RemoteAccessService::runTaskLoop() {
207 GetRemoteTasksRequest request = {};
208 std::unique_ptr<ClientReaderInterface<GetRemoteTasksResponse>> reader;
209 while (true) {
210 {
211 std::lock_guard<std::mutex> lockGuard(mLock);
212 mGetRemoteTasksContext.reset(new ClientContext());
213 reader = mGrpcStub->GetRemoteTasks(mGetRemoteTasksContext.get(), request);
214 }
Yu Shan95493682023-03-21 18:00:17 -0700215 updateGrpcConnected(true);
Yu Shan7a5283f2022-10-25 18:01:05 -0700216 GetRemoteTasksResponse response;
217 while (reader->Read(&response)) {
218 ALOGI("Receiving one task from remote task client");
219
Yu Shan95493682023-03-21 18:00:17 -0700220 if (auto result =
221 deliverRemoteTaskThroughCallback(response.clientid(), response.data());
222 !result.ok()) {
223 ALOGE("%s", result.error().message().c_str());
Yu Shan7a5283f2022-10-25 18:01:05 -0700224 continue;
225 }
Yu Shan7a5283f2022-10-25 18:01:05 -0700226 }
Yu Shan95493682023-03-21 18:00:17 -0700227 updateGrpcConnected(false);
Yu Shan7a5283f2022-10-25 18:01:05 -0700228 Status status = reader->Finish();
Yu Shandf39d6e2022-12-02 17:01:57 -0800229 mGetRemoteTasksContext.reset();
Yu Shan7a5283f2022-10-25 18:01:05 -0700230
231 ALOGE("GetRemoteTasks stream breaks, code: %d, message: %s, sleeping for 10s and retry",
232 status.error_code(), status.error_message().c_str());
233 // The long lasting connection should not return. But if the server returns, retry after
234 // 10s.
235 {
236 std::unique_lock lk(mLock);
237 if (mCv.wait_for(lk, std::chrono::milliseconds(mRetryWaitInMs), [this] {
238 ScopedLockAssertion lockAssertion(mLock);
239 return mTaskWaitStopped;
240 })) {
241 // If the stopped flag is set, we are quitting, exit the loop.
242 break;
243 }
244 }
245 }
246}
247
Eric Jeong6c3a1d82023-03-16 00:45:40 -0700248ScopedAStatus RemoteAccessService::getVehicleId(std::string* vehicleId) {
Yu Shan7a5283f2022-10-25 18:01:05 -0700249#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
250 auto vhalClient = IVhalClient::tryCreate();
251 if (vhalClient == nullptr) {
252 ALOGE("Failed to connect to VHAL");
253 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
Eric Jeong6c3a1d82023-03-16 00:45:40 -0700254 /*errorCode=*/0, "Failed to connect to VHAL to get vehicle ID");
Yu Shan7a5283f2022-10-25 18:01:05 -0700255 }
Eric Jeong6c3a1d82023-03-16 00:45:40 -0700256 return getVehicleIdWithClient(*vhalClient.get(), vehicleId);
Yu Shan7a5283f2022-10-25 18:01:05 -0700257#else
258 // Don't use VHAL client in fuzzing since IPC is not allowed.
259 return ScopedAStatus::ok();
260#endif
261}
262
Eric Jeong6c3a1d82023-03-16 00:45:40 -0700263ScopedAStatus RemoteAccessService::getVehicleIdWithClient(IVhalClient& vhalClient,
264 std::string* vehicleId) {
Yu Shan7a5283f2022-10-25 18:01:05 -0700265 auto result = vhalClient.getValueSync(
266 *vhalClient.createHalPropValue(toInt(VehicleProperty::INFO_VIN)));
267 if (!result.ok()) {
268 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
269 /*errorCode=*/0,
270 ("failed to get INFO_VIN from VHAL: " + result.error().message()).c_str());
271 }
Eric Jeong6c3a1d82023-03-16 00:45:40 -0700272 *vehicleId = (*result)->getStringValue();
273 return ScopedAStatus::ok();
274}
275
276ScopedAStatus RemoteAccessService::getProcessorId(std::string* processorId) {
277 *processorId = PROCESSOR_ID;
Yu Shan7a5283f2022-10-25 18:01:05 -0700278 return ScopedAStatus::ok();
279}
280
281ScopedAStatus RemoteAccessService::getWakeupServiceName(std::string* wakeupServiceName) {
282 *wakeupServiceName = WAKEUP_SERVICE_NAME;
283 return ScopedAStatus::ok();
284}
285
286ScopedAStatus RemoteAccessService::setRemoteTaskCallback(
287 const std::shared_ptr<IRemoteTaskCallback>& callback) {
288 std::lock_guard<std::mutex> lockGuard(mLock);
289 mRemoteTaskCallback = callback;
290 return ScopedAStatus::ok();
291}
292
293ScopedAStatus RemoteAccessService::clearRemoteTaskCallback() {
294 std::lock_guard<std::mutex> lockGuard(mLock);
295 mRemoteTaskCallback.reset();
296 return ScopedAStatus::ok();
297}
298
299ScopedAStatus RemoteAccessService::notifyApStateChange(const ApState& newState) {
300 ClientContext context;
301 NotifyWakeupRequiredRequest request = {};
302 request.set_iswakeuprequired(newState.isWakeupRequired);
303 NotifyWakeupRequiredResponse response = {};
304 Status status = mGrpcStub->NotifyWakeupRequired(&context, request, &response);
305 if (!status.ok()) {
306 return rpcStatusToScopedAStatus(status, "Failed to notify isWakeupRequired");
307 }
308
309 if (newState.isReadyForRemoteTask) {
310 maybeStartTaskLoop();
311 } else {
312 maybeStopTaskLoop();
313 }
314 return ScopedAStatus::ok();
315}
316
Yu Shan06ddbc62023-08-23 18:05:26 -0700317ScopedAStatus RemoteAccessService::isTaskScheduleSupported([[maybe_unused]] bool* out) {
318 // TODO(b/297271235): implement this.
319 return ScopedAStatus::ok();
320}
321
322ScopedAStatus RemoteAccessService::scheduleTask([[maybe_unused]] const ScheduleInfo& scheduleInfo) {
323 // TODO(b/297271235): implement this.
324 return ScopedAStatus::ok();
325}
326
327ScopedAStatus RemoteAccessService::unscheduleTask([[maybe_unused]] const std::string& clientId,
328 [[maybe_unused]] const std::string& scheduleId) {
329 // TODO(b/297271235): implement this.
330 return ScopedAStatus::ok();
331}
332
333ScopedAStatus RemoteAccessService::unscheduleAllTasks(
334 [[maybe_unused]] const std::string& clientId) {
335 // TODO(b/297271235): implement this.
336 return ScopedAStatus::ok();
337}
338
339ScopedAStatus RemoteAccessService::isTaskScheduled([[maybe_unused]] const std::string& clientId,
340 [[maybe_unused]] const std::string& scheduleId,
341 [[maybe_unused]] bool* out) {
342 // TODO(b/297271235): implement this.
343 return ScopedAStatus::ok();
344}
345
346ScopedAStatus RemoteAccessService::getAllScheduledTasks(const std::string& clientId,
347 std::vector<ScheduleInfo>* out) {
348 // TODO(b/297271235): implement this.
349 return ScopedAStatus::ok();
350}
351
Yu Shan7a5283f2022-10-25 18:01:05 -0700352bool RemoteAccessService::checkDumpPermission() {
353 uid_t uid = AIBinder_getCallingUid();
354 return uid == AID_ROOT || uid == AID_SHELL || uid == AID_SYSTEM;
355}
356
357void RemoteAccessService::dumpHelp(int fd) {
Yu Shan95493682023-03-21 18:00:17 -0700358 dprintf(fd,
359 "RemoteAccess HAL debug interface, Usage: \n"
360 "%s [0/1](isReadyForRemoteTask) [0/1](isWakeupRequired): Set the new AP state\n"
361 "%s: Start a debug callback that will record the received tasks\n"
362 "%s: Stop the debug callback\n"
363 "%s: Show tasks received by debug callback\n"
364 "%s: Get vehicle id\n"
365 "%s [client_id] [task_data]: Inject a task\n"
Yu Shan194757d2023-04-19 11:44:35 -0700366 "%s [client_id] [task_data] [latencyInSec]: "
367 "Inject a task on next reboot after latencyInSec seconds\n"
Yu Shan95493682023-03-21 18:00:17 -0700368 "%s: Show status\n",
369 COMMAND_SET_AP_STATE, COMMAND_START_DEBUG_CALLBACK, COMMAND_STOP_DEBUG_CALLBACK,
Yu Shan194757d2023-04-19 11:44:35 -0700370 COMMAND_SHOW_TASK, COMMAND_GET_VEHICLE_ID, COMMAND_INJECT_TASK,
371 COMMAND_INJECT_TASK_NEXT_REBOOT, COMMAND_STATUS);
Yu Shan7a5283f2022-10-25 18:01:05 -0700372}
373
374binder_status_t RemoteAccessService::dump(int fd, const char** args, uint32_t numArgs) {
375 if (!checkDumpPermission()) {
376 dprintf(fd, "Caller must be root, system or shell\n");
377 return STATUS_PERMISSION_DENIED;
378 }
379
380 if (numArgs == 0) {
381 dumpHelp(fd);
Yu Shan95493682023-03-21 18:00:17 -0700382 printCurrentStatus(fd);
Yu Shan7a5283f2022-10-25 18:01:05 -0700383 return STATUS_OK;
384 }
385
386 if (!strcmp(args[0], COMMAND_SET_AP_STATE)) {
387 if (numArgs < 3) {
388 dumpHelp(fd);
389 return STATUS_OK;
390 }
391 ApState apState = {};
392 const char* remoteTaskFlag = args[1];
393 if (!strcmp(remoteTaskFlag, "1") && !strcmp(remoteTaskFlag, "0")) {
394 dumpHelp(fd);
395 return STATUS_OK;
396 }
397 if (!checkBoolFlag(args[1])) {
398 dumpHelp(fd);
399 return STATUS_OK;
400 }
401 if (!strcmp(args[1], "1")) {
402 apState.isReadyForRemoteTask = true;
403 }
404 if (!checkBoolFlag(args[2])) {
405 dumpHelp(fd);
406 return STATUS_OK;
407 }
408 if (!strcmp(args[2], "1")) {
409 apState.isWakeupRequired = true;
410 }
411 auto status = notifyApStateChange(apState);
412 if (!status.isOk()) {
413 dprintErrorStatus(fd, "Failed to set AP state", status);
414 } else {
415 dprintf(fd, "successfully set the new AP state\n");
416 }
417 } else if (!strcmp(args[0], COMMAND_START_DEBUG_CALLBACK)) {
418 mDebugCallback = ndk::SharedRefBase::make<DebugRemoteTaskCallback>();
419 setRemoteTaskCallback(mDebugCallback);
420 dprintf(fd, "Debug callback registered\n");
421 } else if (!strcmp(args[0], COMMAND_STOP_DEBUG_CALLBACK)) {
422 if (mDebugCallback) {
423 mDebugCallback.reset();
424 }
425 clearRemoteTaskCallback();
426 dprintf(fd, "Debug callback unregistered\n");
427 } else if (!strcmp(args[0], COMMAND_SHOW_TASK)) {
428 if (mDebugCallback) {
429 dprintf(fd, "%s", mDebugCallback->printTasks().c_str());
430 } else {
431 dprintf(fd, "Debug callback is not currently used, use \"%s\" first.\n",
432 COMMAND_START_DEBUG_CALLBACK);
433 }
Eric Jeong6c3a1d82023-03-16 00:45:40 -0700434 } else if (!strcmp(args[0], COMMAND_GET_VEHICLE_ID)) {
435 std::string vehicleId;
436 auto status = getVehicleId(&vehicleId);
Yu Shan7a5283f2022-10-25 18:01:05 -0700437 if (!status.isOk()) {
Eric Jeong6c3a1d82023-03-16 00:45:40 -0700438 dprintErrorStatus(fd, "Failed to get vehicle ID", status);
Yu Shan7a5283f2022-10-25 18:01:05 -0700439 } else {
Eric Jeong6c3a1d82023-03-16 00:45:40 -0700440 dprintf(fd, "Vehicle Id: %s\n", vehicleId.c_str());
Yu Shan7a5283f2022-10-25 18:01:05 -0700441 }
Yu Shan95493682023-03-21 18:00:17 -0700442 } else if (!strcmp(args[0], COMMAND_INJECT_TASK)) {
443 if (numArgs < 3) {
444 dumpHelp(fd);
445 return STATUS_OK;
446 }
447 debugInjectTask(fd, args[1], args[2]);
Yu Shan194757d2023-04-19 11:44:35 -0700448 } else if (!strcmp(args[0], COMMAND_INJECT_TASK_NEXT_REBOOT)) {
449 if (numArgs < 4) {
450 dumpHelp(fd);
451 return STATUS_OK;
452 }
453 debugInjectTaskNextReboot(fd, args[1], args[2], args[3]);
Yu Shan95493682023-03-21 18:00:17 -0700454 } else if (!strcmp(args[0], COMMAND_STATUS)) {
455 printCurrentStatus(fd);
Yu Shan7a5283f2022-10-25 18:01:05 -0700456 } else {
457 dumpHelp(fd);
458 }
459
460 return STATUS_OK;
461}
462
Yu Shan95493682023-03-21 18:00:17 -0700463void RemoteAccessService::printCurrentStatus(int fd) {
464 std::lock_guard<std::mutex> lockGuard(mLock);
465 dprintf(fd,
466 "\nRemoteAccess HAL status \n"
467 "Remote task callback registered: %s\n"
468 "Task receiving GRPC connection established: %s\n"
469 "Received task count by clientId: \n%s\n",
470 boolToString(mRemoteTaskCallback.get()).c_str(), boolToString(mGrpcConnected).c_str(),
471 clientIdToTaskCountToStringLocked().c_str());
472}
473
474void RemoteAccessService::debugInjectTask(int fd, std::string_view clientId,
475 std::string_view taskData) {
476 std::string clientIdCopy = std::string(clientId);
477 if (auto result = deliverRemoteTaskThroughCallback(clientIdCopy, taskData); !result.ok()) {
Yu Shan194757d2023-04-19 11:44:35 -0700478 dprintf(fd, "Failed to inject task: %s\n", result.error().message().c_str());
Yu Shan95493682023-03-21 18:00:17 -0700479 return;
480 }
481 dprintf(fd, "Task for client: %s, data: [%s] successfully injected\n", clientId.data(),
482 taskData.data());
483}
484
Yu Shan194757d2023-04-19 11:44:35 -0700485void RemoteAccessService::debugInjectTaskNextReboot(int fd, std::string_view clientId,
486 std::string_view taskData,
487 const char* latencyInSecStr) {
488 int latencyInSec;
489 if (!ParseInt(latencyInSecStr, &latencyInSec)) {
490 dprintf(fd, "The input latency in second is not a valid integer");
491 return;
492 }
493 std::ofstream debugTaskFile;
494 debugTaskFile.open(DEBUG_TASK_FILE, std::ios::out);
495 if (!debugTaskFile.is_open()) {
496 dprintf(fd,
497 "Failed to open debug task file, please run the command: "
498 "'adb shell touch %s' first\n",
499 DEBUG_TASK_FILE);
500 return;
501 }
502 if (taskData.find("\n") != std::string::npos) {
503 dprintf(fd, "Task data must not contain newline\n");
504 return;
505 }
506 debugTaskFile << clientId << "\n" << taskData << "\n" << latencyInSec;
507 debugTaskFile.close();
508 dprintf(fd,
509 "Task with clientId: %s, task data: %s, latency: %d sec scheduled for next reboot\n",
510 clientId.data(), taskData.data(), latencyInSec);
511}
512
Yu Shan95493682023-03-21 18:00:17 -0700513std::string RemoteAccessService::clientIdToTaskCountToStringLocked() {
514 // Print the table header
515 std::string output = "| ClientId | Count |\n";
516 for (const auto& [clientId, taskCount] : mClientIdToTaskCount) {
517 output += StringPrintf(" %-9s %-6zu\n", clientId.c_str(), taskCount);
518 }
519 return output;
520}
521
Yu Shan7a5283f2022-10-25 18:01:05 -0700522ScopedAStatus DebugRemoteTaskCallback::onRemoteTaskRequested(const std::string& clientId,
523 const std::vector<uint8_t>& data) {
524 std::lock_guard<std::mutex> lockGuard(mLock);
525 mTasks.push_back({
526 .clientId = clientId,
527 .data = data,
528 });
529 return ScopedAStatus::ok();
530}
531
532std::string DebugRemoteTaskCallback::printTasks() {
533 std::lock_guard<std::mutex> lockGuard(mLock);
534 std::string s = StringPrintf("Received %zu tasks in %f seconds", mTasks.size(),
535 (android::uptimeMillis() - mStartTimeMillis) / 1000.);
536 for (size_t i = 0; i < mTasks.size(); i++) {
537 StringAppendF(&s, "Client Id: %s, Data: %s\n", mTasks[i].clientId.c_str(),
538 printBytes(mTasks[i].data).c_str());
539 }
540 return s;
541}
542
543} // namespace remoteaccess
544} // namespace automotive
545} // namespace hardware
546} // namespace android