diff options
author | TreeHugger Robot <treehugger-gerrit@google.com> | 2021-06-22 22:56:34 +0000 |
---|---|---|
committer | Android (Google) Code Review <android-gerrit@google.com> | 2021-06-22 22:56:34 +0000 |
commit | 64898ed07e741b3dd0a152b3c8424d30233936cd (patch) | |
tree | 51a913a6a9978b4399bb848c3de51ef733c82332 /cpp/watchdog | |
parent | f595578e83eea5a62fb9cc08cc1d835574760a1d (diff) | |
parent | 0a0a787978537715d4e40d48749d98f85415d697 (diff) | |
download | Car-64898ed07e741b3dd0a152b3c8424d30233936cd.tar.gz |
Merge "Handle garage mode I/O overuse monitoring." into sc-dev
Diffstat (limited to 'cpp/watchdog')
22 files changed, 547 insertions, 315 deletions
diff --git a/cpp/watchdog/server/src/IoOveruseMonitor.cpp b/cpp/watchdog/server/src/IoOveruseMonitor.cpp index 6b77464cda..6d24fcc447 100644 --- a/cpp/watchdog/server/src/IoOveruseMonitor.cpp +++ b/cpp/watchdog/server/src/IoOveruseMonitor.cpp @@ -37,6 +37,7 @@ namespace automotive { namespace watchdog { using ::android::IPCThreadState; +using ::android::sp; using ::android::automotive::watchdog::internal::ComponentType; using ::android::automotive::watchdog::internal::IoOveruseConfiguration; using ::android::automotive::watchdog::internal::PackageIdentifier; @@ -165,7 +166,7 @@ void IoOveruseMonitor::terminate() { } Result<void> IoOveruseMonitor::onPeriodicCollection( - time_t time, const android::wp<UidIoStats>& uidIoStats, + time_t time, SystemState systemState, const android::wp<UidIoStats>& uidIoStats, [[maybe_unused]] const android::wp<ProcStat>& procStat, [[maybe_unused]] const android::wp<ProcPidStat>& procPidStat) { if (uidIoStats == nullptr) { @@ -209,6 +210,7 @@ Result<void> IoOveruseMonitor::onPeriodicCollection( } const auto packageInfosByUid = mPackageInfoResolver->getPackageInfosForUids(seenUids); std::unordered_map<uid_t, IoOveruseStats> overusingNativeStats; + bool isGarageModeActive = systemState == SystemState::GARAGE_MODE; for (const auto& [uid, uidIoStats] : perUidIoUsage) { const auto& packageInfo = packageInfosByUid.find(uid); if (packageInfo == packageInfosByUid.end()) { @@ -218,8 +220,7 @@ Result<void> IoOveruseMonitor::onPeriodicCollection( * TODO(b/185498771): Derive the garage mode status from the collection flag, which will * be added to the |onPeriodicCollection| API. */ - UserPackageIoUsage curUsage(packageInfo->second, uidIoStats.ios, - /*isGarageModeActive=*/false); + UserPackageIoUsage curUsage(packageInfo->second, uidIoStats.ios, isGarageModeActive); UserPackageIoUsage* dailyIoUsage; if (auto cachedUsage = mUserPackageDailyIoUsageById.find(curUsage.id()); cachedUsage != mUserPackageDailyIoUsageById.end()) { @@ -318,11 +319,12 @@ Result<void> IoOveruseMonitor::onPeriodicCollection( } Result<void> IoOveruseMonitor::onCustomCollection( - time_t time, [[maybe_unused]] const std::unordered_set<std::string>& filterPackages, + time_t time, SystemState systemState, + [[maybe_unused]] const std::unordered_set<std::string>& filterPackages, const android::wp<UidIoStats>& uidIoStats, const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat) { // Nothing special for custom collection. - return onPeriodicCollection(time, uidIoStats, procStat, procPidStat); + return onPeriodicCollection(time, systemState, uidIoStats, procStat, procPidStat); } Result<void> IoOveruseMonitor::onPeriodicMonitor( diff --git a/cpp/watchdog/server/src/IoOveruseMonitor.h b/cpp/watchdog/server/src/IoOveruseMonitor.h index efac5538aa..4cf6cc6753 100644 --- a/cpp/watchdog/server/src/IoOveruseMonitor.h +++ b/cpp/watchdog/server/src/IoOveruseMonitor.h @@ -122,16 +122,14 @@ public: return {}; } - // TODO(b/185498771): Forward WatchdogBinderMediator's notifySystemStateChange call to - // WatchdogPerfService. On POWER_CYCLE_SHUTDOWN_PREPARE, switch to garage mode collection - // and pass collection flag as a param in this API to indicate garage mode collection. - android::base::Result<void> onPeriodicCollection(time_t time, + android::base::Result<void> onPeriodicCollection(time_t time, SystemState systemState, const android::wp<UidIoStats>& uidIoStats, const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat); android::base::Result<void> onCustomCollection( - time_t time, const std::unordered_set<std::string>& filterPackages, + time_t time, SystemState systemState, + const std::unordered_set<std::string>& filterPackages, const android::wp<UidIoStats>& uidIoStats, const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat); diff --git a/cpp/watchdog/server/src/IoPerfCollection.cpp b/cpp/watchdog/server/src/IoPerfCollection.cpp index 08c1daa2bc..5537cafeb9 100644 --- a/cpp/watchdog/server/src/IoPerfCollection.cpp +++ b/cpp/watchdog/server/src/IoPerfCollection.cpp @@ -21,9 +21,10 @@ #include <WatchdogProperties.sysprop.h> #include <android-base/file.h> #include <android-base/stringprintf.h> -#include <inttypes.h> #include <log/log.h> +#include <inttypes.h> + #include <iomanip> #include <limits> #include <string> @@ -361,7 +362,9 @@ Result<void> IoPerfCollection::onBoottimeCollection(time_t time, const wp<UidIoS &mBoottimeCollection); } -Result<void> IoPerfCollection::onPeriodicCollection(time_t time, const wp<UidIoStats>& uidIoStats, +Result<void> IoPerfCollection::onPeriodicCollection(time_t time, + [[maybe_unused]] SystemState systemState, + const wp<UidIoStats>& uidIoStats, const wp<ProcStat>& procStat, const wp<ProcPidStat>& procPidStat) { auto result = checkDataCollectors(uidIoStats, procStat, procPidStat); @@ -374,9 +377,9 @@ Result<void> IoPerfCollection::onPeriodicCollection(time_t time, const wp<UidIoS } Result<void> IoPerfCollection::onCustomCollection( - time_t time, const std::unordered_set<std::string>& filterPackages, - const wp<UidIoStats>& uidIoStats, const wp<ProcStat>& procStat, - const wp<ProcPidStat>& procPidStat) { + time_t time, [[maybe_unused]] SystemState systemState, + const std::unordered_set<std::string>& filterPackages, const wp<UidIoStats>& uidIoStats, + const wp<ProcStat>& procStat, const wp<ProcPidStat>& procPidStat) { auto result = checkDataCollectors(uidIoStats, procStat, procPidStat); if (!result.ok()) { return result; diff --git a/cpp/watchdog/server/src/IoPerfCollection.h b/cpp/watchdog/server/src/IoPerfCollection.h index 1c40d00fed..2e976dafcb 100644 --- a/cpp/watchdog/server/src/IoPerfCollection.h +++ b/cpp/watchdog/server/src/IoPerfCollection.h @@ -137,13 +137,14 @@ public: const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat); - android::base::Result<void> onPeriodicCollection(time_t time, + android::base::Result<void> onPeriodicCollection(time_t time, SystemState systemState, const android::wp<UidIoStats>& uidIoStats, const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat); android::base::Result<void> onCustomCollection( - time_t time, const std::unordered_set<std::string>& filterPackages, + time_t time, SystemState systemState, + const std::unordered_set<std::string>& filterPackages, const android::wp<UidIoStats>& uidIoStats, const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat); diff --git a/cpp/watchdog/server/src/ServiceManager.cpp b/cpp/watchdog/server/src/ServiceManager.cpp index a50167b830..afdc2e4b3a 100644 --- a/cpp/watchdog/server/src/ServiceManager.cpp +++ b/cpp/watchdog/server/src/ServiceManager.cpp @@ -26,13 +26,11 @@ namespace automotive { namespace watchdog { using ::android::sp; -using ::android::automotive::watchdog::WatchdogPerfService; -using ::android::automotive::watchdog::WatchdogProcessService; using ::android::base::Error; using ::android::base::Result; sp<WatchdogProcessService> ServiceManager::sWatchdogProcessService = nullptr; -sp<WatchdogPerfService> ServiceManager::sWatchdogPerfService = nullptr; +sp<WatchdogPerfServiceInterface> ServiceManager::sWatchdogPerfService = nullptr; sp<WatchdogBinderMediator> ServiceManager::sWatchdogBinderMediator = nullptr; sp<IWatchdogServiceHelper> ServiceManager::sWatchdogServiceHelper = nullptr; @@ -54,7 +52,7 @@ Result<void> ServiceManager::startServices(const sp<Looper>& looper) { if (const auto result = startPerfService(); !result.ok()) { return result; } - sWatchdogServiceHelper = new WatchdogServiceHelper(); + sWatchdogServiceHelper = sp<WatchdogServiceHelper>::make(); if (const auto result = sWatchdogServiceHelper->init(sWatchdogProcessService); !result.ok()) { return Error() << "Failed to initialize watchdog service helper: " << result.error(); } @@ -86,7 +84,7 @@ void ServiceManager::terminateServices() { } Result<void> ServiceManager::startProcessAnrMonitor(const sp<Looper>& looper) { - sp<WatchdogProcessService> service = new WatchdogProcessService(looper); + sp<WatchdogProcessService> service = sp<WatchdogProcessService>::make(looper); if (const auto result = service->start(); !result.ok()) { return Error(result.error().code()) << "Failed to start watchdog process monitoring: " << result.error(); @@ -96,8 +94,9 @@ Result<void> ServiceManager::startProcessAnrMonitor(const sp<Looper>& looper) { } Result<void> ServiceManager::startPerfService() { - sp<WatchdogPerfService> service = new WatchdogPerfService(); - if (const auto result = service->registerDataProcessor(new IoPerfCollection()); !result.ok()) { + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); + if (const auto result = service->registerDataProcessor(sp<IoPerfCollection>::make()); + !result.ok()) { return Error() << "Failed to register I/O perf collection: " << result.error(); } if (const auto result = service->start(); !result.ok()) { @@ -110,8 +109,8 @@ Result<void> ServiceManager::startPerfService() { Result<void> ServiceManager::startBinderMediator() { sWatchdogBinderMediator = - new WatchdogBinderMediator(sWatchdogProcessService, sWatchdogPerfService, - sWatchdogServiceHelper); + sp<WatchdogBinderMediator>::make(sWatchdogProcessService, sWatchdogPerfService, + sWatchdogServiceHelper); if (const auto result = sWatchdogBinderMediator->init(); !result.ok()) { return Error(result.error().code()) << "Failed to initialize watchdog binder mediator: " << result.error(); diff --git a/cpp/watchdog/server/src/ServiceManager.h b/cpp/watchdog/server/src/ServiceManager.h index a0cc4d40c4..6374e8f6bb 100644 --- a/cpp/watchdog/server/src/ServiceManager.h +++ b/cpp/watchdog/server/src/ServiceManager.h @@ -42,7 +42,7 @@ private: static android::base::Result<void> startPerfService(); static android::sp<WatchdogProcessService> sWatchdogProcessService; - static android::sp<WatchdogPerfService> sWatchdogPerfService; + static android::sp<WatchdogPerfServiceInterface> sWatchdogPerfService; static android::sp<WatchdogBinderMediator> sWatchdogBinderMediator; static android::sp<IWatchdogServiceHelper> sWatchdogServiceHelper; }; diff --git a/cpp/watchdog/server/src/WatchdogBinderMediator.cpp b/cpp/watchdog/server/src/WatchdogBinderMediator.cpp index f3fba35d31..0166112109 100644 --- a/cpp/watchdog/server/src/WatchdogBinderMediator.cpp +++ b/cpp/watchdog/server/src/WatchdogBinderMediator.cpp @@ -79,7 +79,7 @@ Result<void> addToServiceManager(const char* serviceName, sp<IBinder> service) { WatchdogBinderMediator::WatchdogBinderMediator( const android::sp<WatchdogProcessService>& watchdogProcessService, - const android::sp<WatchdogPerfService>& watchdogPerfService, + const android::sp<WatchdogPerfServiceInterface>& watchdogPerfService, const android::sp<IWatchdogServiceHelper>& watchdogServiceHelper, const AddServiceFunction& addServiceHandler) : mWatchdogProcessService(watchdogProcessService), @@ -89,10 +89,11 @@ WatchdogBinderMediator::WatchdogBinderMediator( mAddServiceHandler = &addToServiceManager; } if (watchdogServiceHelper != nullptr) { - mIoOveruseMonitor = new IoOveruseMonitor(watchdogServiceHelper); + mIoOveruseMonitor = sp<IoOveruseMonitor>::make(watchdogServiceHelper); mWatchdogInternalHandler = - new WatchdogInternalHandler(this, watchdogServiceHelper, mWatchdogProcessService, - mWatchdogPerfService, mIoOveruseMonitor); + sp<WatchdogInternalHandler>::make(this, watchdogServiceHelper, + mWatchdogProcessService, mWatchdogPerfService, + mIoOveruseMonitor); } } diff --git a/cpp/watchdog/server/src/WatchdogBinderMediator.h b/cpp/watchdog/server/src/WatchdogBinderMediator.h index 212352066b..493d231546 100644 --- a/cpp/watchdog/server/src/WatchdogBinderMediator.h +++ b/cpp/watchdog/server/src/WatchdogBinderMediator.h @@ -57,7 +57,7 @@ class WatchdogBinderMediatorPeer; class WatchdogBinderMediator : public BnCarWatchdog { public: WatchdogBinderMediator(const android::sp<WatchdogProcessService>& watchdogProcessService, - const android::sp<WatchdogPerfService>& watchdogPerfService, + const android::sp<WatchdogPerfServiceInterface>& watchdogPerfService, const android::sp<IWatchdogServiceHelper>& watchdogServiceHelper, const std::function<android::base::Result<void>( const char*, const android::sp<android::IBinder>&)>& @@ -116,7 +116,7 @@ private: status_t dumpHelpText(const int fd, const std::string& errorMsg); android::sp<WatchdogProcessService> mWatchdogProcessService; - android::sp<WatchdogPerfService> mWatchdogPerfService; + android::sp<WatchdogPerfServiceInterface> mWatchdogPerfService; android::sp<IIoOveruseMonitor> mIoOveruseMonitor; android::sp<WatchdogInternalHandler> mWatchdogInternalHandler; diff --git a/cpp/watchdog/server/src/WatchdogInternalHandler.cpp b/cpp/watchdog/server/src/WatchdogInternalHandler.cpp index 556f9f1394..68bb489204 100644 --- a/cpp/watchdog/server/src/WatchdogInternalHandler.cpp +++ b/cpp/watchdog/server/src/WatchdogInternalHandler.cpp @@ -35,6 +35,7 @@ namespace aawi = ::android::automotive::watchdog::internal; using aawi::ComponentType; using aawi::ICarWatchdogServiceForSystem; using aawi::PackageResourceOveruseAction; +using aawi::PowerCycle; using aawi::ResourceOveruseConfiguration; using ::android::sp; using ::android::String16; @@ -163,13 +164,12 @@ Status WatchdogInternalHandler::notifySystemStateChange(aawi::StateType type, in } switch (type) { case aawi::StateType::POWER_CYCLE: { - aawi::PowerCycle powerCycle = - static_cast<aawi::PowerCycle>(static_cast<uint32_t>(arg1)); - if (powerCycle >= aawi::PowerCycle::NUM_POWER_CYLES) { + PowerCycle powerCycle = static_cast<PowerCycle>(static_cast<uint32_t>(arg1)); + if (powerCycle >= PowerCycle::NUM_POWER_CYLES) { return fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, StringPrintf("Invalid power cycle %d", powerCycle)); } - return mWatchdogProcessService->notifyPowerCycleChange(powerCycle); + return handlePowerCycleChange(powerCycle); } case aawi::StateType::USER_STATE: { userid_t userId = static_cast<userid_t>(arg1); @@ -194,6 +194,30 @@ Status WatchdogInternalHandler::notifySystemStateChange(aawi::StateType type, in StringPrintf("Invalid state change type %d", type)); } +Status WatchdogInternalHandler::handlePowerCycleChange(PowerCycle powerCycle) { + switch (powerCycle) { + case PowerCycle::POWER_CYCLE_SHUTDOWN: + ALOGI("Received SHUTDOWN power cycle"); + mWatchdogProcessService->setEnabled(/*isEnabled=*/false); + break; + case PowerCycle::POWER_CYCLE_SUSPEND: + ALOGI("Received SUSPEND power cycle"); + mWatchdogProcessService->setEnabled(/*isEnabled=*/false); + mWatchdogPerfService->setSystemState(SystemState::GARAGE_MODE); + break; + case PowerCycle::POWER_CYCLE_RESUME: + ALOGI("Received RESUME power cycle"); + mWatchdogProcessService->setEnabled(/*isEnabled=*/true); + mWatchdogPerfService->setSystemState(SystemState::NORMAL_MODE); + break; + default: + ALOGW("Unsupported power cycle: %d", powerCycle); + return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, + "Unsupported power cycle"); + } + return Status::ok(); +} + Status WatchdogInternalHandler::updateResourceOveruseConfigurations( const std::vector<ResourceOveruseConfiguration>& configs) { Status status = checkSystemUser(); diff --git a/cpp/watchdog/server/src/WatchdogInternalHandler.h b/cpp/watchdog/server/src/WatchdogInternalHandler.h index 1f417e7683..a2b4892832 100644 --- a/cpp/watchdog/server/src/WatchdogInternalHandler.h +++ b/cpp/watchdog/server/src/WatchdogInternalHandler.h @@ -47,7 +47,7 @@ public: const android::sp<WatchdogBinderMediator>& binderMediator, const android::sp<IWatchdogServiceHelper>& watchdogServiceHelper, const android::sp<WatchdogProcessService>& watchdogProcessService, - const android::sp<WatchdogPerfService>& watchdogPerfService, + const android::sp<WatchdogPerfServiceInterface>& watchdogPerfService, const android::sp<IIoOveruseMonitor>& ioOveruseMonitor) : mBinderMediator(binderMediator), mWatchdogServiceHelper(watchdogServiceHelper), @@ -106,10 +106,13 @@ protected: private: void checkAndRegisterIoOveruseMonitor(); + android::binder::Status handlePowerCycleChange( + android::automotive::watchdog::internal::PowerCycle powerCycle); + android::sp<WatchdogBinderMediator> mBinderMediator; android::sp<IWatchdogServiceHelper> mWatchdogServiceHelper; android::sp<WatchdogProcessService> mWatchdogProcessService; - android::sp<WatchdogPerfService> mWatchdogPerfService; + android::sp<WatchdogPerfServiceInterface> mWatchdogPerfService; android::sp<IIoOveruseMonitor> mIoOveruseMonitor; friend class WatchdogBinderMediator; diff --git a/cpp/watchdog/server/src/WatchdogPerfService.cpp b/cpp/watchdog/server/src/WatchdogPerfService.cpp index 151a5efd7b..bf7480f7bf 100644 --- a/cpp/watchdog/server/src/WatchdogPerfService.cpp +++ b/cpp/watchdog/server/src/WatchdogPerfService.cpp @@ -36,8 +36,10 @@ namespace android { namespace automotive { namespace watchdog { +using ::android::sp; using ::android::String16; using ::android::String8; +using ::android::automotive::watchdog::internal::PowerCycle; using ::android::base::Error; using ::android::base::Join; using ::android::base::ParseUint; @@ -117,6 +119,17 @@ constexpr const char* toString(std::variant<EventType, SwitchMessage> what) { what); } +constexpr const char* toString(SystemState systemState) { + switch (systemState) { + case SystemState::NORMAL_MODE: + return "NORMAL_MODE"; + case SystemState::GARAGE_MODE: + return "GARAGE_MODE"; + default: + return "UNKNOWN MODE"; + } +} + } // namespace std::string WatchdogPerfService::EventMetadata::toString() const { @@ -131,8 +144,7 @@ std::string WatchdogPerfService::EventMetadata::toString() const { return buffer; } -Result<void> WatchdogPerfService::registerDataProcessor( - android::sp<IDataProcessorInterface> processor) { +Result<void> WatchdogPerfService::registerDataProcessor(sp<IDataProcessorInterface> processor) { if (processor == nullptr) { return Error() << "Must provide a valid data processor"; } @@ -252,6 +264,15 @@ void WatchdogPerfService::terminate() { } } +void WatchdogPerfService::setSystemState(SystemState systemState) { + Mutex::Autolock lock(mMutex); + if (mSystemState != systemState) { + ALOGI("%s switching from %s to %s", kServiceName, toString(mSystemState), + toString(systemState)); + } + mSystemState = systemState; +} + Result<void> WatchdogPerfService::onBootFinished() { Mutex::Autolock lock(mMutex); if (EventType expected = EventType::BOOT_TIME_COLLECTION; mCurrCollectionEvent != expected) { @@ -630,11 +651,12 @@ Result<void> WatchdogPerfService::collectLocked(WatchdogPerfService::EventMetada result = processor->onBoottimeCollection(now, mUidIoStats, mProcStat, mProcPidStat); break; case EventType::PERIODIC_COLLECTION: - result = processor->onPeriodicCollection(now, mUidIoStats, mProcStat, mProcPidStat); + result = processor->onPeriodicCollection(now, mSystemState, mUidIoStats, mProcStat, + mProcPidStat); break; case EventType::CUSTOM_COLLECTION: - result = processor->onCustomCollection(now, metadata->filterPackages, mUidIoStats, - mProcStat, mProcPidStat); + result = processor->onCustomCollection(now, mSystemState, metadata->filterPackages, + mUidIoStats, mProcStat, mProcPidStat); break; default: result = Error() << "Invalid collection event " << toString(mCurrCollectionEvent); @@ -702,6 +724,13 @@ Result<void> WatchdogPerfService::processMonitorEvent( } } metadata->lastUptime += metadata->interval.count(); + if (metadata->lastUptime == currCollectionMetadata->lastUptime) { + /* + * If the |PERIODIC_MONITOR| and *_COLLECTION events overlap, skip the |PERIODIC_MONITOR| + * event. + */ + metadata->lastUptime += metadata->interval.count(); + } mHandlerLooper->sendMessageAtTime(metadata->lastUptime, this, metadata->eventType); return {}; } diff --git a/cpp/watchdog/server/src/WatchdogPerfService.h b/cpp/watchdog/server/src/WatchdogPerfService.h index 6f1230ac6e..7ff9e562a3 100644 --- a/cpp/watchdog/server/src/WatchdogPerfService.h +++ b/cpp/watchdog/server/src/WatchdogPerfService.h @@ -25,6 +25,7 @@ #include <android-base/chrono_utils.h> #include <android-base/result.h> +#include <android/automotive/watchdog/internal/PowerCycle.h> #include <cutils/multiuser.h> #include <gtest/gtest_prod.h> #include <utils/Errors.h> @@ -58,11 +59,16 @@ constexpr const char* kIntervalFlag = "--interval"; constexpr const char* kMaxDurationFlag = "--max_duration"; constexpr const char* kFilterPackagesFlag = "--filter_packages"; +enum SystemState { + NORMAL_MODE = 0, + GARAGE_MODE = 1, +}; + /* * DataProcessor defines methods that must be implemented in order to process the data collected * by |WatchdogPerfService|. */ -class IDataProcessorInterface : public RefBase { +class IDataProcessorInterface : public android::RefBase { public: IDataProcessorInterface() {} virtual ~IDataProcessorInterface() {} @@ -78,14 +84,15 @@ public: const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat) = 0; // Callback to process the data collected periodically post boot complete. virtual android::base::Result<void> onPeriodicCollection( - time_t time, const android::wp<UidIoStats>& uidIoStats, + time_t time, SystemState systemState, const android::wp<UidIoStats>& uidIoStats, const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat) = 0; /* * Callback to process the data collected on custom collection and filter the results only to * the specified |filterPackages|. */ virtual android::base::Result<void> onCustomCollection( - time_t time, const std::unordered_set<std::string>& filterPackages, + time_t time, SystemState systemState, + const std::unordered_set<std::string>& filterPackages, const android::wp<UidIoStats>& uidIoStats, const android::wp<ProcStat>& procStat, const android::wp<ProcPidStat>& procPidStat) = 0; /* @@ -133,52 +140,76 @@ enum SwitchMessage { END_CUSTOM_COLLECTION, }; -// WatchdogPerfService collects performance data during boot-time and periodically post boot -// complete. It exposes APIs that the main thread and binder service can call to start a collection, -// switch the collection type, and generate collection dumps. -class WatchdogPerfService : public MessageHandler { +/* + * WatchdogPerfServiceInterface collects performance data during boot-time and periodically post + * boot complete. It exposes APIs that the main thread and binder service can call to start a + * collection, switch the collection type, and generate collection dumps. + */ +class WatchdogPerfServiceInterface : public MessageHandler { +public: + // Register a data processor to process the data collected by |WatchdogPerfService|. + virtual android::base::Result<void> registerDataProcessor( + android::sp<IDataProcessorInterface> processor) = 0; + /* + * Starts the boot-time collection in the looper handler on a new thread and returns + * immediately. Must be called only once. Otherwise, returns an error. + */ + virtual android::base::Result<void> start() = 0; + // Terminates the collection thread and returns. + virtual void terminate() = 0; + // Sets the system state. + virtual void setSystemState(SystemState systemState) = 0; + // Ends the boot-time collection by switching to periodic collection and returns immediately. + virtual android::base::Result<void> onBootFinished() = 0; + /* + * Depending on the arguments, it either: + * 1. Starts a custom collection. + * 2. Or ends the current custom collection and dumps the collected data. + * Returns any error observed during the dump generation. + */ + virtual android::base::Result<void> onCustomCollection( + int fd, const Vector<android::String16>& args) = 0; + // Generates a dump from the boot-time and periodic collection events. + virtual android::base::Result<void> onDump(int fd) = 0; + // Dumps the help text. + virtual bool dumpHelpText(int fd) = 0; +}; + +class WatchdogPerfService final : public WatchdogPerfServiceInterface { public: WatchdogPerfService() : - mHandlerLooper(new LooperWrapper()), + mHandlerLooper(android::sp<LooperWrapper>::make()), + mSystemState(NORMAL_MODE), mBoottimeCollection({}), mPeriodicCollection({}), mCustomCollection({}), mPeriodicMonitor({}), mCurrCollectionEvent(EventType::INIT), - mUidIoStats(new UidIoStats()), - mProcStat(new ProcStat()), - mProcPidStat(new ProcPidStat()), - mProcDiskStats(new ProcDiskStats()), + mUidIoStats(android::sp<UidIoStats>::make()), + mProcStat(android::sp<ProcStat>::make()), + mProcPidStat(android::sp<ProcPidStat>::make()), + mProcDiskStats(android::sp<ProcDiskStats>::make()), mDataProcessors({}) {} ~WatchdogPerfService() { terminate(); } - // Register a data processor to process the data collected by |WatchdogPerfService|. android::base::Result<void> registerDataProcessor( - android::sp<IDataProcessorInterface> processor); + android::sp<IDataProcessorInterface> processor) override; - // Starts the boot-time collection in the looper handler on a new thread and returns - // immediately. Must be called only once. Otherwise, returns an error. - virtual android::base::Result<void> start(); + android::base::Result<void> start() override; - // Terminates the collection thread and returns. - virtual void terminate(); + void terminate() override; - // Ends the boot-time collection by switching to periodic collection and returns immediately. - virtual android::base::Result<void> onBootFinished(); + void setSystemState(SystemState systemState) override; - // Depending on the arguments, it either: - // 1. Starts a custom collection. - // 2. Or ends the current custom collection and dumps the collected data. - // Returns any error observed during the dump generation. - virtual android::base::Result<void> onCustomCollection(int fd, - const Vector<android::String16>& args); + android::base::Result<void> onBootFinished() override; - // Generates a dump from the boot-time and periodic collection events. - virtual android::base::Result<void> onDump(int fd); + android::base::Result<void> onCustomCollection(int fd, + const Vector<android::String16>& args) override; - // Dumps the help text. - bool dumpHelpText(int fd); + android::base::Result<void> onDump(int fd) override; + + bool dumpHelpText(int fd) override; private: struct EventMetadata { @@ -197,22 +228,26 @@ private: // Dumps the collectors' status when they are disabled. android::base::Result<void> dumpCollectorsStatusLocked(int fd); - // Starts a custom collection on the looper handler, temporarily stops the periodic collection - // (won't discard the collected data), and returns immediately. Returns any error observed - // during this process. - // The custom collection happens once every |interval| seconds. When the |maxDuration| is - // reached, the looper receives a message to end the collection, discards the collected data, - // and starts the periodic collection. This is needed to ensure the custom collection doesn't - // run forever when a subsequent |endCustomCollection| call is not received. - // When |kFilterPackagesFlag| value specified, the results are filtered only to the specified - // package names. + /* + * Starts a custom collection on the looper handler, temporarily stops the periodic collection + * (won't discard the collected data), and returns immediately. Returns any error observed + * during this process. + * The custom collection happens once every |interval| seconds. When the |maxDuration| is + * reached, the looper receives a message to end the collection, discards the collected data, + * and starts the periodic collection. This is needed to ensure the custom collection doesn't + * run forever when a subsequent |endCustomCollection| call is not received. + * When |kFilterPackagesFlag| value specified, the results are filtered only to the specified + * package names. + */ android::base::Result<void> startCustomCollection( std::chrono::nanoseconds interval, std::chrono::nanoseconds maxDuration, const std::unordered_set<std::string>& filterPackages); - // Ends the current custom collection, generates a dump, sends a looper message to start the - // periodic collection, and returns immediately. Returns an error when there is no custom - // collection running or when a dump couldn't be generated from the custom collection. + /* + * Ends the current custom collection, generates a dump, sends a looper message to start the + * periodic collection, and returns immediately. Returns an error when there is no custom + * collection running or when a dump couldn't be generated from the custom collection. + */ android::base::Result<void> endCustomCollection(int fd); // Handles the messages received by the lopper. @@ -227,8 +262,10 @@ private: // Processes the monitor events received by |handleMessage|. android::base::Result<void> processMonitorEvent(EventMetadata* metadata); - // Returns the metadata for the current collection based on |mCurrCollectionEvent|. Returns - // nullptr on invalid collection event. + /* + * Returns the metadata for the current collection based on |mCurrCollectionEvent|. Returns + * nullptr on invalid collection event. + */ EventMetadata* currCollectionMetadataLocked(); // Thread on which the actual collection happens. @@ -240,21 +277,28 @@ private: // Handler lopper to execute different collection events on the collection thread. android::sp<LooperWrapper> mHandlerLooper GUARDED_BY(mMutex); + // Current system state. + SystemState mSystemState GUARDED_BY(mMutex); + // Info for the |CollectionEvent::BOOT_TIME| collection event. EventMetadata mBoottimeCollection GUARDED_BY(mMutex); // Info for the |CollectionEvent::PERIODIC| collection event. EventMetadata mPeriodicCollection GUARDED_BY(mMutex); - // Info for the |CollectionEvent::CUSTOM| collection event. The info is cleared at the end of - // every custom collection. + /* + * Info for the |CollectionEvent::CUSTOM| collection event. The info is cleared at the end of + * every custom collection. + */ EventMetadata mCustomCollection GUARDED_BY(mMutex); // Info for the |EventType::PERIODIC| monitor event. EventMetadata mPeriodicMonitor GUARDED_BY(mMutex); - // Tracks either the WatchdogPerfService's state or current collection event. Updated on - // |start|, |onBootComplete|, |startCustomCollection|, |endCustomCollection|, and |terminate|. + /* + * Tracks either the WatchdogPerfService's state or current collection event. Updated on + * |start|, |onBootComplete|, |startCustomCollection|, |endCustomCollection|, and |terminate|. + */ EventType mCurrCollectionEvent GUARDED_BY(mMutex); // Collector/parser for `/proc/uid_io/stats`. diff --git a/cpp/watchdog/server/src/WatchdogProcessService.cpp b/cpp/watchdog/server/src/WatchdogProcessService.cpp index b84f5a22d0..97a4047531 100644 --- a/cpp/watchdog/server/src/WatchdogProcessService.cpp +++ b/cpp/watchdog/server/src/WatchdogProcessService.cpp @@ -88,7 +88,8 @@ const int32_t MSG_VHAL_HEALTH_CHECK = MSG_VHAL_WATCHDOG_ALIVE + 1; constexpr std::chrono::nanoseconds kVhalHealthCheckDelayNs = 4s; constexpr int64_t kVhalHeartBeatIntervalMs = 3000; -constexpr const char* kVhalInterfaceName = "android.hardware.automotive.vehicle@2.0::IVehicle"; +constexpr const char kServiceName[] = "WatchdogProcessService"; +constexpr const char kVhalInterfaceName[] = "android.hardware.automotive.vehicle@2.0::IVehicle"; std::chrono::nanoseconds timeoutToDurationNs(const TimeoutLength& timeout) { switch (timeout) { @@ -126,14 +127,14 @@ bool isSystemShuttingDown() { WatchdogProcessService::WatchdogProcessService(const sp<Looper>& handlerLooper) : mHandlerLooper(handlerLooper), + mIsEnabled(true), mLastSessionId(0), mServiceStarted(false), mVhalService(nullptr) { - mMessageHandler = new MessageHandlerImpl(this); - mWatchdogEnabled = true; - mBinderDeathRecipient = new BinderDeathRecipient(this); - mHidlDeathRecipient = new HidlDeathRecipient(this); - mPropertyChangeListener = new PropertyChangeListener(this); + mMessageHandler = sp<MessageHandlerImpl>::make(this); + mBinderDeathRecipient = sp<BinderDeathRecipient>::make(this); + mHidlDeathRecipient = sp<HidlDeathRecipient>::make(this); + mPropertyChangeListener = sp<PropertyChangeListener>::make(this); for (const auto& timeout : kTimeouts) { mClients.insert(std::make_pair(timeout, std::vector<ClientInfo>())); mPingedClients.insert(std::make_pair(timeout, PingedClientMap())); @@ -268,36 +269,17 @@ Status WatchdogProcessService::tellDumpFinished(const sp<aawi::ICarWatchdogMonit return Status::ok(); } -Status WatchdogProcessService::notifyPowerCycleChange(aawi::PowerCycle cycle) { - std::string buffer; +void WatchdogProcessService::setEnabled(bool isEnabled) { Mutex::Autolock lock(mMutex); - bool oldStatus = mWatchdogEnabled; - switch (cycle) { - case aawi::PowerCycle::POWER_CYCLE_SHUTDOWN: - mWatchdogEnabled = false; - buffer = "SHUTDOWN power cycle"; - break; - case aawi::PowerCycle::POWER_CYCLE_SUSPEND: - mWatchdogEnabled = false; - buffer = "SUSPEND power cycle"; - break; - case aawi::PowerCycle::POWER_CYCLE_RESUME: - mWatchdogEnabled = true; - for (const auto& timeout : kTimeouts) { - startHealthCheckingLocked(timeout); - } - buffer = "RESUME power cycle"; - break; - default: - ALOGW("Unsupported power cycle: %d", cycle); - return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, - "Unsupported power cycle"); + if (mIsEnabled != isEnabled) { + ALOGI("%s is %s", kServiceName, isEnabled ? "enabled" : "disabled"); } - ALOGI("Received %s", buffer.c_str()); - if (oldStatus != mWatchdogEnabled) { - ALOGI("Car watchdog is %s", mWatchdogEnabled ? "enabled" : "disabled"); + mIsEnabled = isEnabled; + if (mIsEnabled) { + for (const auto& timeout : kTimeouts) { + startHealthCheckingLocked(timeout); + } } - return Status::ok(); } Status WatchdogProcessService::notifyUserStateChange(userid_t userId, aawi::UserState state) { @@ -326,8 +308,8 @@ Result<void> WatchdogProcessService::dump(int fd, const Vector<String16>& /*args const char* doubleIndent = " "; std::string buffer; WriteStringToFd("CAR WATCHDOG PROCESS SERVICE\n", fd); - WriteStringToFd(StringPrintf("%sWatchdog enabled: %s\n", indent, - mWatchdogEnabled ? "true" : "false"), + WriteStringToFd(StringPrintf("%s%s enabled: %s\n", indent, kServiceName, + mIsEnabled ? "true" : "false"), fd); WriteStringToFd(StringPrintf("%sRegistered clients\n", indent), fd); int count = 1; @@ -361,7 +343,7 @@ Result<void> WatchdogProcessService::dump(int fd, const Vector<String16>& /*args void WatchdogProcessService::doHealthCheck(int what) { mHandlerLooper->removeMessages(mMessageHandler, what); - if (!isWatchdogEnabled()) { + if (Mutex::Autolock lock(mMutex); !mIsEnabled) { return; } const TimeoutLength timeout = static_cast<TimeoutLength>(what); @@ -793,11 +775,6 @@ int32_t WatchdogProcessService::getNewSessionId() { return mLastSessionId; } -bool WatchdogProcessService::isWatchdogEnabled() { - Mutex::Autolock lock(mMutex); - return mWatchdogEnabled; -} - void WatchdogProcessService::updateVhalHeartBeat(int64_t value) { bool wrongHeartBeat; { diff --git a/cpp/watchdog/server/src/WatchdogProcessService.h b/cpp/watchdog/server/src/WatchdogProcessService.h index fcc1b3d535..7fab6cb84a 100644 --- a/cpp/watchdog/server/src/WatchdogProcessService.h +++ b/cpp/watchdog/server/src/WatchdogProcessService.h @@ -78,8 +78,7 @@ public: const android::sp<android::automotive::watchdog::internal::ICarWatchdogMonitor>& monitor, int32_t pid); - virtual android::binder::Status notifyPowerCycleChange( - android::automotive::watchdog::internal::PowerCycle cycle); + virtual void setEnabled(bool isEnabled); virtual android::binder::Status notifyUserStateChange( userid_t userId, android::automotive::watchdog::internal::UserState state); @@ -200,7 +199,6 @@ private: android::base::Result<void> dumpAndKillAllProcesses( const std::vector<int32_t>& processesNotResponding, bool reportToVhal); int32_t getNewSessionId(); - bool isWatchdogEnabled(); android::base::Result<void> updateVhal( const android::hardware::automotive::vehicle::V2_0::VehiclePropValue& value); android::base::Result<void> connectToVhalLocked(); @@ -234,7 +232,7 @@ private: std::unordered_set<userid_t> mStoppedUserIds GUARDED_BY(mMutex); android::sp<android::automotive::watchdog::internal::ICarWatchdogMonitor> mMonitor GUARDED_BY(mMutex); - bool mWatchdogEnabled GUARDED_BY(mMutex); + bool mIsEnabled GUARDED_BY(mMutex); // mLastSessionId is accessed only within main thread. No need for mutual-exclusion. int32_t mLastSessionId; bool mServiceStarted; diff --git a/cpp/watchdog/server/tests/IoOveruseMonitorTest.cpp b/cpp/watchdog/server/tests/IoOveruseMonitorTest.cpp index a3081269c9..719638ade8 100644 --- a/cpp/watchdog/server/tests/IoOveruseMonitorTest.cpp +++ b/cpp/watchdog/server/tests/IoOveruseMonitorTest.cpp @@ -30,13 +30,9 @@ namespace android { namespace automotive { namespace watchdog { -constexpr size_t kTestMonitorBufferSize = 3; -constexpr int64_t KTestMinSyncWrittenBytes = 5'000; -constexpr double kTestIoOveruseWarnPercentage = 80; -constexpr std::chrono::seconds kTestMonitorInterval = 5s; - using ::android::IPCThreadState; using ::android::RefBase; +using ::android::sp; using ::android::automotive::watchdog::internal::IoOveruseAlertThreshold; using ::android::automotive::watchdog::internal::PackageIdentifier; using ::android::automotive::watchdog::internal::PackageInfo; @@ -54,6 +50,11 @@ using ::testing::UnorderedElementsAreArray; namespace { +constexpr size_t kTestMonitorBufferSize = 3; +constexpr int64_t KTestMinSyncWrittenBytes = 5'000; +constexpr double kTestIoOveruseWarnPercentage = 80; +constexpr std::chrono::seconds kTestMonitorInterval = 5s; + IoOveruseAlertThreshold toIoOveruseAlertThreshold(const int64_t durationInSeconds, const int64_t writtenBytesPerSecond) { IoOveruseAlertThreshold threshold; @@ -187,11 +188,11 @@ private: class IoOveruseMonitorTest : public ::testing::Test { protected: virtual void SetUp() { - mMockWatchdogServiceHelper = new MockWatchdogServiceHelper(); - mMockIoOveruseConfigs = new MockIoOveruseConfigs(); - mMockPackageInfoResolver = new MockPackageInfoResolver(); - mIoOveruseMonitor = new IoOveruseMonitor(mMockWatchdogServiceHelper); - mIoOveruseMonitorPeer = new internal::IoOveruseMonitorPeer(mIoOveruseMonitor); + mMockWatchdogServiceHelper = sp<MockWatchdogServiceHelper>::make(); + mMockIoOveruseConfigs = sp<MockIoOveruseConfigs>::make(); + mMockPackageInfoResolver = sp<MockPackageInfoResolver>::make(); + mIoOveruseMonitor = sp<IoOveruseMonitor>::make(mMockWatchdogServiceHelper); + mIoOveruseMonitorPeer = sp<internal::IoOveruseMonitorPeer>::make(mIoOveruseMonitor); mIoOveruseMonitorPeer->init(mMockIoOveruseConfigs, mMockPackageInfoResolver); } @@ -239,7 +240,7 @@ protected: } void executeAsUid(uid_t uid, std::function<void()> func) { - sp<ScopedChangeCallingUid> scopedChangeCallingUid = new ScopedChangeCallingUid(uid); + sp<ScopedChangeCallingUid> scopedChangeCallingUid = sp<ScopedChangeCallingUid>::make(uid); ASSERT_NO_FATAL_FAILURE(func()); } @@ -252,7 +253,8 @@ protected: TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollection) { setUpPackagesAndConfigurations(); - sp<MockResourceOveruseListener> mockResourceOveruseListener = new MockResourceOveruseListener(); + sp<MockResourceOveruseListener> mockResourceOveruseListener = + sp<MockResourceOveruseListener>::make(); ASSERT_NO_FATAL_FAILURE(executeAsUid(1001000, [&]() { ASSERT_RESULT_OK(mIoOveruseMonitor->addIoOveruseListener(mockResourceOveruseListener)); })); @@ -261,7 +263,7 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollection) { * Package "system.daemon" (UID: 1001000) exceeds warn threshold percentage of 80% but no * warning is issued as it is a native UID. */ - sp<MockUidIoStats> mockUidIoStats = new MockUidIoStats(); + sp<MockUidIoStats> mockUidIoStats = sp<MockUidIoStats>::make(); mockUidIoStats->expectDeltaStats( {{1001000, IoUsage(0, 0, /*fgWrBytes=*/70'000, /*bgWrBytes=*/20'000, 0, 0)}, {1112345, IoUsage(0, 0, /*fgWrBytes=*/35'000, /*bgWrBytes=*/15'000, 0, 0)}, @@ -274,8 +276,8 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollection) { time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); const auto [startTime, durationInSeconds] = calculateStartAndDuration(currentTime); - ASSERT_RESULT_OK( - mIoOveruseMonitor->onPeriodicCollection(currentTime, mockUidIoStats, nullptr, nullptr)); + ASSERT_RESULT_OK(mIoOveruseMonitor->onPeriodicCollection(currentTime, SystemState::NORMAL_MODE, + mockUidIoStats, nullptr, nullptr)); std::vector<PackageIoOveruseStats> expectedIoOveruseStats = {constructPackageIoOveruseStats(/*uid*=*/1001000, /*shouldNotify=*/false, @@ -311,8 +313,8 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollection) { EXPECT_CALL(*mMockWatchdogServiceHelper, latestIoOveruseStats(_)) .WillOnce(DoAll(SaveArg<0>(&actualIoOveruseStats), Return(Status::ok()))); - ASSERT_RESULT_OK( - mIoOveruseMonitor->onPeriodicCollection(currentTime, mockUidIoStats, nullptr, nullptr)); + ASSERT_RESULT_OK(mIoOveruseMonitor->onPeriodicCollection(currentTime, SystemState::NORMAL_MODE, + mockUidIoStats, nullptr, nullptr)); const auto expectedOverusingNativeStats = constructResourceOveruseStats( constructIoOveruseStats(/*isKillable=*/false, @@ -362,8 +364,8 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollection) { .WillOnce(DoAll(SaveArg<0>(&actualIoOveruseStats), Return(Status::ok()))); currentTime += (24 * 60 * 60); // Change collection time to next day. - ASSERT_RESULT_OK( - mIoOveruseMonitor->onPeriodicCollection(currentTime, mockUidIoStats, nullptr, nullptr)); + ASSERT_RESULT_OK(mIoOveruseMonitor->onPeriodicCollection(currentTime, SystemState::NORMAL_MODE, + mockUidIoStats, nullptr, nullptr)); const auto [nextDayStartTime, nextDayDuration] = calculateStartAndDuration(currentTime); expectedIoOveruseStats = @@ -389,8 +391,71 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollection) { << "\nActual: " << toString(actualIoOveruseStats); } +TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithGarageMode) { + setUpPackagesAndConfigurations(); + sp<MockResourceOveruseListener> mockResourceOveruseListener = + sp<MockResourceOveruseListener>::make(); + ASSERT_NO_FATAL_FAILURE(executeAsUid(1001000, [&]() { + ASSERT_RESULT_OK(mIoOveruseMonitor->addIoOveruseListener(mockResourceOveruseListener)); + })); + + /* + * Package "system.daemon" (UID: 1001000) exceeds warn threshold percentage of 80% but no + * warning is issued as it is a native UID. + */ + sp<MockUidIoStats> mockUidIoStats = sp<MockUidIoStats>::make(); + mockUidIoStats->expectDeltaStats( + {{1001000, IoUsage(0, 0, /*fgWrBytes=*/70'000, /*bgWrBytes=*/60'000, 0, 0)}, + {1112345, IoUsage(0, 0, /*fgWrBytes=*/35'000, /*bgWrBytes=*/15'000, 0, 0)}, + {1212345, IoUsage(0, 0, /*fgWrBytes=*/90'000, /*bgWrBytes=*/20'000, 0, 0)}}); + + ResourceOveruseStats actualOverusingNativeStats; + EXPECT_CALL(*mockResourceOveruseListener, onOveruse(_)) + .WillOnce(DoAll(SaveArg<0>(&actualOverusingNativeStats), Return(Status::ok()))); + std::vector<PackageIoOveruseStats> actualIoOveruseStats; + EXPECT_CALL(*mMockWatchdogServiceHelper, latestIoOveruseStats(_)) + .WillOnce(DoAll(SaveArg<0>(&actualIoOveruseStats), Return(Status::ok()))); + + time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + const auto [startTime, durationInSeconds] = calculateStartAndDuration(currentTime); + + ASSERT_RESULT_OK(mIoOveruseMonitor->onPeriodicCollection(currentTime, SystemState::GARAGE_MODE, + mockUidIoStats, nullptr, nullptr)); + + const auto expectedOverusingNativeStats = constructResourceOveruseStats( + constructIoOveruseStats(/*isKillable=*/false, + /*remaining=*/constructPerStateBytes(80'000, 40'000, 0), + /*written=*/constructPerStateBytes(0, 0, 130'000), + /*totalOveruses=*/1, startTime, durationInSeconds)); + EXPECT_THAT(actualOverusingNativeStats, expectedOverusingNativeStats) + << "Expected: " << expectedOverusingNativeStats.toString() + << "\nActual: " << actualOverusingNativeStats.toString(); + + const std::vector<PackageIoOveruseStats> expectedIoOveruseStats = + {constructPackageIoOveruseStats(/*uid*=*/1001000, /*shouldNotify=*/true, + /*isKillable=*/false, /*remaining=*/ + constructPerStateBytes(80'000, 40'000, 0), + /*written=*/constructPerStateBytes(0, 0, 130'000), + /*totalOveruses=*/1, startTime, durationInSeconds), + constructPackageIoOveruseStats(/*uid*=*/1112345, /*shouldNotify=*/false, + /*isKillable=*/true, /*remaining=*/ + constructPerStateBytes(70'000, 30'000, 50'000), + /*written=*/constructPerStateBytes(0, 0, 50'000), + /*totalOveruses=*/0, startTime, durationInSeconds), + // Exceeds threshold. + constructPackageIoOveruseStats(/*uid*=*/1212345, /*shouldNotify=*/true, + /*isKillable=*/true, + /*remaining=*/ + constructPerStateBytes(70'000, 30'000, 0), + /*written=*/constructPerStateBytes(0, 0, 110'000), + /*totalOveruses=*/1, startTime, durationInSeconds)}; + EXPECT_THAT(actualIoOveruseStats, UnorderedElementsAreArray(expectedIoOveruseStats)) + << "Expected: " << toString(expectedIoOveruseStats) + << "\nActual: " << toString(actualIoOveruseStats); +} + TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithZeroWriteBytes) { - sp<MockUidIoStats> mockUidIoStats = new MockUidIoStats(); + sp<MockUidIoStats> mockUidIoStats = sp<MockUidIoStats>::make(); mockUidIoStats->expectDeltaStats( {{1001000, IoUsage(10, 0, /*fgWrBytes=*/0, /*bgWrBytes=*/0, 1, 0)}, {1112345, IoUsage(0, 20, /*fgWrBytes=*/0, /*bgWrBytes=*/0, 0, 0)}, @@ -404,12 +469,13 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithZeroWriteBytes) { ASSERT_RESULT_OK( mIoOveruseMonitor->onPeriodicCollection(std::chrono::system_clock::to_time_t( std::chrono::system_clock::now()), - mockUidIoStats, nullptr, nullptr)); + SystemState::NORMAL_MODE, mockUidIoStats, + nullptr, nullptr)); } TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithSmallWrittenBytes) { setUpPackagesAndConfigurations(); - sp<MockUidIoStats> mockUidIoStats = new MockUidIoStats(); + sp<MockUidIoStats> mockUidIoStats = sp<MockUidIoStats>::make(); /* * UID 1212345 current written bytes < |KTestMinSyncWrittenBytes| so the UID's stats are not * synced. @@ -427,8 +493,8 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithSmallWrittenBytes) { time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); const auto [startTime, durationInSeconds] = calculateStartAndDuration(currentTime); - ASSERT_RESULT_OK( - mIoOveruseMonitor->onPeriodicCollection(currentTime, mockUidIoStats, nullptr, nullptr)); + ASSERT_RESULT_OK(mIoOveruseMonitor->onPeriodicCollection(currentTime, SystemState::NORMAL_MODE, + mockUidIoStats, nullptr, nullptr)); std::vector<PackageIoOveruseStats> expectedIoOveruseStats = {constructPackageIoOveruseStats(/*uid*=*/1001000, /*shouldNotify=*/false, @@ -477,8 +543,8 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithSmallWrittenBytes) { IoUsage(0, 00, /*fgWrBytes=*/KTestMinSyncWrittenBytes - 100, /*bgWrBytes=*/0, 0, 1)}}); - ASSERT_RESULT_OK( - mIoOveruseMonitor->onPeriodicCollection(currentTime, mockUidIoStats, nullptr, nullptr)); + ASSERT_RESULT_OK(mIoOveruseMonitor->onPeriodicCollection(currentTime, SystemState::NORMAL_MODE, + mockUidIoStats, nullptr, nullptr)); expectedIoOveruseStats = {constructPackageIoOveruseStats(/*uid*=*/1112345, /*shouldNotify=*/true, @@ -502,7 +568,7 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithSmallWrittenBytes) { } TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithNoPackageInfo) { - sp<MockUidIoStats> mockUidIoStats = new MockUidIoStats(); + sp<MockUidIoStats> mockUidIoStats = sp<MockUidIoStats>::make(); mockUidIoStats->expectDeltaStats( {{1001000, IoUsage(0, 0, /*fgWrBytes=*/70'000, /*bgWrBytes=*/20'000, 0, 0)}, {1112345, IoUsage(0, 0, /*fgWrBytes=*/35'000, /*bgWrBytes=*/15'000, 0, 0)}, @@ -518,7 +584,8 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicCollectionWithNoPackageInfo) { ASSERT_RESULT_OK( mIoOveruseMonitor->onPeriodicCollection(std::chrono::system_clock::to_time_t( std::chrono::system_clock::now()), - mockUidIoStats, nullptr, nullptr)); + SystemState::NORMAL_MODE, mockUidIoStats, + nullptr, nullptr)); } TEST_F(IoOveruseMonitorTest, TestOnPeriodicMonitor) { @@ -541,7 +608,7 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicMonitor) { const auto alertHandler = [&]() { isAlertReceived = true; }; // 1st polling is ignored - sp<MockProcDiskStats> mockProcDiskStats = new MockProcDiskStats(); + sp<MockProcDiskStats> mockProcDiskStats = sp<MockProcDiskStats>::make(); EXPECT_CALL(*mockProcDiskStats, deltaSystemWideDiskStats()).Times(0); ASSERT_RESULT_OK(mIoOveruseMonitor->onPeriodicMonitor(nextCollectionTime(), mockProcDiskStats, @@ -599,7 +666,8 @@ TEST_F(IoOveruseMonitorTest, TestOnPeriodicMonitor) { } TEST_F(IoOveruseMonitorTest, TestRegisterResourceOveruseListener) { - sp<MockResourceOveruseListener> mockResourceOveruseListener = new MockResourceOveruseListener(); + sp<MockResourceOveruseListener> mockResourceOveruseListener = + sp<MockResourceOveruseListener>::make(); ASSERT_RESULT_OK(mIoOveruseMonitor->addIoOveruseListener(mockResourceOveruseListener)); @@ -607,7 +675,8 @@ TEST_F(IoOveruseMonitorTest, TestRegisterResourceOveruseListener) { } TEST_F(IoOveruseMonitorTest, TestErrorsRegisterResourceOveruseListenerOnLinkToDeathError) { - sp<MockResourceOveruseListener> mockResourceOveruseListener = new MockResourceOveruseListener(); + sp<MockResourceOveruseListener> mockResourceOveruseListener = + sp<MockResourceOveruseListener>::make(); mockResourceOveruseListener->injectLinkToDeathFailure(); @@ -615,7 +684,8 @@ TEST_F(IoOveruseMonitorTest, TestErrorsRegisterResourceOveruseListenerOnLinkToDe } TEST_F(IoOveruseMonitorTest, TestUnaddIoOveruseListener) { - sp<MockResourceOveruseListener> mockResourceOveruseListener = new MockResourceOveruseListener(); + sp<MockResourceOveruseListener> mockResourceOveruseListener = + sp<MockResourceOveruseListener>::make(); ASSERT_RESULT_OK(mIoOveruseMonitor->addIoOveruseListener(mockResourceOveruseListener)); @@ -626,7 +696,8 @@ TEST_F(IoOveruseMonitorTest, TestUnaddIoOveruseListener) { } TEST_F(IoOveruseMonitorTest, TestUnaddIoOveruseListenerOnUnlinkToDeathError) { - sp<MockResourceOveruseListener> mockResourceOveruseListener = new MockResourceOveruseListener(); + sp<MockResourceOveruseListener> mockResourceOveruseListener = + sp<MockResourceOveruseListener>::make(); ASSERT_RESULT_OK(mIoOveruseMonitor->addIoOveruseListener(mockResourceOveruseListener)); @@ -637,15 +708,15 @@ TEST_F(IoOveruseMonitorTest, TestUnaddIoOveruseListenerOnUnlinkToDeathError) { TEST_F(IoOveruseMonitorTest, TestGetIoOveruseStats) { setUpPackagesAndConfigurations(); - sp<MockUidIoStats> mockUidIoStats = new MockUidIoStats(); + sp<MockUidIoStats> mockUidIoStats = sp<MockUidIoStats>::make(); mockUidIoStats->expectDeltaStats( {{1001000, IoUsage(0, 0, /*fgWrBytes=*/90'000, /*bgWrBytes=*/20'000, 0, 0)}}); time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); const auto [startTime, durationInSeconds] = calculateStartAndDuration(currentTime); - ASSERT_RESULT_OK( - mIoOveruseMonitor->onPeriodicCollection(currentTime, mockUidIoStats, nullptr, nullptr)); + ASSERT_RESULT_OK(mIoOveruseMonitor->onPeriodicCollection(currentTime, SystemState::NORMAL_MODE, + mockUidIoStats, nullptr, nullptr)); const auto expected = constructIoOveruseStats(/*isKillable=*/false, @@ -664,14 +735,15 @@ TEST_F(IoOveruseMonitorTest, TestGetIoOveruseStats) { TEST_F(IoOveruseMonitorTest, TestResetIoOveruseStats) { setUpPackagesAndConfigurations(); - sp<MockUidIoStats> mockUidIoStats = new MockUidIoStats(); + sp<MockUidIoStats> mockUidIoStats = sp<MockUidIoStats>::make(); mockUidIoStats->expectDeltaStats( {{1001000, IoUsage(0, 0, /*fgWrBytes=*/90'000, /*bgWrBytes=*/20'000, 0, 0)}}); ASSERT_RESULT_OK( mIoOveruseMonitor->onPeriodicCollection(std::chrono::system_clock::to_time_t( std::chrono::system_clock::now()), - mockUidIoStats, nullptr, nullptr)); + SystemState::NORMAL_MODE, mockUidIoStats, + nullptr, nullptr)); IoOveruseStats actual; ASSERT_NO_FATAL_FAILURE(executeAsUid(1001000, [&]() { diff --git a/cpp/watchdog/server/tests/IoPerfCollectionTest.cpp b/cpp/watchdog/server/tests/IoPerfCollectionTest.cpp index ad727b567c..85e049d9a3 100644 --- a/cpp/watchdog/server/tests/IoPerfCollectionTest.cpp +++ b/cpp/watchdog/server/tests/IoPerfCollectionTest.cpp @@ -36,6 +36,7 @@ namespace android { namespace automotive { namespace watchdog { +using ::android::sp; using ::android::base::Error; using ::android::base::ReadFdToString; using ::android::base::Result; @@ -286,8 +287,8 @@ TEST(IoPerfCollectionTest, TestPeriodicCollection) { collectorPeer.injectUidToPackageNameMapping({{1009, "mount"}}); time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - ASSERT_RESULT_OK( - collector->onPeriodicCollection(now, mockUidIoStats, mockProcStat, mockProcPidStat)); + ASSERT_RESULT_OK(collector->onPeriodicCollection(now, SystemState::NORMAL_MODE, mockUidIoStats, + mockProcStat, mockProcPidStat)); const CollectionInfo& collectionInfo = collectorPeer.getPeriodicCollectionInfo(); @@ -392,7 +393,8 @@ TEST(IoPerfCollectionTest, TestCustomCollection) { }); time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - ASSERT_RESULT_OK(collector->onCustomCollection(now, {"android.car.cts", "system_server"}, + ASSERT_RESULT_OK(collector->onCustomCollection(now, SystemState::NORMAL_MODE, + {"android.car.cts", "system_server"}, mockUidIoStats, mockProcStat, mockProcPidStat)); const CollectionInfo& collectionInfo = collectorPeer.getCustomCollectionInfo(); diff --git a/cpp/watchdog/server/tests/MockDataProcessor.h b/cpp/watchdog/server/tests/MockDataProcessor.h index 34a572e87b..d9a2600ada 100644 --- a/cpp/watchdog/server/tests/MockDataProcessor.h +++ b/cpp/watchdog/server/tests/MockDataProcessor.h @@ -37,10 +37,11 @@ public: (time_t, const wp<UidIoStats>&, const wp<ProcStat>&, const wp<ProcPidStat>&), (override)); MOCK_METHOD(android::base::Result<void>, onPeriodicCollection, - (time_t, const wp<UidIoStats>&, const wp<ProcStat>&, const wp<ProcPidStat>&), + (time_t, SystemState, const wp<UidIoStats>&, const wp<ProcStat>&, + const wp<ProcPidStat>&), (override)); MOCK_METHOD(android::base::Result<void>, onCustomCollection, - (time_t, const std::unordered_set<std::string>&, const wp<UidIoStats>&, + (time_t, SystemState, const std::unordered_set<std::string>&, const wp<UidIoStats>&, const wp<ProcStat>&, const wp<ProcPidStat>&), (override)); MOCK_METHOD(android::base::Result<void>, onPeriodicMonitor, diff --git a/cpp/watchdog/server/tests/MockWatchdogPerfService.h b/cpp/watchdog/server/tests/MockWatchdogPerfService.h index 60d165bac9..6f0fb51acf 100644 --- a/cpp/watchdog/server/tests/MockWatchdogPerfService.h +++ b/cpp/watchdog/server/tests/MockWatchdogPerfService.h @@ -28,16 +28,21 @@ namespace android { namespace automotive { namespace watchdog { -class MockWatchdogPerfService : public WatchdogPerfService { +class MockWatchdogPerfService : public WatchdogPerfServiceInterface { public: MockWatchdogPerfService() {} ~MockWatchdogPerfService() {} + MOCK_METHOD(android::base::Result<void>, registerDataProcessor, + (android::sp<IDataProcessorInterface>), (override)); MOCK_METHOD(android::base::Result<void>, start, (), (override)); MOCK_METHOD(void, terminate, (), (override)); + MOCK_METHOD(void, setSystemState, (SystemState), (override)); MOCK_METHOD(android::base::Result<void>, onBootFinished, (), (override)); MOCK_METHOD(android::base::Result<void>, onCustomCollection, (int fd, const Vector<android::String16>& args), (override)); MOCK_METHOD(android::base::Result<void>, onDump, (int fd), (override)); + MOCK_METHOD(bool, dumpHelpText, (int fd), (override)); + MOCK_METHOD(void, handleMessage, (const Message&), (override)); }; } // namespace watchdog diff --git a/cpp/watchdog/server/tests/MockWatchdogProcessService.h b/cpp/watchdog/server/tests/MockWatchdogProcessService.h index ac78b4542a..44f33770c8 100644 --- a/cpp/watchdog/server/tests/MockWatchdogProcessService.h +++ b/cpp/watchdog/server/tests/MockWatchdogProcessService.h @@ -72,8 +72,7 @@ public: monitor, int32_t pid), (override)); - MOCK_METHOD(android::binder::Status, notifyPowerCycleChange, - (android::automotive::watchdog::internal::PowerCycle cycle), (override)); + MOCK_METHOD(void, setEnabled, (bool), (override)); MOCK_METHOD(android::binder::Status, notifyUserStateChange, (userid_t userId, android::automotive::watchdog::internal::UserState state), (override)); diff --git a/cpp/watchdog/server/tests/WatchdogBinderMediatorTest.cpp b/cpp/watchdog/server/tests/WatchdogBinderMediatorTest.cpp index 64f9c07c81..642e306966 100644 --- a/cpp/watchdog/server/tests/WatchdogBinderMediatorTest.cpp +++ b/cpp/watchdog/server/tests/WatchdogBinderMediatorTest.cpp @@ -94,14 +94,15 @@ private: class WatchdogBinderMediatorTest : public ::testing::Test { protected: virtual void SetUp() { - mMockWatchdogProcessService = new MockWatchdogProcessService(); - mMockWatchdogPerfService = new MockWatchdogPerfService(); + mMockWatchdogProcessService = sp<MockWatchdogProcessService>::make(); + mMockWatchdogPerfService = sp<MockWatchdogPerfService>::make(); mWatchdogBinderMediator = - new WatchdogBinderMediator(mMockWatchdogProcessService, mMockWatchdogPerfService, - new MockWatchdogServiceHelper(), - kAddServiceFunctionStub); + sp<WatchdogBinderMediator>::make(mMockWatchdogProcessService, + mMockWatchdogPerfService, + sp<MockWatchdogServiceHelper>::make(), + kAddServiceFunctionStub); internal::WatchdogBinderMediatorPeer mediatorPeer(mWatchdogBinderMediator); - mMockIoOveruseMonitor = new MockIoOveruseMonitor(); + mMockIoOveruseMonitor = sp<MockIoOveruseMonitor>::make(); ASSERT_RESULT_OK(mediatorPeer.init(mMockIoOveruseMonitor)); } virtual void TearDown() { @@ -119,9 +120,10 @@ protected: TEST_F(WatchdogBinderMediatorTest, TestInit) { sp<WatchdogBinderMediator> mediator = - new WatchdogBinderMediator(new MockWatchdogProcessService(), - new MockWatchdogPerfService(), - new MockWatchdogServiceHelper(), kAddServiceFunctionStub); + sp<WatchdogBinderMediator>::make(sp<MockWatchdogProcessService>::make(), + sp<MockWatchdogPerfService>::make(), + sp<MockWatchdogServiceHelper>::make(), + kAddServiceFunctionStub); ASSERT_RESULT_OK(mediator->init()); @@ -132,27 +134,29 @@ TEST_F(WatchdogBinderMediatorTest, TestInit) { } TEST_F(WatchdogBinderMediatorTest, TestErrorOnInitWithNullServiceInstances) { + auto mockWatchdogProcessService = sp<MockWatchdogProcessService>::make(); + auto mockWatchdogPerfservice = sp<MockWatchdogPerfService>::make(); + auto mockWatchdogServiceHelper = sp<MockWatchdogServiceHelper>::make(); sp<WatchdogBinderMediator> mediator = - new WatchdogBinderMediator(nullptr, new MockWatchdogPerfService(), - new MockWatchdogServiceHelper(), kAddServiceFunctionStub); + sp<WatchdogBinderMediator>::make(nullptr, mockWatchdogPerfservice, + mockWatchdogServiceHelper, kAddServiceFunctionStub); EXPECT_FALSE(mediator->init().ok()) << "No error returned on nullptr watchdog process service"; mediator.clear(); - mediator = new WatchdogBinderMediator(new MockWatchdogProcessService(), nullptr, - new MockWatchdogServiceHelper(), kAddServiceFunctionStub); + mediator = sp<WatchdogBinderMediator>::make(mockWatchdogProcessService, nullptr, + mockWatchdogServiceHelper, kAddServiceFunctionStub); EXPECT_FALSE(mediator->init().ok()) << "No error returned on nullptr watchdog perf service"; mediator.clear(); - mediator = new WatchdogBinderMediator(new MockWatchdogProcessService(), - new MockWatchdogPerfService(), nullptr, - kAddServiceFunctionStub); + mediator = sp<WatchdogBinderMediator>::make(mockWatchdogProcessService, mockWatchdogPerfservice, + nullptr, kAddServiceFunctionStub); EXPECT_FALSE(mediator->init().ok()) << "No error returned on nullptr watchdog service helper"; mediator.clear(); - mediator = new WatchdogBinderMediator(nullptr, nullptr, nullptr, kAddServiceFunctionStub); + mediator = sp<WatchdogBinderMediator>::make(nullptr, nullptr, nullptr, kAddServiceFunctionStub); EXPECT_FALSE(mediator->init().ok()) << "No error returned on null services"; mediator.clear(); @@ -229,7 +233,7 @@ TEST_F(WatchdogBinderMediatorTest, TestDumpWithInvalidDumpArgs) { } TEST_F(WatchdogBinderMediatorTest, TestRegisterClient) { - sp<ICarWatchdogClient> client = new MockICarWatchdogClient(); + sp<ICarWatchdogClient> client = sp<MockICarWatchdogClient>::make(); TimeoutLength timeout = TimeoutLength::TIMEOUT_MODERATE; EXPECT_CALL(*mMockWatchdogProcessService, registerClient(client, timeout)) .WillOnce(Return(Status::ok())); @@ -238,7 +242,7 @@ TEST_F(WatchdogBinderMediatorTest, TestRegisterClient) { } TEST_F(WatchdogBinderMediatorTest, TestUnregisterClient) { - sp<ICarWatchdogClient> client = new MockICarWatchdogClient(); + sp<ICarWatchdogClient> client = sp<MockICarWatchdogClient>::make(); EXPECT_CALL(*mMockWatchdogProcessService, unregisterClient(client)) .WillOnce(Return(Status::ok())); Status status = mWatchdogBinderMediator->unregisterClient(client); @@ -246,7 +250,7 @@ TEST_F(WatchdogBinderMediatorTest, TestUnregisterClient) { } TEST_F(WatchdogBinderMediatorTest, TestTellClientAlive) { - sp<ICarWatchdogClient> client = new MockICarWatchdogClient(); + sp<ICarWatchdogClient> client = sp<MockICarWatchdogClient>::make(); EXPECT_CALL(*mMockWatchdogProcessService, tellClientAlive(client, 456)) .WillOnce(Return(Status::ok())); Status status = mWatchdogBinderMediator->tellClientAlive(client, 456); @@ -254,7 +258,7 @@ TEST_F(WatchdogBinderMediatorTest, TestTellClientAlive) { } TEST_F(WatchdogBinderMediatorTest, TestAddResourceOveruseListener) { - sp<IResourceOveruseListener> listener = new MockResourceOveruseListener(); + sp<IResourceOveruseListener> listener = sp<MockResourceOveruseListener>::make(); EXPECT_CALL(*mMockIoOveruseMonitor, addIoOveruseListener(listener)) .WillOnce(Return(Result<void>{})); @@ -264,7 +268,7 @@ TEST_F(WatchdogBinderMediatorTest, TestAddResourceOveruseListener) { } TEST_F(WatchdogBinderMediatorTest, TestErrorsAddResourceOveruseListenerOnInvalidArgs) { - sp<IResourceOveruseListener> listener = new MockResourceOveruseListener(); + sp<IResourceOveruseListener> listener = sp<MockResourceOveruseListener>::make(); EXPECT_CALL(*mMockIoOveruseMonitor, addIoOveruseListener(listener)).Times(0); ASSERT_FALSE(mWatchdogBinderMediator->addResourceOveruseListener({}, listener).isOk()) @@ -276,7 +280,7 @@ TEST_F(WatchdogBinderMediatorTest, TestErrorsAddResourceOveruseListenerOnInvalid } TEST_F(WatchdogBinderMediatorTest, TestRemoveResourceOveruseListener) { - sp<IResourceOveruseListener> listener = new MockResourceOveruseListener(); + sp<IResourceOveruseListener> listener = sp<MockResourceOveruseListener>::make(); EXPECT_CALL(*mMockIoOveruseMonitor, removeIoOveruseListener(listener)) .WillOnce(Return(Result<void>{})); @@ -306,7 +310,7 @@ TEST_F(WatchdogBinderMediatorTest, TestGetResourceOveruseStats) { } TEST_F(WatchdogBinderMediatorTest, TestErrorsGetResourceOveruseStatsOnInvalidArgs) { - sp<IResourceOveruseListener> listener = new MockResourceOveruseListener(); + sp<IResourceOveruseListener> listener = sp<MockResourceOveruseListener>::make(); EXPECT_CALL(*mMockIoOveruseMonitor, getIoOveruseStats(_)).Times(0); std::vector<ResourceOveruseStats> actual; diff --git a/cpp/watchdog/server/tests/WatchdogInternalHandlerTest.cpp b/cpp/watchdog/server/tests/WatchdogInternalHandlerTest.cpp index 47d82b75fc..92a4098402 100644 --- a/cpp/watchdog/server/tests/WatchdogInternalHandlerTest.cpp +++ b/cpp/watchdog/server/tests/WatchdogInternalHandlerTest.cpp @@ -44,6 +44,7 @@ namespace aawi = ::android::automotive::watchdog::internal; using aawi::ICarWatchdogServiceForSystem; using aawi::ICarWatchdogServiceForSystemDefault; using aawi::PackageResourceOveruseAction; +using aawi::PowerCycle; using aawi::ResourceOveruseConfiguration; using ::android::sp; using ::android::String16; @@ -58,7 +59,7 @@ namespace { class MockWatchdogBinderMediator : public WatchdogBinderMediator { public: MockWatchdogBinderMediator(const android::sp<WatchdogProcessService>& watchdogProcessService, - const android::sp<WatchdogPerfService>& watchdogPerfService, + const android::sp<WatchdogPerfServiceInterface>& watchdogPerfService, const android::sp<IWatchdogServiceHelper>& watchdogServiceHelper) : WatchdogBinderMediator(watchdogProcessService, watchdogPerfService, watchdogServiceHelper, [](const char*, const android::sp<android::IBinder>&) @@ -99,17 +100,19 @@ private: class WatchdogInternalHandlerTest : public ::testing::Test { protected: virtual void SetUp() { - mMockWatchdogProcessService = new MockWatchdogProcessService(); - mMockWatchdogPerfService = new MockWatchdogPerfService(); - mMockWatchdogServiceHelper = new MockWatchdogServiceHelper(); - mMockIoOveruseMonitor = new MockIoOveruseMonitor(); - mMockWatchdogBinderMediator = new MockWatchdogBinderMediator(mMockWatchdogProcessService, - mMockWatchdogPerfService, - mMockWatchdogServiceHelper); + mMockWatchdogProcessService = sp<MockWatchdogProcessService>::make(); + mMockWatchdogPerfService = sp<MockWatchdogPerfService>::make(); + mMockWatchdogServiceHelper = sp<MockWatchdogServiceHelper>::make(); + mMockIoOveruseMonitor = sp<MockIoOveruseMonitor>::make(); + mMockWatchdogBinderMediator = + sp<MockWatchdogBinderMediator>::make(mMockWatchdogProcessService, + mMockWatchdogPerfService, + mMockWatchdogServiceHelper); mWatchdogInternalHandler = - new WatchdogInternalHandler(mMockWatchdogBinderMediator, mMockWatchdogServiceHelper, - mMockWatchdogProcessService, mMockWatchdogPerfService, - mMockIoOveruseMonitor); + sp<WatchdogInternalHandler>::make(mMockWatchdogBinderMediator, + mMockWatchdogServiceHelper, + mMockWatchdogProcessService, + mMockWatchdogPerfService, mMockIoOveruseMonitor); } virtual void TearDown() { mMockWatchdogBinderMediator.clear(); @@ -122,7 +125,9 @@ protected: } // Sets calling UID to imitate System's process. - void setSystemCallingUid() { mScopedChangeCallingUid = new ScopedChangeCallingUid(AID_SYSTEM); } + void setSystemCallingUid() { + mScopedChangeCallingUid = sp<ScopedChangeCallingUid>::make(AID_SYSTEM); + } sp<MockWatchdogBinderMediator> mMockWatchdogBinderMediator; sp<MockWatchdogServiceHelper> mMockWatchdogServiceHelper; @@ -156,7 +161,7 @@ TEST_F(WatchdogInternalHandlerTest, TestDump) { TEST_F(WatchdogInternalHandlerTest, TestRegisterCarWatchdogService) { setSystemCallingUid(); - sp<ICarWatchdogServiceForSystem> service = new ICarWatchdogServiceForSystemDefault(); + sp<ICarWatchdogServiceForSystem> service = sp<ICarWatchdogServiceForSystemDefault>::make(); EXPECT_CALL(*mMockWatchdogServiceHelper, registerService(service)) .WillOnce(Return(Status::ok())); EXPECT_CALL(*mMockWatchdogServiceHelper, registerService(service)) @@ -168,7 +173,7 @@ TEST_F(WatchdogInternalHandlerTest, TestRegisterCarWatchdogService) { } TEST_F(WatchdogInternalHandlerTest, TestErrorOnRegisterCarWatchdogServiceWithNonSystemCallingUid) { - sp<ICarWatchdogServiceForSystem> service = new ICarWatchdogServiceForSystemDefault(); + sp<ICarWatchdogServiceForSystem> service = sp<ICarWatchdogServiceForSystemDefault>::make(); EXPECT_CALL(*mMockWatchdogServiceHelper, registerService(_)).Times(0); Status status = mWatchdogInternalHandler->registerCarWatchdogService(service); @@ -179,7 +184,7 @@ TEST_F(WatchdogInternalHandlerTest, TestErrorOnRegisterCarWatchdogServiceWithNon TEST_F(WatchdogInternalHandlerTest, TestErrorOnRegisterCarWatchdogServiceWithWatchdogServiceHelperError) { setSystemCallingUid(); - sp<ICarWatchdogServiceForSystem> service = new ICarWatchdogServiceForSystemDefault(); + sp<ICarWatchdogServiceForSystem> service = sp<ICarWatchdogServiceForSystemDefault>::make(); EXPECT_CALL(*mMockWatchdogServiceHelper, registerService(service)) .WillOnce(Return(Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Illegal state"))); @@ -190,7 +195,7 @@ TEST_F(WatchdogInternalHandlerTest, TEST_F(WatchdogInternalHandlerTest, TestUnregisterCarWatchdogService) { setSystemCallingUid(); - sp<ICarWatchdogServiceForSystem> service = new ICarWatchdogServiceForSystemDefault(); + sp<ICarWatchdogServiceForSystem> service = sp<ICarWatchdogServiceForSystemDefault>::make(); EXPECT_CALL(*mMockWatchdogServiceHelper, unregisterService(service)) .WillOnce(Return(Status::ok())); Status status = mWatchdogInternalHandler->unregisterCarWatchdogService(service); @@ -199,7 +204,7 @@ TEST_F(WatchdogInternalHandlerTest, TestUnregisterCarWatchdogService) { TEST_F(WatchdogInternalHandlerTest, TestErrorOnUnregisterCarWatchdogServiceWithNonSystemCallingUid) { - sp<ICarWatchdogServiceForSystem> service = new ICarWatchdogServiceForSystemDefault(); + sp<ICarWatchdogServiceForSystem> service = sp<ICarWatchdogServiceForSystemDefault>::make(); EXPECT_CALL(*mMockWatchdogServiceHelper, unregisterService(service)).Times(0); Status status = mWatchdogInternalHandler->unregisterCarWatchdogService(service); ASSERT_FALSE(status.isOk()) << status; @@ -207,7 +212,7 @@ TEST_F(WatchdogInternalHandlerTest, TEST_F(WatchdogInternalHandlerTest, TestErrorOnUnregisterCarWatchdogServiceWithWatchdogServiceHelperError) { setSystemCallingUid(); - sp<ICarWatchdogServiceForSystem> service = new ICarWatchdogServiceForSystemDefault(); + sp<ICarWatchdogServiceForSystem> service = sp<ICarWatchdogServiceForSystemDefault>::make(); EXPECT_CALL(*mMockWatchdogServiceHelper, unregisterService(service)) .WillOnce(Return( Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Illegal argument"))); @@ -217,7 +222,7 @@ TEST_F(WatchdogInternalHandlerTest, TEST_F(WatchdogInternalHandlerTest, TestRegisterMonitor) { setSystemCallingUid(); - sp<aawi::ICarWatchdogMonitor> monitor = new aawi::ICarWatchdogMonitorDefault(); + sp<aawi::ICarWatchdogMonitor> monitor = sp<aawi::ICarWatchdogMonitorDefault>::make(); EXPECT_CALL(*mMockWatchdogProcessService, registerMonitor(monitor)) .WillOnce(Return(Status::ok())); Status status = mWatchdogInternalHandler->registerMonitor(monitor); @@ -225,7 +230,7 @@ TEST_F(WatchdogInternalHandlerTest, TestRegisterMonitor) { } TEST_F(WatchdogInternalHandlerTest, TestErrorOnRegisterMonitorWithNonSystemCallingUid) { - sp<aawi::ICarWatchdogMonitor> monitor = new aawi::ICarWatchdogMonitorDefault(); + sp<aawi::ICarWatchdogMonitor> monitor = sp<aawi::ICarWatchdogMonitorDefault>::make(); EXPECT_CALL(*mMockWatchdogProcessService, registerMonitor(monitor)).Times(0); Status status = mWatchdogInternalHandler->registerMonitor(monitor); ASSERT_FALSE(status.isOk()) << status; @@ -233,7 +238,7 @@ TEST_F(WatchdogInternalHandlerTest, TestErrorOnRegisterMonitorWithNonSystemCalli TEST_F(WatchdogInternalHandlerTest, TestUnregisterMonitor) { setSystemCallingUid(); - sp<aawi::ICarWatchdogMonitor> monitor = new aawi::ICarWatchdogMonitorDefault(); + sp<aawi::ICarWatchdogMonitor> monitor = sp<aawi::ICarWatchdogMonitorDefault>::make(); EXPECT_CALL(*mMockWatchdogProcessService, unregisterMonitor(monitor)) .WillOnce(Return(Status::ok())); Status status = mWatchdogInternalHandler->unregisterMonitor(monitor); @@ -241,7 +246,7 @@ TEST_F(WatchdogInternalHandlerTest, TestUnregisterMonitor) { } TEST_F(WatchdogInternalHandlerTest, TestErrorOnUnregisterMonitorWithNonSystemCallingUid) { - sp<aawi::ICarWatchdogMonitor> monitor = new aawi::ICarWatchdogMonitorDefault(); + sp<aawi::ICarWatchdogMonitor> monitor = sp<aawi::ICarWatchdogMonitorDefault>::make(); EXPECT_CALL(*mMockWatchdogProcessService, unregisterMonitor(monitor)).Times(0); Status status = mWatchdogInternalHandler->unregisterMonitor(monitor); ASSERT_FALSE(status.isOk()) << status; @@ -249,7 +254,7 @@ TEST_F(WatchdogInternalHandlerTest, TestErrorOnUnregisterMonitorWithNonSystemCal TEST_F(WatchdogInternalHandlerTest, TestCarWatchdogServiceAlive) { setSystemCallingUid(); - sp<ICarWatchdogServiceForSystem> service = new ICarWatchdogServiceForSystemDefault(); + sp<ICarWatchdogServiceForSystem> service = sp<ICarWatchdogServiceForSystemDefault>::make(); std::vector clientsNotResponding = {123}; EXPECT_CALL(*mMockWatchdogProcessService, tellCarWatchdogServiceAlive(service, clientsNotResponding, 456)) @@ -261,7 +266,7 @@ TEST_F(WatchdogInternalHandlerTest, TestCarWatchdogServiceAlive) { } TEST_F(WatchdogInternalHandlerTest, TestErrorOnCarWatchdogServiceWithNonSystemCallingUid) { - sp<ICarWatchdogServiceForSystem> service = new ICarWatchdogServiceForSystemDefault(); + sp<ICarWatchdogServiceForSystem> service = sp<ICarWatchdogServiceForSystemDefault>::make(); std::vector clientsNotResponding = {123}; EXPECT_CALL(*mMockWatchdogProcessService, tellCarWatchdogServiceAlive(_, _, _)).Times(0); Status status = @@ -272,7 +277,7 @@ TEST_F(WatchdogInternalHandlerTest, TestErrorOnCarWatchdogServiceWithNonSystemCa TEST_F(WatchdogInternalHandlerTest, TestTellDumpFinished) { setSystemCallingUid(); - sp<aawi::ICarWatchdogMonitor> monitor = new aawi::ICarWatchdogMonitorDefault(); + sp<aawi::ICarWatchdogMonitor> monitor = sp<aawi::ICarWatchdogMonitorDefault>::make(); EXPECT_CALL(*mMockWatchdogProcessService, tellDumpFinished(monitor, 456)) .WillOnce(Return(Status::ok())); Status status = mWatchdogInternalHandler->tellDumpFinished(monitor, 456); @@ -280,29 +285,51 @@ TEST_F(WatchdogInternalHandlerTest, TestTellDumpFinished) { } TEST_F(WatchdogInternalHandlerTest, TestErrorOnTellDumpFinishedWithNonSystemCallingUid) { - sp<aawi::ICarWatchdogMonitor> monitor = new aawi::ICarWatchdogMonitorDefault(); + sp<aawi::ICarWatchdogMonitor> monitor = sp<aawi::ICarWatchdogMonitorDefault>::make(); EXPECT_CALL(*mMockWatchdogProcessService, tellDumpFinished(_, _)).Times(0); Status status = mWatchdogInternalHandler->tellDumpFinished(monitor, 456); ASSERT_FALSE(status.isOk()) << status; } -TEST_F(WatchdogInternalHandlerTest, TestNotifyPowerCycleChange) { +TEST_F(WatchdogInternalHandlerTest, TestNotifyPowerCycleChangeToSuspend) { setSystemCallingUid(); - aawi::StateType type = aawi::StateType::POWER_CYCLE; - EXPECT_CALL(*mMockWatchdogProcessService, - notifyPowerCycleChange(aawi::PowerCycle::POWER_CYCLE_SUSPEND)) - .WillOnce(Return(Status::ok())); + EXPECT_CALL(*mMockWatchdogProcessService, setEnabled(/*isEnabled=*/false)).Times(1); + EXPECT_CALL(*mMockWatchdogPerfService, setSystemState(SystemState::GARAGE_MODE)).Times(1); Status status = mWatchdogInternalHandler - ->notifySystemStateChange(type, - static_cast<int32_t>( - aawi::PowerCycle::POWER_CYCLE_SUSPEND), + ->notifySystemStateChange(aawi::StateType::POWER_CYCLE, + static_cast<int32_t>(PowerCycle::POWER_CYCLE_SUSPEND), + -1); + ASSERT_TRUE(status.isOk()) << status; +} + +TEST_F(WatchdogInternalHandlerTest, TestNotifyPowerCycleChangeToShutdown) { + setSystemCallingUid(); + EXPECT_CALL(*mMockWatchdogProcessService, setEnabled(/*isEnabled=*/false)).Times(1); + EXPECT_CALL(*mMockWatchdogPerfService, setSystemState(_)).Times(0); + Status status = mWatchdogInternalHandler + ->notifySystemStateChange(aawi::StateType::POWER_CYCLE, + static_cast<int32_t>( + PowerCycle::POWER_CYCLE_SHUTDOWN), + -1); + ASSERT_TRUE(status.isOk()) << status; +} + +TEST_F(WatchdogInternalHandlerTest, TestNotifyPowerCycleChangeToResume) { + setSystemCallingUid(); + EXPECT_CALL(*mMockWatchdogProcessService, setEnabled(/*isEnabled=*/true)).Times(1); + EXPECT_CALL(*mMockWatchdogPerfService, setSystemState(SystemState::NORMAL_MODE)).Times(1); + Status status = + mWatchdogInternalHandler + ->notifySystemStateChange(aawi::StateType::POWER_CYCLE, + static_cast<int32_t>(PowerCycle::POWER_CYCLE_RESUME), -1); ASSERT_TRUE(status.isOk()) << status; } TEST_F(WatchdogInternalHandlerTest, TestErrorOnNotifyPowerCycleChangeWithInvalidArgs) { - EXPECT_CALL(*mMockWatchdogProcessService, notifyPowerCycleChange(_)).Times(0); + EXPECT_CALL(*mMockWatchdogProcessService, setEnabled(_)).Times(0); + EXPECT_CALL(*mMockWatchdogPerfService, setSystemState(_)).Times(0); aawi::StateType type = aawi::StateType::POWER_CYCLE; Status status = mWatchdogInternalHandler->notifySystemStateChange(type, -1, -1); @@ -358,12 +385,12 @@ TEST_F(WatchdogInternalHandlerTest, TestNotifyBootPhaseChangeWithNonBootComplete TEST_F(WatchdogInternalHandlerTest, TestErrorOnNotifySystemStateChangeWithNonSystemCallingUid) { aawi::StateType type = aawi::StateType::POWER_CYCLE; - EXPECT_CALL(*mMockWatchdogProcessService, notifyPowerCycleChange(_)).Times(0); + EXPECT_CALL(*mMockWatchdogProcessService, setEnabled(_)).Times(0); + EXPECT_CALL(*mMockWatchdogPerfService, setSystemState(_)).Times(0); Status status = mWatchdogInternalHandler ->notifySystemStateChange(type, - static_cast<int32_t>( - aawi::PowerCycle::POWER_CYCLE_SUSPEND), + static_cast<int32_t>(PowerCycle::POWER_CYCLE_SUSPEND), -1); ASSERT_FALSE(status.isOk()) << status; } diff --git a/cpp/watchdog/server/tests/WatchdogPerfServiceTest.cpp b/cpp/watchdog/server/tests/WatchdogPerfServiceTest.cpp index 3873195228..2bc9803d71 100644 --- a/cpp/watchdog/server/tests/WatchdogPerfServiceTest.cpp +++ b/cpp/watchdog/server/tests/WatchdogPerfServiceTest.cpp @@ -39,8 +39,10 @@ namespace android { namespace automotive { namespace watchdog { +using ::android::sp; using ::android::String16; using ::android::wp; +using ::android::automotive::watchdog::internal::PowerCycle; using ::android::automotive::watchdog::testing::LooperStub; using ::android::base::Error; using ::android::base::Result; @@ -68,12 +70,12 @@ public: ~WatchdogPerfServicePeer() { service->terminate(); } void injectFakes() { - looperStub = new LooperStub(); - mockUidIoStats = new NiceMock<MockUidIoStats>(); - mockProcDiskStats = new NiceMock<MockProcDiskStats>(); - mockProcStat = new NiceMock<MockProcStat>(); - mockProcPidStat = new NiceMock<MockProcPidStat>(); - mockDataProcessor = new StrictMock<MockDataProcessor>(); + looperStub = sp<LooperStub>::make(); + mockUidIoStats = sp<NiceMock<MockUidIoStats>>::make(); + mockProcDiskStats = sp<NiceMock<MockProcDiskStats>>::make(); + mockProcStat = sp<NiceMock<MockProcStat>>::make(); + mockProcPidStat = sp<NiceMock<MockProcPidStat>>::make(); + mockDataProcessor = sp<StrictMock<MockDataProcessor>>::make(); { Mutex::Autolock lock(service->mMutex); @@ -130,9 +132,49 @@ public: } // namespace internal +namespace { + +void startPeriodicCollection(internal::WatchdogPerfServicePeer* servicePeer) { + ASSERT_NO_FATAL_FAILURE(servicePeer->injectFakes()); + + ASSERT_RESULT_OK(servicePeer->start()); + + EXPECT_CALL(*servicePeer->mockUidIoStats, collect()).Times(2); + EXPECT_CALL(*servicePeer->mockProcStat, collect()).Times(2); + EXPECT_CALL(*servicePeer->mockProcPidStat, collect()).Times(2); + EXPECT_CALL(*servicePeer->mockDataProcessor, + onBoottimeCollection(_, wp<UidIoStats>(servicePeer->mockUidIoStats), + wp<ProcStat>(servicePeer->mockProcStat), + wp<ProcPidStat>(servicePeer->mockProcPidStat))) + .Times(2); + + // Make sure the collection event changes from EventType::INIT to + // EventType::BOOT_TIME_COLLECTION. + ASSERT_RESULT_OK(servicePeer->looperStub->pollCache()); + + // Mark boot complete. + ASSERT_RESULT_OK(servicePeer->service->onBootFinished()); + + // Process |SwitchMessage::END_BOOTTIME_COLLECTION| and switch to periodic collection. + ASSERT_RESULT_OK(servicePeer->looperStub->pollCache()); + + ASSERT_EQ(servicePeer->getCurrCollectionEvent(), EventType::PERIODIC_COLLECTION) + << "Invalid collection event"; + + servicePeer->verifyAndClearExpectations(); +} + +void skipPeriodicMonitorEvents(internal::WatchdogPerfServicePeer* servicePeer) { + EXPECT_CALL(*servicePeer->mockDataProcessor, onPeriodicMonitor(_, _, _)).Times(2); + ASSERT_RESULT_OK(servicePeer->looperStub->pollCache()); + ASSERT_RESULT_OK(servicePeer->looperStub->pollCache()); +} + +} // namespace + TEST(WatchdogPerfServiceTest, TestServiceStartAndTerminate) { - sp<WatchdogPerfService> service = new WatchdogPerfService(); - sp<MockDataProcessor> mockDataProcessor = new MockDataProcessor(); + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); + sp<MockDataProcessor> mockDataProcessor = sp<MockDataProcessor>::make(); EXPECT_CALL(*mockDataProcessor, init()).Times(1); @@ -157,7 +199,7 @@ TEST(WatchdogPerfServiceTest, TestServiceStartAndTerminate) { } TEST(WatchdogPerfServiceTest, TestValidCollectionSequence) { - sp<WatchdogPerfService> service = new WatchdogPerfService(); + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); internal::WatchdogPerfServicePeer servicePeer(service); ASSERT_NO_FATAL_FAILURE(servicePeer.injectFakes()); @@ -248,7 +290,8 @@ TEST(WatchdogPerfServiceTest, TestValidCollectionSequence) { EXPECT_CALL(*servicePeer.mockProcStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockProcPidStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockDataProcessor, - onPeriodicCollection(_, uidIoStats, procStat, procPidStat)) + onPeriodicCollection(_, SystemState::NORMAL_MODE, uidIoStats, procStat, + procPidStat)) .Times(1); ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); @@ -273,7 +316,8 @@ TEST(WatchdogPerfServiceTest, TestValidCollectionSequence) { EXPECT_CALL(*servicePeer.mockProcStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockProcPidStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockDataProcessor, - onCustomCollection(_, _, uidIoStats, procStat, procPidStat)) + onCustomCollection(_, SystemState::NORMAL_MODE, _, uidIoStats, procStat, + procPidStat)) .Times(1); ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); @@ -289,7 +333,8 @@ TEST(WatchdogPerfServiceTest, TestValidCollectionSequence) { EXPECT_CALL(*servicePeer.mockProcStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockProcPidStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockDataProcessor, - onCustomCollection(_, _, uidIoStats, procStat, procPidStat)) + onCustomCollection(_, SystemState::NORMAL_MODE, _, uidIoStats, procStat, + procPidStat)) .Times(1); ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); @@ -321,7 +366,8 @@ TEST(WatchdogPerfServiceTest, TestValidCollectionSequence) { EXPECT_CALL(*servicePeer.mockProcStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockProcPidStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockDataProcessor, - onPeriodicCollection(_, uidIoStats, procStat, procPidStat)) + onPeriodicCollection(_, SystemState::NORMAL_MODE, uidIoStats, procStat, + procPidStat)) .Times(1); ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); @@ -345,7 +391,7 @@ TEST(WatchdogPerfServiceTest, TestValidCollectionSequence) { } TEST(WatchdogPerfServiceTest, TestCollectionTerminatesOnZeroEnabledCollectors) { - sp<WatchdogPerfService> service = new WatchdogPerfService(); + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); internal::WatchdogPerfServicePeer servicePeer(service); ASSERT_NO_FATAL_FAILURE(servicePeer.injectFakes()); @@ -367,7 +413,7 @@ TEST(WatchdogPerfServiceTest, TestCollectionTerminatesOnZeroEnabledCollectors) { } TEST(WatchdogPerfServiceTest, TestCollectionTerminatesOnDataCollectorError) { - sp<WatchdogPerfService> service = new WatchdogPerfService(); + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); internal::WatchdogPerfServicePeer servicePeer(service); ASSERT_NO_FATAL_FAILURE(servicePeer.injectFakes()); @@ -389,7 +435,7 @@ TEST(WatchdogPerfServiceTest, TestCollectionTerminatesOnDataCollectorError) { } TEST(WatchdogPerfServiceTest, TestCollectionTerminatesOnDataProcessorError) { - sp<WatchdogPerfService> service = new WatchdogPerfService(); + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); internal::WatchdogPerfServicePeer servicePeer(service); ASSERT_NO_FATAL_FAILURE(servicePeer.injectFakes()); @@ -417,33 +463,10 @@ TEST(WatchdogPerfServiceTest, TestCollectionTerminatesOnDataProcessorError) { } TEST(WatchdogPerfServiceTest, TestCustomCollection) { - sp<WatchdogPerfService> service = new WatchdogPerfService(); - + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); internal::WatchdogPerfServicePeer servicePeer(service); - ASSERT_NO_FATAL_FAILURE(servicePeer.injectFakes()); - - ASSERT_RESULT_OK(servicePeer.start()); - - EXPECT_CALL(*servicePeer.mockUidIoStats, collect()).Times(2); - EXPECT_CALL(*servicePeer.mockProcStat, collect()).Times(2); - EXPECT_CALL(*servicePeer.mockProcPidStat, collect()).Times(2); - EXPECT_CALL(*servicePeer.mockDataProcessor, - onBoottimeCollection(_, wp<UidIoStats>(servicePeer.mockUidIoStats), - wp<ProcStat>(servicePeer.mockProcStat), - wp<ProcPidStat>(servicePeer.mockProcPidStat))) - .Times(2); - - // Make sure the collection event changes from EventType::INIT to - // EventType::BOOT_TIME_COLLECTION. - ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); - - // Mock boot complete and switch collection event to EventType::PERIODIC_COLLECTION. - ASSERT_RESULT_OK(service->onBootFinished()); - ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); - ASSERT_EQ(servicePeer.getCurrCollectionEvent(), EventType::PERIODIC_COLLECTION) - << "Invalid collection event"; - servicePeer.verifyAndClearExpectations(); + ASSERT_NO_FATAL_FAILURE(startPeriodicCollection(&servicePeer)); // Start custom collection with filter packages option. Vector<String16> args; @@ -465,7 +488,7 @@ TEST(WatchdogPerfServiceTest, TestCustomCollection) { EXPECT_CALL(*servicePeer.mockProcStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockProcPidStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockDataProcessor, - onCustomCollection(_, + onCustomCollection(_, SystemState::NORMAL_MODE, UnorderedElementsAreArray( {"android.car.cts", "system_server"}), wp<UidIoStats>(servicePeer.mockUidIoStats), @@ -501,39 +524,16 @@ TEST(WatchdogPerfServiceTest, TestCustomCollection) { } TEST(WatchdogPerfServiceTest, TestPeriodicMonitorRequestsCollection) { - sp<WatchdogPerfService> service = new WatchdogPerfService(); - + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); internal::WatchdogPerfServicePeer servicePeer(service); - ASSERT_NO_FATAL_FAILURE(servicePeer.injectFakes()); - ASSERT_RESULT_OK(servicePeer.start()); + ASSERT_NO_FATAL_FAILURE(startPeriodicCollection(&servicePeer)); wp<UidIoStats> uidIoStats(servicePeer.mockUidIoStats); wp<IProcDiskStatsInterface> procDiskStats(servicePeer.mockProcDiskStats); wp<ProcStat> procStat(servicePeer.mockProcStat); wp<ProcPidStat> procPidStat(servicePeer.mockProcPidStat); - EXPECT_CALL(*servicePeer.mockUidIoStats, collect()).Times(2); - EXPECT_CALL(*servicePeer.mockProcStat, collect()).Times(2); - EXPECT_CALL(*servicePeer.mockProcPidStat, collect()).Times(2); - EXPECT_CALL(*servicePeer.mockDataProcessor, - onBoottimeCollection(_, uidIoStats, procStat, procPidStat)) - .Times(2); - - // Make sure the collection event changes from EventType::INIT to - // EventType::BOOT_TIME_COLLECTION. - ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); - - // Mock boot complete. - ASSERT_RESULT_OK(service->onBootFinished()); - - // Process |SwitchMessage::END_BOOTTIME_COLLECTION|. - ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); - ASSERT_EQ(servicePeer.getCurrCollectionEvent(), EventType::PERIODIC_COLLECTION) - << "Invalid collection event"; - - servicePeer.verifyAndClearExpectations(); - // Periodic monitor issuing an alert to start new collection. EXPECT_CALL(*servicePeer.mockProcDiskStats, collect()).Times(1); EXPECT_CALL(*servicePeer.mockDataProcessor, onPeriodicMonitor(_, procDiskStats, _)) @@ -553,7 +553,8 @@ TEST(WatchdogPerfServiceTest, TestPeriodicMonitorRequestsCollection) { EXPECT_CALL(*servicePeer.mockProcStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockProcPidStat, collect()).Times(1); EXPECT_CALL(*servicePeer.mockDataProcessor, - onPeriodicCollection(_, uidIoStats, procStat, procPidStat)) + onPeriodicCollection(_, SystemState::NORMAL_MODE, uidIoStats, procStat, + procPidStat)) .Times(1); ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); @@ -566,8 +567,50 @@ TEST(WatchdogPerfServiceTest, TestPeriodicMonitorRequestsCollection) { EXPECT_CALL(*servicePeer.mockDataProcessor, terminate()).Times(1); } +TEST(WatchdogPerfServiceTest, TestSystemStateSwitch) { + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); + internal::WatchdogPerfServicePeer servicePeer(service); + + ASSERT_NO_FATAL_FAILURE(startPeriodicCollection(&servicePeer)); + ASSERT_NO_FATAL_FAILURE(skipPeriodicMonitorEvents(&servicePeer)); + + EXPECT_CALL(*servicePeer.mockDataProcessor, + onPeriodicCollection(_, SystemState::NORMAL_MODE, _, _, _)) + .Times(1); + + ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); + + servicePeer.verifyAndClearExpectations(); + + ASSERT_NO_FATAL_FAILURE(skipPeriodicMonitorEvents(&servicePeer)); + + service->setSystemState(SystemState::GARAGE_MODE); + + EXPECT_CALL(*servicePeer.mockDataProcessor, + onPeriodicCollection(_, SystemState::GARAGE_MODE, _, _, _)) + .Times(1); + + ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); + + servicePeer.verifyAndClearExpectations(); + + ASSERT_NO_FATAL_FAILURE(skipPeriodicMonitorEvents(&servicePeer)); + + service->setSystemState(SystemState::NORMAL_MODE); + + EXPECT_CALL(*servicePeer.mockDataProcessor, + onPeriodicCollection(_, SystemState::NORMAL_MODE, _, _, _)) + .Times(1); + + ASSERT_RESULT_OK(servicePeer.looperStub->pollCache()); + + servicePeer.verifyAndClearExpectations(); + + EXPECT_CALL(*servicePeer.mockDataProcessor, terminate()).Times(1); +} + TEST(WatchdogPerfServiceTest, TestHandlesInvalidDumpArguments) { - sp<WatchdogPerfService> service = new WatchdogPerfService(); + sp<WatchdogPerfService> service = sp<WatchdogPerfService>::make(); Vector<String16> args; args.push_back(String16(kStartCustomCollectionFlag)); args.push_back(String16("Invalid flag")); |