Используйте автомобильный сторожевой таймер для отладки VHAL. Автомобильный сторожевой таймер следит за состоянием — и убивает — нездоровые процессы. Чтобы процесс мог контролироваться сторожевым устройством автомобиля, этот процесс должен быть зарегистрирован в сторожевом устройстве автомобиля. Когда автомобильный сторожевой таймер убивает неработоспособные процессы, автомобильный сторожевой таймер записывает состояние процессов в data/anr
, как и в случае других дампов приложения, не отвечающего (ANR). Это облегчает процесс отладки.
В этой статье описывается, как HAL и службы поставщиков могут зарегистрировать процесс с помощью сторожевого таймера автомобиля.
Поставщик HAL
Обычно поставщик HAL использует пул потоков для hwbinder
. Однако клиент car watchdog взаимодействует с демоном car watchdog через binder
, который отличается от hwbinder
. Поэтому используется другой пул потоков для binder
.
Укажите car watchdog helpl в makefile
- Включите
carwatchdog_aidl_interface-ndk_platform
вshared_libs
:Android.bp
:cc_defaults {
name: "vhal_v2_0_defaults",
shared_libs: [
"libbinder_ndk",
"libhidlbase",
"liblog",
"libutils",
"android.hardware.automotive.vehicle@2.0",
"carwatchdog_aidl_interface-ndk_platform",
],
cflags: [
"-Wall",
"-Wextra",
"-Werror",
],
}
Добавить политику SELinux
- Разрешить
system_server
убить ваш HAL. Если у вас нетsystem_server.te
, создайте его. Настоятельно рекомендуется добавить политику SELinux для каждого устройства. - Разрешите поставщику HAL использовать связыватель (макрос
binder_use
) и добавьте поставщика HAL в клиентский доменcarwatchdog
(макросcarwatchdog_client_domain
). См. приведенный ниже код дляsystemserver.te
иvehicle_default.te
:# Allow system_server to kill vehicle HAL
allow system_server hal_vehicle_server:process sigkill;# Configuration for register VHAL to car watchdog
carwatchdog_client_domain(hal_vehicle_default)
binder_use(hal_vehicle_default)
Реализуйте клиентский класс, наследуя BnCarWatchdogClient.
- В
checkIfAlive
выполните проверку работоспособности. Например, отправьте сообщение в обработчик цикла потока. Если все в порядке, вызовитеICarWatchdog::tellClientAlive
. См. приведенный ниже код дляWatchogClient.h
иWatchogClient.cpp
:class WatchdogClient : public aidl::android::automotive::watchdog::BnCarWatchdogClient {
public:
explicit WatchdogClient(const ::android::sp<::android::Looper>& handlerLooper, VehicleHalManager* vhalManager);
ndk::ScopedAStatus checkIfAlive(int32_t sessionId, aidl::android::automotive::watchdog::TimeoutLength timeout) override;
ndk::ScopedAStatus prepareProcessTermination() override;
};ndk::ScopedAStatus WatchdogClient::checkIfAlive(int32_t sessionId, TimeoutLength /*timeout*/) {
// Implement or call your health check logic here
return ndk::ScopedAStatus::ok();
}
Запустите поток связывателя и зарегистрируйте клиент
- Создайте пул потоков для связи связующего. Если поставщик HAL использует hwbinder для своих собственных целей, вы должны создать еще один пул потоков для связи связывателя car watchdog).
- Найдите демон с именем и вызовите
ICarWatchdog::registerClient
. Имя интерфейса демона car watchdog —android.automotive.watchdog.ICarWatchdog/default
. - В зависимости от скорости отклика службы выберите один из трех следующих типов тайм-аута, поддерживаемых сторожевым таймером автомобиля, а затем передайте тайм-аут в вызове
ICarWatchdog::registerClient
:- критический(3с)
- умеренный (5с)
- нормальный(10с)
VehicleService.cpp
иWatchogClient.cpp
:int main(int /* argc */, char* /* argv */ []) {
// Set up thread pool for hwbinder
configureRpcThreadpool(4, false /* callerWillJoin */);
ALOGI("Registering as service...");
status_t status = service->registerAsService();
if (status != OK) {
ALOGE("Unable to register vehicle service (%d)", status);
return 1;
}
// Setup a binder thread pool to be a car watchdog client.
ABinderProcess_setThreadPoolMaxThreadCount(1);
ABinderProcess_startThreadPool();
sp<Looper> looper(Looper::prepare(0 /* opts */));
std::shared_ptr<WatchdogClient> watchdogClient =
ndk::SharedRefBase::make<WatchdogClient>(looper, service.get());
// The current health check is done in the main thread, so it falls short of capturing the real
// situation. Checking through HAL binder thread should be considered.
if (!watchdogClient->initialize()) {
ALOGE("Failed to initialize car watchdog client");
return 1;
}
ALOGI("Ready");
while (true) {
looper->pollAll(-1 /* timeoutMillis */);
}
return 1;
}bool WatchdogClient::initialize() {
ndk::SpAIBinder binder(AServiceManager_getService("android.automotive.watchdog.ICarWatchdog/default"));
if (binder.get() == nullptr) {
ALOGE("Failed to get carwatchdog daemon");
return false;
}
std::shared_ptr<ICarWatchdog> server = ICarWatchdog::fromBinder(binder);
if (server == nullptr) {
ALOGE("Failed to connect to carwatchdog daemon");
return false;
}
mWatchdogServer = server;
binder = this->asBinder();
if (binder.get() == nullptr) {
ALOGE("Failed to get car watchdog client binder object");
return false;
}
std::shared_ptr<ICarWatchdogClient> client = ICarWatchdogClient::fromBinder(binder);
if (client == nullptr) {
ALOGE("Failed to get ICarWatchdogClient from binder");
return false;
}
mTestClient = client;
mWatchdogServer->registerClient(client, TimeoutLength::TIMEOUT_NORMAL);
ALOGI("Successfully registered the client to car watchdog server");
return true;
}
Услуги поставщика (собственные)
Укажите файл makefile помощи car watchdog
- Включите
carwatchdog_aidl_interface-ndk_platform
вshared_libs
.Android.bp
cc_binary {
name: "sample_native_client",
srcs: [
"src/*.cpp"
],
shared_libs: [
"carwatchdog_aidl_interface-ndk_platform",
"libbinder_ndk",
],
vendor: true,
}
Добавьте политику SELinux
- Чтобы добавить политику SELinux, разрешите сервисному домену поставщика использовать связыватель (макрос
binder_use
) и добавьте сервисный домен поставщика в клиентский доменcarwatchdog
(макросcarwatchdog_client_domain
). См. приведенный ниже код дляsample_client.te
иfile_contexts
:type sample_client, domain;
type sample_client_exec, exec_type, file_type, vendor_file_type;
carwatchdog_client_domain(sample_client)
init_daemon_domain(sample_client)
binder_use(sample_client)/vendor/bin/sample_native_client u:object_r:sample_client_exec:s0
Реализуйте клиентский класс, наследуя BnCarWatchdogClient.
- В
checkIfAlive
выполните проверку работоспособности. Один из вариантов — опубликовать обработчик цикла потока. Если все в порядке, вызовитеICarWatchdog::tellClientAlive
. См. приведенный ниже код дляSampleNativeClient.h
иSampleNativeClient.cpp
:class SampleNativeClient : public BnCarWatchdogClient {
public:
ndk::ScopedAStatus checkIfAlive(int32_t sessionId, TimeoutLength
timeout) override;
ndk::ScopedAStatus prepareProcessTermination() override;
void initialize();
private:
void respondToDaemon();
private:
::android::sp<::android::Looper> mHandlerLooper;
std::shared_ptr<ICarWatchdog> mWatchdogServer;
std::shared_ptr<ICarWatchdogClient> mClient;
int32_t mSessionId;
};ndk::ScopedAStatus WatchdogClient::checkIfAlive(int32_t sessionId, TimeoutLength timeout) {
mHandlerLooper->removeMessages(mMessageHandler,
WHAT_CHECK_ALIVE);
mSessionId = sessionId;
mHandlerLooper->sendMessage(mMessageHandler,
Message(WHAT_CHECK_ALIVE));
return ndk::ScopedAStatus::ok();
}
// WHAT_CHECK_ALIVE triggers respondToDaemon from thread handler
void WatchdogClient::respondToDaemon() {
// your health checking method here
ndk::ScopedAStatus status = mWatchdogServer->tellClientAlive(mClient,
mSessionId);
}
Запустите поток связующего и зарегистрируйте клиента
Имя интерфейса демона car watchdog — android.automotive.watchdog.ICarWatchdog/default
.
- Найдите демон с именем и вызовите
ICarWatchdog::registerClient
. См. приведенный ниже код дляmain.cpp
иSampleNativeClient.cpp
:int main(int argc, char** argv) {
sp<Looper> looper(Looper::prepare(/*opts=*/0));
ABinderProcess_setThreadPoolMaxThreadCount(1);
ABinderProcess_startThreadPool();
std::shared_ptr<SampleNativeClient> client =
ndk::SharedRefBase::make<SampleNatvieClient>(looper);
// The client is registered in initialize()
client->initialize();
...
}void SampleNativeClient::initialize() {
ndk::SpAIBinder binder(AServiceManager_getService(
"android.automotive.watchdog.ICarWatchdog/default"));
std::shared_ptr<ICarWatchdog> server =
ICarWatchdog::fromBinder(binder);
mWatchdogServer = server;
ndk::SpAIBinder binder = this->asBinder();
std::shared_ptr<ICarWatchdogClient> client =
ICarWatchdogClient::fromBinder(binder)
mClient = client;
server->registerClient(client, TimeoutLength::TIMEOUT_NORMAL);
}
Службы поставщика (Android)
Реализуйте клиента, наследуя CarWatchdogClientCallback
- Отредактируйте новый файл следующим образом:
private final CarWatchdogClientCallback mClientCallback = new CarWatchdogClientCallback() {
@Override
public boolean onCheckHealthStatus(int sessionId, int timeout) {
// Your health check logic here
// Returning true implies the client is healthy
// If false is returned, the client should call
// CarWatchdogManager.tellClientAlive after health check is
// completed
}
@Override
public void onPrepareProcessTermination() {}
};
Зарегистрировать клиент
- Вызов
CarWatchdogManager.registerClient()
:private void startClient() {
CarWatchdogManager manager =
(CarWatchdogManager) car.getCarManager(
Car.CAR_WATCHDOG_SERVICE);
// Choose a proper executor according to your health check method
ExecutorService executor = Executors.newFixedThreadPool(1);
manager.registerClient(executor, mClientCallback,
CarWatchdogManager.TIMEOUT_NORMAL);
}
Отменить регистрацию клиента
- Вызовите
CarWatchdogManager.unregisterClient()
, когда служба будет завершена:private void finishClient() {
CarWatchdogManager manager =
(CarWatchdogManager) car.getCarManager(
Car.CAR_WATCHDOG_SERVICE);
manager.unregisterClient(mClientCallback);
}
Обнаружение процессов, завершенных автомобильным сторожевым таймером
Car Watchdog сбрасывает/убивает процессы (HAL поставщика, собственные службы поставщика, службы Android поставщика), которые зарегистрированы в Car Watchdog, когда они зависают и не отвечают. Такой дамп выявляется проверкой logcats. Car watchdog выводит журнал carwatchdog killed process_name (pid:process_id)
, когда проблемный процесс сбрасывается или уничтожается. Поэтому:
$ adb logcat -s CarServiceHelper | fgrep "carwatchdog killed"
Соответствующие журналы захватываются. Например, если приложение KitchenSink (клиент автомобильного сторожевого таймера) зависает, в журнал записывается следующая строка:
05-01 09:50:19.683 578 5777 W CarServiceHelper: carwatchdog killed com.google.android.car.kitchensink (pid: 5574)
Чтобы определить, почему и где приложение KitchenSink зависло, используйте дамп процесса, хранящийся в /data/anr
, точно так же, как вы бы использовали случаи ANR Activity.
$ adb root
$ adb shell grep -Hn "pid process_pid" /data/anr/*
Следующий образец выходных данных относится к приложению KitchenSink:
$ adb shell su root grep -Hn "pid 5574" /data/anr/*.
/data/anr/anr_2020-05-01-09-50-18-290:3:----- pid 5574 at 2020-05-01 09:50:18 -----
/data/anr/anr_2020-05-01-09-50-18-290:285:----- Waiting Channels: pid 5574 at 2020-05-01 09:50:18 -----
Найдите файл дампа (например, /data/anr/anr_2020-05-01-09-50-18-290
в приведенном выше примере) и начните анализ.