diff --git a/BUILD.gn b/BUILD.gn index 90d85f3f8014da169db6263a3f46df5fe8272f6b..f812895aa7f711dc2e4d3af02ede8b432e84d078 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -41,6 +41,7 @@ ohos_shared_library("usagestatsinner") { public_configs = [ ":usagestatsinner_public_config" ] public_deps = [ ":usagestatservice" ] external_deps = [ + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", @@ -80,6 +81,7 @@ ohos_shared_library("bundlestate") { ] external_deps = [ + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", @@ -136,6 +138,7 @@ ohos_shared_library("usagestatservice") { "services/packageusage/include", "services/packagegroup/include", "interfaces/innerkits/include", + "interfaces/kits/bundlestats/napi/include", ] external_deps = [ @@ -169,36 +172,3 @@ ohos_shared_library("usagestatservice") { part_name = "${device_usage_statistics_part_name}" subsystem_name = "resourceschedule" } - -ohos_executable("deviceusagestats") { - include_dirs = [ - "services/common/include", - "services/packageusage/include", - "services/packagegroup/include", - "interfaces/innerkits/include", - "utils/dump/include", - ] - - sources = [ - "utils/dump/src/bundle_active_shell_command.cpp", - "utils/dump/src/main.cpp", - "utils/dump/src/shell_command.cpp", - ] - - deps = [ ":usagestatsinner" ] - - configs = [] - - external_deps = [ - "ability_base:want", - "ability_runtime:wantagent_innerkits", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - "utils_base:utils", - ] - - install_enable = true - part_name = "${device_usage_statistics_part_name}" -} diff --git a/bundle.json b/bundle.json index cccf5f4b1588a4a293505b2ff6e4e874bf97284c..d3893474702a7e6e4624c006b557a7e9c153063f 100644 --- a/bundle.json +++ b/bundle.json @@ -51,8 +51,7 @@ "//foundation/resourceschedule/device_usage_statistics:usagestatservice", "//foundation/resourceschedule/device_usage_statistics:device_usage_statistics_sa_profile", "//foundation/resourceschedule/device_usage_statistics:device_usage_statistics_service_init", - "//foundation/resourceschedule/device_usage_statistics:bundlestate", - "//foundation/resourceschedule/device_usage_statistics:deviceusagestats" + "//foundation/resourceschedule/device_usage_statistics:bundlestate" ], "inner_kits": [ { diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 1a15740efca198ca593a13ad09ae6ede90d1bbb6..7dce5a3d3565acbe336cdc7639c83f08c10e7634 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -48,31 +48,8 @@ void BundleActiveGroupObserver::SetCallbackInfo(const napi_env &env, const napi_ bundleGroupCallbackInfo_.ref = ref; } -template -napi_value AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) -{ - if (params.errorCode != ERR_OK) { - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - asyncCallbackInfo = new (std::nothrow) ASYNCT(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) - != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - return BundleStateCommon::NapiGetNull(env); -} - napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEventDataWorkerData, napi_value &result) { - BUNDLE_ACTIVE_LOGI("enter"); - if (!commonEventDataWorkerData) { BUNDLE_ACTIVE_LOGE("commonEventDataWorkerData is null"); return nullptr; @@ -98,7 +75,7 @@ napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEven napi_create_string_utf8( commonEventDataWorkerData->env, commonEventDataWorkerData->bundleName.c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(commonEventDataWorkerData->env, result, "bundleName", value); - BUNDLE_ACTIVE_LOGI( + BUNDLE_ACTIVE_LOGD( "RegisterGroupCallBack oldGroup=%{public}d, newGroup=%{public}d, userId=%{public}d, " "changeReason=%{public}d, bundleName=%{public}s", commonEventDataWorkerData->oldGroup, commonEventDataWorkerData->newGroup, commonEventDataWorkerData->userId, @@ -109,7 +86,7 @@ napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEven void UvQueueWorkOnBundleGroupChanged(uv_work_t *work, int status) { - BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged uv_work_t start"); + BUNDLE_ACTIVE_LOGD("OnBundleGroupChanged uv_work_t start"); if (!work) { return; } @@ -154,15 +131,13 @@ void UvQueueWorkOnBundleGroupChanged(uv_work_t *work, int status) */ void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) { - BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged start"); - + BUNDLE_ACTIVE_LOGD("OnBundleGroupChanged start"); uv_loop_s *loop = nullptr; napi_get_uv_event_loop(bundleGroupCallbackInfo_.env, &loop); if (!loop) { BUNDLE_ACTIVE_LOGE("loop instance is nullptr"); return; } - uv_work_t* work = new (std::nothrow) uv_work_t; if (!work) { BUNDLE_ACTIVE_LOGE("work is null"); @@ -185,14 +160,10 @@ void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCall callbackReceiveDataWorker->changeReason = callBackInfo->GetChangeReason(); callbackReceiveDataWorker->userId = callBackInfo->GetUserId(); callbackReceiveDataWorker->bundleName = callBackInfo->GetBundleName(); - callbackReceiveDataWorker->env = bundleGroupCallbackInfo_.env; callbackReceiveDataWorker->ref = bundleGroupCallbackInfo_.ref; work->data = (void *)callbackReceiveDataWorker; - - BUNDLE_ACTIVE_LOGI("OnReceiveEvent this = %{public}p", this); - int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnBundleGroupChanged); if (ret != 0) { delete callbackReceiveDataWorker; @@ -218,7 +189,7 @@ napi_value GetBundleGroupChangeCallback(const napi_env &env, const napi_value &v } napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info, - RegisterCallbackInfo ¶ms) + RegisterCallbackInfo ¶ms, AsyncRegisterCallbackInfo* &asyncCallbackInfo) { size_t argc = REGISTER_GROUP_CALLBACK_PARAMS; napi_value argv[REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr}; @@ -244,34 +215,22 @@ napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_ NAPI_ASSERT(env, valuetype == napi_function, "ParseStatesParameters invalid parameter type. Function expected"); napi_create_reference(env, argv[1], 1, ¶ms.callback); } + BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) { RegisterCallbackInfo params; - ParseRegisterGroupCallBackParameters(env, info, params); - + AsyncRegisterCallbackInfo *asyncCallbackInfo = nullptr; + ParseRegisterGroupCallBackParameters(env, info, params, asyncCallbackInfo); if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; - AsyncRegisterCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncRegisterCallbackInfo(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) - != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->observer = registerObserver; + napi_value promise = nullptr; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); - napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "RegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName)); NAPI_CALL(env, napi_create_async_work(env, @@ -307,7 +266,7 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) } napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info, - UnRegisterCallbackInfo ¶ms) + UnRegisterCallbackInfo ¶ms, AsyncUnRegisterCallbackInfo* &asyncCallbackInfo) { size_t argc = UN_REGISTER_GROUP_CALLBACK_PARAMS; napi_value argv[UN_REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr}; @@ -323,23 +282,26 @@ napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const nap "Function expected."); napi_create_reference(env, argv[0], 1, ¶ms.callback); } + if (!registerObserver) { + BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist"); + params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; + return BundleStateCommon::NapiGetNull(env); + } + BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) { UnRegisterCallbackInfo params; - ParseUnRegisterGroupCallBackParameters(env, info, params); - if (!registerObserver) { - BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist"); - params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; + AsyncUnRegisterCallbackInfo *asyncCallbackInfo = nullptr; + ParseUnRegisterGroupCallBackParameters(env, info, params, asyncCallbackInfo); + if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; - AsyncUnRegisterCallbackInfo *asyncCallbackInfo = nullptr; - AsyncInit(env, params, asyncCallbackInfo); std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->observer = registerObserver; + napi_value promise = nullptr; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "UnRegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName)); diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index dcefc9718700a24ca6d61b1a74c57e7330744866..9bcc0a8456a9db75cdc812a20dd5b3100f17eb6d 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -16,7 +16,6 @@ #include "securec.h" #include "bundle_active_log.h" -#include "bundle_state_inner_errors.h" #include "bundle_state_common.h" namespace OHOS { diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index b604db1f4a8cf4f25ead7bcb92d9c34966c42789..f472641ba84390a762186222276d0a37b6665865 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -247,7 +247,7 @@ napi_value IsIdleState(napi_env env, napi_callback_info info) } napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback_info &info, - PriorityGroupParamsInfo ¶ms) + PriorityGroupParamsInfo ¶ms, AsyncCallbackInfoPriorityGroup* &asyncCallbackInfo) { size_t argc = PRIORITY_GROUP_PARAMS; napi_value argv[PRIORITY_GROUP_PARAMS] = {nullptr}; @@ -288,33 +288,23 @@ napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback napi_create_reference(env, argv[1], 1, ¶ms.callback); } } + BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) { PriorityGroupParamsInfo params; - ParsePriorityGroupParameters(env, info, params); + AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = nullptr; + ParsePriorityGroupParameters(env, info, params, asyncCallbackInfo); if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; - AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = - new (std::nothrow) AsyncCallbackInfoPriorityGroup(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->bundleName = params.bundleName; - BUNDLE_ACTIVE_LOGI("QueryPackageGroup callbackPtr->bundleName: %{public}s", + BUNDLE_ACTIVE_LOGD("QueryPackageGroup callbackPtr->bundleName: %{public}s", callbackPtr->bundleName.c_str()); + napi_value promise = nullptr; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "QueryAppUsagePriorityGroup", NAPI_AUTO_LENGTH, &resourceName)); @@ -422,10 +412,10 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->beginTime = params.beginTime; - BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates callbackPtr->beginTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryCurrentBundleActiveStates callbackPtr->beginTime: %{public}lld", (long long)callbackPtr->beginTime); callbackPtr->endTime = params.endTime; - BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates callbackPtr->endTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryCurrentBundleActiveStates callbackPtr->endTime: %{public}lld", (long long)callbackPtr->endTime); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); @@ -487,10 +477,10 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->beginTime = params.beginTime; - BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates callbackPtr->beginTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleActiveStates callbackPtr->beginTime: %{public}lld", (long long)callbackPtr->beginTime); callbackPtr->endTime = params.endTime; - BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates callbackPtr->endTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleActiveStates callbackPtr->endTime: %{public}lld", (long long)callbackPtr->endTime); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); @@ -613,13 +603,13 @@ napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->intervalType = params.intervalType; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->intervalType: %{public}d", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->intervalType: %{public}d", callbackPtr->intervalType); callbackPtr->beginTime = params.beginTime; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->beginTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->beginTime: %{public}lld", (long long)callbackPtr->beginTime); callbackPtr->endTime = params.endTime; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->endTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->endTime: %{public}lld", (long long)callbackPtr->endTime); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; @@ -725,10 +715,10 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->beginTime = params.beginTime; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos callbackPtr->beginTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfos callbackPtr->beginTime: %{public}lld", (long long)callbackPtr->beginTime); callbackPtr->endTime = params.endTime; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos callbackPtr->endTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfos callbackPtr->endTime: %{public}lld", (long long)callbackPtr->endTime); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; @@ -767,9 +757,8 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) } napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const napi_callback_info &info, - ParamsBundleGroupInfo ¶ms) + ParamsBundleGroupInfo ¶ms, AsyncCallbackInfoSetBundleGroup* &asyncCallbackInfo) { - BUNDLE_ACTIVE_LOGD("enter ParseAppUsageBundleGroupInfoParameters"); size_t argc = APP_USAGE_PARAMS_BUNDLE_GROUP; napi_value argv[APP_USAGE_PARAMS_BUNDLE_GROUP] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); @@ -816,36 +805,24 @@ napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const nap "Function expected."); napi_create_reference(env, argv[SECOND_ARG], 1, ¶ms.callback); } + BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } napi_value SetBundleGroup(napi_env env, napi_callback_info info) { - BUNDLE_ACTIVE_LOGI("enter SetBundleGroup"); ParamsBundleGroupInfo params; - ParseAppUsageBundleGroupInfoParameters(env, info, params); + AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = nullptr; + ParseAppUsageBundleGroupInfoParameters(env, info, params, asyncCallbackInfo); if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; - AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = - new (std::nothrow) AsyncCallbackInfoSetBundleGroup(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) - != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->newGroup = params.newGroup; callbackPtr->bundleName = params.bundleName; - BUNDLE_ACTIVE_LOGI("SetBundleGroup, bundleName is %{public}s, newGroup is %{public}d", + BUNDLE_ACTIVE_LOGD("SetBundleGroup, bundleName is %{public}s, newGroup is %{public}d", callbackPtr->bundleName.c_str(), callbackPtr->newGroup); + napi_value promise = nullptr; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "SetBundleGroup", NAPI_AUTO_LENGTH, &resourceName)); diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index c39690379d3485cd9c0d5f358ba830ced90bc3c8..90765762a540f5065d450430e0d3f37c12e0dace 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -24,6 +24,8 @@ #include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" #include "bundle_active_module_record.h" +#include "event_handler.h" +#include "event_runner.h" namespace OHOS { namespace DeviceUsageStats { @@ -124,19 +126,41 @@ public: * return: object of BundleActiveClient. */ static BundleActiveClient& GetInstance(); - /* - * function: BundleActiveClient, default constructor. - */ - BundleActiveClient() {} - /* - * function: ~BundleActiveClient, default destructor. - */ - ~BundleActiveClient() {} +private: + class BundleActiveClientDeathRecipient : public IRemoteObject::DeathRecipient { + public: + /* + * function: BundleActiveClientDeathRecipient, default constructor. + */ + BundleActiveClientDeathRecipient() = default; + /* + * function: ~BundleActiveClientDeathRecipient, default destructor. + */ + ~BundleActiveClientDeathRecipient() = default; + /* + * function: setObserver. + */ + void setObserver(const sptr &observer); + /* + * function: OnRemoteDied, PostTask when service(bundleActiveProxy_) is died. + */ + void OnRemoteDied(const wptr &object) override; + /* + * function: OnServiceDiedInner, get bundleActiveProxy_ and registerGroupCallBack again. + */ + void OnServiceDiedInner(const wptr &object); - int32_t ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); + private: + sptr observer_ = nullptr; + }; private: bool GetBundleActiveProxy(); + BundleActiveClient() {} + ~BundleActiveClient() {} sptr bundleActiveProxy_; + sptr recipient_; + std::shared_ptr bundleClientRunner_ {nullptr}; + std::shared_ptr bundleClientHandler_ {nullptr}; std::mutex mutex_; }; } // namespace DeviceUsageStats diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 58478d4fc6540b2f9023b7ac1fa5cd0cc3b51b8f..af44281d75da3577b92882524384ac42586760fa 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -18,9 +18,8 @@ namespace OHOS { namespace DeviceUsageStats { namespace { - const int32_t EVENTS_PARAM = 5; - const int32_t PACKAGE_USAGE_PARAM = 6; - const int32_t MODULE_USAGE_PARAM = 4; + const std::string BUNDLE_ACTIVE_CLIENT_NAME = "bundleActiveName"; + static const int32_t DELAY_TIME = 5000; } BundleActiveClient& BundleActiveClient::GetInstance() { @@ -51,6 +50,19 @@ bool BundleActiveClient::GetBundleActiveProxy() BUNDLE_ACTIVE_LOGE("Failed to get BundleActiveProxy."); return false; } + if (!recipient_) { + recipient_ = new (std::nothrow) BundleActiveClientDeathRecipient(); + } + bundleClientRunner_ = AppExecFwk::EventRunner::Create(BUNDLE_ACTIVE_CLIENT_NAME); + if (!bundleClientRunner_) { + BUNDLE_ACTIVE_LOGE("BundleActiveClient runner create failed!"); + return false; + } + bundleClientHandler_ = std::make_shared(bundleClientRunner_); + if (!bundleClientHandler_) { + BUNDLE_ACTIVE_LOGE("BundleActiveClient handler create failed!"); + return false; + } return true; } @@ -140,20 +152,27 @@ int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vector &observer) { if (!GetBundleActiveProxy()) { - BUNDLE_ACTIVE_LOGE("GetBackgroundTaskManagerProxy failed."); - return false; + return -1; } int32_t result = bundleActiveProxy_->RegisterGroupCallBack(observer); + // AddDeathRecipient when RegisterGroupCallBack success + if (recipient_ && result == ERR_OK) { + recipient_->setObserver(observer); + bundleActiveProxy_->AsObject()->AddDeathRecipient(recipient_); + } return result; } int32_t BundleActiveClient::UnregisterGroupCallBack(const sptr &observer) { if (!GetBundleActiveProxy()) { - BUNDLE_ACTIVE_LOGE("GetBackgroundTaskManagerProxy failed."); - return false; + return -1; } - return bundleActiveProxy_->UnregisterGroupCallBack(observer); + int32_t result = bundleActiveProxy_->UnregisterGroupCallBack(observer); + if (recipient_) { + bundleActiveProxy_->AsObject()->RemoveDeathRecipient(recipient_); + } + return result; } int32_t BundleActiveClient::QueryEventStats(int64_t beginTime, int64_t endTime, @@ -174,53 +193,29 @@ int32_t BundleActiveClient::QueryAppNotificationNumber(int64_t beginTime, int64_ return bundleActiveProxy_->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId); } -int32_t BundleActiveClient::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) -{ - int32_t ret = -1; - - if (dumpOption[1] == "Events") { - std::vector eventResult; - if (static_cast(dumpOption.size()) != EVENTS_PARAM) { - return ret; - } - int64_t beginTime = std::stoll(dumpOption[2]); - int64_t endTime = std::stoll(dumpOption[3]); - int32_t userId = std::stoi(dumpOption[4]); - eventResult = this->QueryEvents(beginTime, endTime, ret, userId); - for (auto& oneEvent : eventResult) { - dumpInfo.emplace_back(oneEvent.ToString()); - } - } else if (dumpOption[1] == "PackageUsage") { - std::vector packageUsageResult; - if (static_cast(dumpOption.size()) != PACKAGE_USAGE_PARAM) { - return ret; - } - int32_t intervalType = std::stoi(dumpOption[2]); - int64_t beginTime = std::stoll(dumpOption[3]); - int64_t endTime = std::stoll(dumpOption[4]); - int32_t userId = std::stoi(dumpOption[5]); - packageUsageResult = this->QueryPackageStats(intervalType, beginTime, endTime, ret, userId); - for (auto& onePackageRecord : packageUsageResult) { - dumpInfo.emplace_back(onePackageRecord.ToString()); - } - } else if (dumpOption[1] == "ModuleUsage") { - std::vector moduleResult; - if (static_cast(dumpOption.size()) != MODULE_USAGE_PARAM) { - return ret; - } - int32_t maxNum = std::stoi(dumpOption[2]); - int32_t userId = std::stoi(dumpOption[3]); - BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId); - ret = this->QueryFormStatistics(maxNum, moduleResult, userId); - for (auto& oneModuleRecord : moduleResult) { - dumpInfo.emplace_back(oneModuleRecord.ToString()); - for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) { - std::string oneFormInfo = "form " + std::to_string(static_cast(i) + 1) + ", "; - dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString()); - } - } - } - return ret; +void BundleActiveClient::BundleActiveClientDeathRecipient::setObserver(const sptr &observer) +{ + if (observer) { + observer_ = observer; + } +} +void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wptr &object) +{ + if (object == nullptr) { + BUNDLE_ACTIVE_LOGE("remote object is null."); + return; + } + BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr; + BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() { + this->OnServiceDiedInner(object); + }, + DELAY_TIME); +} + +void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner(const wptr &object) +{ + while (!BundleActiveClient::GetInstance().GetBundleActiveProxy()) { } + BundleActiveClient::GetInstance().RegisterGroupCallBack(observer_); } } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp index 7b8ebce88690908661e287ffb5b0530e0cda6897..266ff17dc4d9a5a583ecf111df314a126cb89382 100644 --- a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp +++ b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp @@ -23,16 +23,15 @@ int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessagePar std::u16string descriptor = BundleActiveGroupCallbackStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack OnRemoteRequest cannot get power mgr service"); + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack OnRemoteRequest cannot get power mgr service"); return -1; } - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack BundleActiveGroupCallbackStub will switch"); switch (code) { case static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED): { std::shared_ptr groupInfo( data.ReadParcelable()); if (!groupInfo) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack ReadParcelable failed"); + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack ReadParcelable failed"); return -1; } OnBundleGroupChanged(*(groupInfo.get())); diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 1392c7d3e063d0e6c3660f1bb633bb77968e8690..69d4cd19d68665d369a9cf3de4c1827f92ed8902 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -44,7 +44,7 @@ bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName) data.WriteString(bundleName); Remote() -> SendRequest(IS_BUNDLE_IDLE, data, reply, option); int32_t result = reply.ReadInt32(); - BUNDLE_ACTIVE_LOGI("result is %{public}d", result); + BUNDLE_ACTIVE_LOGD("result is %{public}d", result); return result; } @@ -75,7 +75,7 @@ std::vector BundleActiveProxy::QueryPackageStats(const result.push_back(*tmp); } for (uint32_t i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " + BUNDLE_ACTIVE_LOGD("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " "lastTimeUsed_ is %{public}lld, lastContiniousTaskUsed_ is %{public}lld, " "totalInFrontTime_ is %{public}lld, totalContiniousTaskUsedTime_ is %{public}lld", i + 1, result[i].bundleName_.c_str(), @@ -119,7 +119,6 @@ std::vector BundleActiveProxy::QueryEvents(const int64_t begi int32_t BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) { - BUNDLE_ACTIVE_LOGI("SetBundleGroup enter bundleActiveProxy"); MessageParcel data; MessageParcel reply; MessageOption option; @@ -159,7 +158,7 @@ std::vector BundleActiveProxy::QueryCurrentPackageStat result.push_back(*tmp); } for (uint32_t i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " + BUNDLE_ACTIVE_LOGD("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " "lastTimeUsed_ is %{public}lld, lastContiniousTaskUsed_ is %{public}lld, " "totalInFrontTime_ is %{public}lld, totalContiniousTaskUsedTime_ is %{public}lld", i + 1, result[i].bundleName_.c_str(), @@ -191,7 +190,7 @@ std::vector BundleActiveProxy::QueryCurrentEvents(const int64 result.push_back(*tmp); } for (uint32_t i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents event id is %{public}d, bundle name is %{public}s," + BUNDLE_ACTIVE_LOGD("QueryCurrentEvents event id is %{public}d, bundle name is %{public}s," "time stamp is %{public}lld", result[i].eventId_, result[i].bundleName_.c_str(), (long long)result[i].timeStamp_); } @@ -237,11 +236,11 @@ int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector &observer) { if (!observer) { - BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer null"); + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer is nullptr"); return false; } MessageParcel data; @@ -277,7 +276,7 @@ int32_t BundleActiveProxy::RegisterGroupCallBack(const sptr &observer) { if (!observer) { - BUNDLE_ACTIVE_LOGE("observer null"); + BUNDLE_ACTIVE_LOGE("UnregisterGroupCallBack observer is nullptr"); return false; } MessageParcel data; @@ -287,7 +286,7 @@ int32_t BundleActiveProxy::UnregisterGroupCallBack(const sptrAsObject())) { - BUNDLE_ACTIVE_LOGE("observer write failed."); + BUNDLE_ACTIVE_LOGE("UnregisterGroupCallBack observer write failed."); return false; } Remote()->SendRequest(UNREGISTER_GROUP_CALLBACK, data, reply, option); @@ -299,7 +298,7 @@ int32_t BundleActiveProxy::QueryEventStats(int64_t beginTime, int64_t endTime, { int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_EVENT_STATS); for (const auto& singleEvent : eventStats) { - BUNDLE_ACTIVE_LOGI("name is %{public}s, eventId is %{public}d, count is %{public}d", + BUNDLE_ACTIVE_LOGD("QueryEventStats name is %{public}s, eventId is %{public}d, count is %{public}d", singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_); } return errCode; @@ -310,7 +309,7 @@ int32_t BundleActiveProxy::QueryAppNotificationNumber(int64_t beginTime, int64_t { int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_APP_NOTIFICATION_NUMBER); for (const auto& singleEvent : eventStats) { - BUNDLE_ACTIVE_LOGI("name is %{public}s, eventId is %{public}d, count is %{public}d", + BUNDLE_ACTIVE_LOGD("QueryAppNotificationNumber name is %{public}s, eventId is %{public}d, count is %{public}d", singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_); } return errCode; diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index a0f551216710e83afa8c18789fff4c379132f29e..3ac5015a617f4271157770f8765409cc0aaf9a10 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -21,6 +21,7 @@ #include "bundle_state_query.h" #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "bundle_state_inner_errors.h" namespace OHOS { namespace DeviceUsageStats { @@ -83,7 +84,29 @@ public: static std::unique_ptr HandleEventStatsInfo( AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms); + + template + static void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo); }; + +template +void BundleStateCommon::AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) +{ + if (params.errorCode != ERR_OK) { + return ; + } + asyncCallbackInfo = new (std::nothrow) ASYNCT(env); + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return ; + } + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) + != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } +} } // namespace DeviceUsageStats } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_COMMON_H diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h index 7d54aa3fb3b90dc1c3c78e56d3c863543f54a3f5..7261d2bc90e2b41b74a00b7aff9b537223ea8800 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -57,6 +57,8 @@ enum : int32_t { ERR_REPEAT_OPERATION, ERR_REGISTER_OBSERVER_IS_NULL, ERR_OBSERVER_CALLBACK_IS_INVALID, + ERR_USAGE_STATS_METHOD_CALLED_FAILED, + ERR_USAGE_STATS_INVALID_PARAM, }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index a5c96c4b18094cb7a6e551cd2bea52ec0b60b540..84079eae9aa0ce6bcb2f89f86f86dcbb7e135c26 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -434,10 +434,10 @@ describe("DeviceUsageStatisticsJsTest", function () { let newGroup = 30; bundleState.setBundleGroup(bundleName, newGroup).then( res => { console.info('BUNDLE_ACTIVE setBundleGroup promise success.'); - expect(true).assertEqual(true); + expect(false).assertEqual(true); }).catch( err => { console.info('BUNDLE_ACTIVE setBundleGroup promise failure.'); - expect(false).assertEqual(true); + expect(true).assertEqual(true); }); setTimeout(()=>{ diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index 954a28bac8ff99909618a85869607f94f85feced..ca7a6de41c338e1f6d94cdc5b798f4aebf25f833 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -28,6 +28,8 @@ #include "bundle_active_app_state_observer.h" #include "bundle_active_continuous_task_observer.h" #include "bundle_active_account_helper.h" +#include "file_ex.h" +#include "string_ex.h" namespace OHOS { namespace DeviceUsageStats { @@ -135,6 +137,7 @@ public: * return: result of UnregisterGroupCallBack, true or false. */ int32_t UnregisterGroupCallBack(const sptr &observer) override; + int32_t Dump(int32_t fd, const std::vector &args) override; protected: /** @@ -171,6 +174,8 @@ private: void QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord); void SerModuleProperties(const HapModuleInfo& hapModuleInfo, const ApplicationInfo& appInfo, const AbilityInfo& abilityInfo, BundleActiveModuleRecord& moduleRecord); + void DumpUsage(std::string &result); + int32_t ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 3ab62373c8b883864d1aab9292d582d4f41e9a58..723dd8bcafe69624a4c35cd4e9893c5ebb5c1e0a 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -70,7 +70,7 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da { std::lock_guard lock(mutex_); std::string action = data.GetWant().GetAction(); - BUNDLE_ACTIVE_LOGI("OnReceiveEvent action is %{public}s", action.c_str()); + BUNDLE_ACTIVE_LOGD("OnReceiveEvent action is %{public}s", action.c_str()); if (action == CommonEventSupport::COMMON_EVENT_SCREEN_OFF || action == CommonEventSupport::COMMON_EVENT_SCREEN_ON) { if (!activeGroupController_.expired()) { @@ -157,7 +157,7 @@ void BundleActiveCore::RegisterSubscriber() commonEventSubscriber_ = std::make_shared(subscriberInfo, bundleGroupController_, handler_); bool subscribeResult = CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); - BUNDLE_ACTIVE_LOGI("Register for events result is %{public}d", subscribeResult); + BUNDLE_ACTIVE_LOGD("Register for events result is %{public}d", subscribeResult); } void BundleActiveCore::UnRegisterSubscriber() @@ -175,12 +175,12 @@ void BundleActiveCore::Init() realTimeShot_ = timer->GetBootTimeMs(); systemTimeShot_ = GetSystemTimeMs(); bundleGroupController_ = std::make_shared(debugCore_); - BUNDLE_ACTIVE_LOGI("system time shot is %{public}lld", (long long)systemTimeShot_); + BUNDLE_ACTIVE_LOGD("system time shot is %{public}lld", (long long)systemTimeShot_); } void BundleActiveCore::InitBundleGroupController() { - BUNDLE_ACTIVE_LOGI("InitBundleGroupController called"); + BUNDLE_ACTIVE_LOGD("InitBundleGroupController called"); std::string threadName = "bundle_active_group_handler"; auto runner = AppExecFwk::EventRunner::Create(threadName); if (runner == nullptr) { @@ -219,7 +219,7 @@ void BundleActiveCore::SetHandler(const std::shared_ptr BundleActiveCore::GetUserDataAndInitializeIfNeeded(const int32_t userId, const int64_t timeStamp, const bool debug) { - BUNDLE_ACTIVE_LOGI("GetUserDataAndInitializeIfNeeded called"); + BUNDLE_ACTIVE_LOGD("GetUserDataAndInitializeIfNeeded called"); std::map>::iterator it = userStatServices_.find(userId); if (it == userStatServices_.end()) { BUNDLE_ACTIVE_LOGI("first initialize user service"); @@ -238,7 +238,7 @@ std::shared_ptr BundleActiveCore::GetUserDataAndInitial void BundleActiveCore::OnBundleUninstalled(const int32_t userId, const std::string& bundleName) { - BUNDLE_ACTIVE_LOGI("OnBundleUninstalled CALLED"); + BUNDLE_ACTIVE_LOGD("OnBundleUninstalled CALLED"); std::lock_guard lock(mutex_); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); if (timeNow == -1) { @@ -293,7 +293,7 @@ void BundleActiveCore::RestoreAllData() void BundleActiveCore::RestoreToDatabase(const int32_t userId) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabase called"); + BUNDLE_ACTIVE_LOGD("RestoreToDatabase called"); sptr timer = MiscServices::TimeServiceClient::GetInstance(); BundleActiveEvent event; event.eventId_ = BundleActiveEvent::FLUSH; @@ -308,7 +308,7 @@ void BundleActiveCore::RestoreToDatabase(const int32_t userId) void BundleActiveCore::RestoreToDatabaseLocked(const int32_t userId) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked called"); + BUNDLE_ACTIVE_LOGD("RestoreToDatabaseLocked called"); auto it = userStatServices_.find(userId); if (it != userStatServices_.end()) { it->second->RestoreStats(false); @@ -347,7 +347,7 @@ void BundleActiveCore::PreservePowerStateInfo(const int32_t eventId) void BundleActiveCore::ShutDown() { std::lock_guard lock(mutex_); - BUNDLE_ACTIVE_LOGI("ShutDown called"); + BUNDLE_ACTIVE_LOGD("ShutDown called"); sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t timeStamp = timer->GetBootTimeMs(); BundleActiveEvent event(BundleActiveEvent::SHUTDOWN, timeStamp); @@ -367,7 +367,7 @@ void BundleActiveCore::ShutDown() void BundleActiveCore::OnStatsReload() { - BUNDLE_ACTIVE_LOGI("OnStatsReload called"); + BUNDLE_ACTIVE_LOGD("OnStatsReload called"); bundleGroupController_->CheckIdleStatsOneTime(); } @@ -377,7 +377,7 @@ void BundleActiveCore::OnSystemUpdate(int32_t userId) int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId) { - BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId); + BUNDLE_ACTIVE_LOGD("CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId); sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t actualSystemTime = GetSystemTimeMs(); int64_t actualRealTime = timer->GetBootTimeMs(); @@ -386,7 +386,7 @@ int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId) if (actualSystemTime == -1 || actualRealTime == -1) { return -1; } - BUNDLE_ACTIVE_LOGI("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, " + BUNDLE_ACTIVE_LOGD("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, " "diff is %{public}lld", (long long)actualSystemTime, (long long)actualRealTime, (long long)expectedSystemTime, (long long)diffSystemTime); if (std::abs(diffSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) { @@ -415,13 +415,13 @@ int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId) void BundleActiveCore::ConvertToSystemTimeLocked(BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("ConvertToSystemTimeLocked called"); + BUNDLE_ACTIVE_LOGD("ConvertToSystemTimeLocked called"); event.timeStamp_ = std::max((int64_t)0, event.timeStamp_ - realTimeShot_) + systemTimeShot_; } void BundleActiveCore::OnUserRemoved(const int32_t userId) { - BUNDLE_ACTIVE_LOGI("OnUserRemoved called"); + BUNDLE_ACTIVE_LOGD("OnUserRemoved called"); std::lock_guard lock(mutex_); auto it = userStatServices_.find(userId); if (it == userStatServices_.end()) { @@ -463,7 +463,7 @@ void BundleActiveCore::OnUserSwitched(const int32_t userId) int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) { - BUNDLE_ACTIVE_LOGI("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_); + BUNDLE_ACTIVE_LOGD("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_); ObtainSystemEventName(event); event.PrintEvent(debugCore_); std::lock_guard lock(mutex_); @@ -481,7 +481,7 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); return 0; } - BUNDLE_ACTIVE_LOGI("report event called, bundle name %{public}s time %{public}lld userId %{public}d, " + BUNDLE_ACTIVE_LOGD("report event called, bundle name %{public}s time %{public}lld userId %{public}d, " "eventid %{public}d, in lock range", event.bundleName_.c_str(), (long long)event.timeStamp_, userId, event.eventId_); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); @@ -527,7 +527,7 @@ void BundleActiveCore::ObtainSystemEventName(BundleActiveEvent& event) int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("ReportEventToAllUserId called"); + BUNDLE_ACTIVE_LOGD("ReportEventToAllUserId called"); int64_t timeNow = CheckTimeChangeAndGetWallTime(); if (timeNow == -1) { return -1; @@ -554,14 +554,14 @@ int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) std::vector BundleActiveCore::QueryPackageStats(const int32_t userId, const int32_t intervalType, const int64_t beginTime, const int64_t endTime, std::string bundleName) { - BUNDLE_ACTIVE_LOGI("QueryPackageStats called"); + BUNDLE_ACTIVE_LOGD("QueryPackageStats called"); std::lock_guard lock(mutex_); std::vector result; int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); if (timeNow == -1) { return result; } - BUNDLE_ACTIVE_LOGI("QueryPackageStats begin time is %{public}lld, end time is %{public}lld, " + BUNDLE_ACTIVE_LOGD("QueryPackageStats begin time is %{public}lld, end time is %{public}lld, " "intervaltype is %{public}d", (long long)beginTime, (long long)endTime, intervalType); if (beginTime > timeNow || beginTime >= endTime) { BUNDLE_ACTIVE_LOGI("QueryPackageStats time span illegal"); @@ -579,7 +579,7 @@ std::vector BundleActiveCore::QueryPackageStats(const std::vector BundleActiveCore::QueryEvents(const int32_t userId, const int64_t beginTime, const int64_t endTime, std::string bundleName) { - BUNDLE_ACTIVE_LOGI("QueryEvents called"); + BUNDLE_ACTIVE_LOGD("QueryEvents called"); std::vector result; std::lock_guard lock(mutex_); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); @@ -735,7 +735,7 @@ int32_t BundleActiveCore::RegisterGroupCallBack(const AccessToken::AccessTokenID } groupChangeObservers_.emplace(tokenId, observer); AddObserverDeathRecipient(observer); - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); + BUNDLE_ACTIVE_LOGD("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); return 0; } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 437563712f0f1034795e9572104ddf1692042620..204bbf5aac90f99303b965b52aae1960ee75cf52 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -19,6 +19,7 @@ #include "accesstoken_kit.h" #include "app_mgr_interface.h" +#include "bundle_state_inner_errors.h" #include "bundle_active_event.h" #include "bundle_active_package_stats.h" #include "bundle_active_account_helper.h" @@ -33,6 +34,11 @@ static const int32_t PERIOD_BEST_SERVICE = 4; static const int32_t DELAY_TIME = 2000; static const std::string PERMITTED_PROCESS_NAME = "foundation"; static const int32_t MAXNUM_UP_LIMIT = 1000; +const int32_t EVENTS_PARAM = 5; +static constexpr int32_t NO_DUMP_PARAM_NUMS = 0; +static constexpr int32_t MIN_DUMP_PARAM_NUMS = 1; +const int32_t PACKAGE_USAGE_PARAM = 6; +const int32_t MODULE_USAGE_PARAM = 4; const std::string NEEDED_PERMISSION = "ohos.permission.BUNDLE_ACTIVE_INFO"; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); @@ -174,7 +180,6 @@ void BundleActiveService::InitContinuousSubscriber(const std::shared_ptr appManager = GetAppManagerInstance(); if (appStateObserver_ == nullptr || appManager == nullptr) { BUNDLE_ACTIVE_LOGE("SubscribeAppState appstateobserver is null, return"); @@ -185,7 +190,7 @@ bool BundleActiveService::SubscribeAppState() BUNDLE_ACTIVE_LOGE("RegisterApplicationStateObserver failed. err:%{public}d", err); return false; } - BUNDLE_ACTIVE_LOGI("RegisterApplicationStateObserver success."); + BUNDLE_ACTIVE_LOGD("RegisterApplicationStateObserver success."); return true; } @@ -247,9 +252,8 @@ int32_t BundleActiveService::ReportEvent(BundleActiveEvent& event, const int32_t bool BundleActiveService::IsBundleIdle(const std::string& bundleName) { // get uid - BUNDLE_ACTIVE_LOGI("Is bundle active called"); int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("UID is %{public}d", callingUid); // get user id int32_t userId = -1; int32_t result = -1; @@ -266,12 +270,12 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName) std::vector BundleActiveService::QueryPackageStats(const int32_t intervalType, const int64_t beginTime, const int64_t endTime, int32_t& errCode, int32_t userId) { - BUNDLE_ACTIVE_LOGI("QueryPackageStats stats called, intervaltype is %{public}d", intervalType); + BUNDLE_ACTIVE_LOGD("QueryPackageStats stats called, intervaltype is %{public}d", intervalType); std::vector result; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - BUNDLE_ACTIVE_LOGI("QueryPackageStats UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryPackageStats UID is %{public}d", callingUid); if (userId == -1) { // get userid OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); @@ -298,12 +302,11 @@ std::vector BundleActiveService::QueryPackageStats(con std::vector BundleActiveService::QueryEvents(const int64_t beginTime, const int64_t endTime, int32_t& errCode, int32_t userId) { - BUNDLE_ACTIVE_LOGI("QueryEvents stats called"); std::vector result; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - BUNDLE_ACTIVE_LOGI("QueryEvents UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryEvents UID is %{public}d", callingUid); if (userId == -1) { // get userid OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); @@ -364,17 +367,16 @@ int32_t BundleActiveService::SetBundleGroup(const std::string& bundleName, int32 std::vector BundleActiveService::QueryCurrentPackageStats(const int32_t intervalType, const int64_t beginTime, const int64_t endTime) { - BUNDLE_ACTIVE_LOGI("QueryCurrentPackageStats stats called"); std::vector result; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - BUNDLE_ACTIVE_LOGI("UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("UID is %{public}d", callingUid); // get userid int32_t userId = -1; OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("QueryCurrentPackageStats userid is %{public}d", userId); + BUNDLE_ACTIVE_LOGD("QueryCurrentPackageStats userid is %{public}d", userId); if (!GetBundleMgrProxy()) { BUNDLE_ACTIVE_LOGE("get bundle manager proxy failed!"); return result; @@ -396,11 +398,10 @@ std::vector BundleActiveService::QueryCurrentPackageSt std::vector BundleActiveService::QueryCurrentEvents(const int64_t beginTime, const int64_t endTime) { - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents stats called"); std::vector result; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryCurrentEvents UID is %{public}d", callingUid); // get userid int32_t userId = -1; OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); @@ -417,7 +418,7 @@ std::vector BundleActiveService::QueryCurrentEvents(const int result = bundleActiveCore_->QueryEvents(userId, beginTime, endTime, bundleName); } } - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents result size is %{public}zu", result.size()); + BUNDLE_ACTIVE_LOGD("QueryCurrentEvents result size is %{public}zu", result.size()); return result; } @@ -555,7 +556,7 @@ int32_t BundleActiveService::QueryFormStatistics(int32_t maxNum, std::vector& eventStats, int32_t userId) { int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("QueryEventStats UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryEventStats UID is %{public}d", callingUid); // get userid when userId is -1 int32_t errCode = 0; if (userId == -1) { @@ -603,7 +604,7 @@ int32_t BundleActiveService::QueryEventStats(int64_t beginTime, int64_t endTime, errCode = bundleActiveCore_->QueryEventStats(beginTime, endTime, eventStats, userId); } } - BUNDLE_ACTIVE_LOGI("QueryEventStats result size is %{public}zu", eventStats.size()); + BUNDLE_ACTIVE_LOGD("QueryEventStats result size is %{public}zu", eventStats.size()); return errCode; } @@ -611,7 +612,7 @@ int32_t BundleActiveService::QueryAppNotificationNumber(int64_t beginTime, int64 std::vector& eventStats, int32_t userId) { int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryAppNotificationNumber UID is %{public}d", callingUid); // get userid when userId is -1 int32_t errCode = 0; if (userId == -1) { @@ -642,13 +643,13 @@ void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& modul ApplicationInfo appInfo; if (!sptrBundleMgr_->GetApplicationInfo(moduleRecord.bundleName_, ApplicationFlag::GET_BASIC_APPLICATION_INFO, moduleRecord.userId_, appInfo)) { - BUNDLE_ACTIVE_LOGW("GetApplicationInfo failed!"); + BUNDLE_ACTIVE_LOGE("GetApplicationInfo failed!"); return; } BundleInfo bundleInfo; if (!sptrBundleMgr_->GetBundleInfo(moduleRecord.bundleName_, BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, moduleRecord.userId_)) { - BUNDLE_ACTIVE_LOGW("GetBundleInfo failed!"); + BUNDLE_ACTIVE_LOGE("GetBundleInfo failed!"); return; } for (const auto & oneModuleInfo : bundleInfo.hapModuleInfos) { @@ -679,6 +680,100 @@ void BundleActiveService::SerModuleProperties(const HapModuleInfo& hapModuleInfo moduleRecord.abilityIconId_ = abilityInfo.iconId; moduleRecord.installFreeSupported_ = hapModuleInfo.installationFree; } + +int32_t BundleActiveService::Dump(int32_t fd, const std::vector &args) +{ + std::vector argsInStr; + std::transform(args.begin(), args.end(), std::back_inserter(argsInStr), + [](const std::u16string &arg) { + return Str16ToStr8(arg); + }); + std::string result; + int32_t ret = ERR_OK; + if (argsInStr.size() == NO_DUMP_PARAM_NUMS) { + DumpUsage(result); + } else if (argsInStr.size() >= MIN_DUMP_PARAM_NUMS) { + std::vector infos; + if (argsInStr[0] == "-h") { + DumpUsage(result); + } else if (argsInStr[0] == "-A") { + ret = ShellDump(argsInStr, infos); + } else { + infos.emplace_back("BundleActiveService Error params.\n"); + ret = ERR_USAGE_STATS_INVALID_PARAM; + } + for (auto info : infos) { + result.append(info); + } + } + if (!SaveStringToFd(fd, result)) { + BUNDLE_ACTIVE_LOGE("BundleActiveService dump save string to fd failed!"); + ret = ERR_USAGE_STATS_METHOD_CALLED_FAILED; + } + return ret; +} + +int32_t BundleActiveService::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) +{ + int32_t ret = -1; + + if (dumpOption[1] == "Events") { + std::vector eventResult; + if (static_cast(dumpOption.size()) != EVENTS_PARAM) { + return ret; + } + int64_t beginTime = std::stoll(dumpOption[2]); + int64_t endTime = std::stoll(dumpOption[3]); + int32_t userId = std::stoi(dumpOption[4]); + eventResult = this->QueryEvents(beginTime, endTime, ret, userId); + for (auto& oneEvent : eventResult) { + dumpInfo.emplace_back(oneEvent.ToString()); + } + } else if (dumpOption[1] == "PackageUsage") { + std::vector packageUsageResult; + if (static_cast(dumpOption.size()) != PACKAGE_USAGE_PARAM) { + return ret; + } + int32_t intervalType = std::stoi(dumpOption[2]); + int64_t beginTime = std::stoll(dumpOption[3]); + int64_t endTime = std::stoll(dumpOption[4]); + int32_t userId = std::stoi(dumpOption[5]); + packageUsageResult = this->QueryPackageStats(intervalType, beginTime, endTime, ret, userId); + for (auto& onePackageRecord : packageUsageResult) { + dumpInfo.emplace_back(onePackageRecord.ToString()); + } + } else if (dumpOption[1] == "ModuleUsage") { + std::vector moduleResult; + if (static_cast(dumpOption.size()) != MODULE_USAGE_PARAM) { + return ret; + } + int32_t maxNum = std::stoi(dumpOption[2]); + int32_t userId = std::stoi(dumpOption[3]); + BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId); + ret = this->QueryFormStatistics(maxNum, moduleResult, userId); + for (auto& oneModuleRecord : moduleResult) { + dumpInfo.emplace_back(oneModuleRecord.ToString()); + for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) { + std::string oneFormInfo = "form " + std::to_string(static_cast(i) + 1) + ", "; + dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString()); + } + } + } + return ret; +} + +void BundleActiveService::DumpUsage(std::string &result) +{ + std::string dumpHelpMsg = + "usage: bundleactive dump []\n" + "options list:\n" + " -h help menu\n" + " -A \n" + " Events [beginTime] [endTime] [userId] get events for one user\n" + " PackageUsage [intervalType] [beginTime] [endTime] [userId] get package usage for one user\n" + " ModuleUsage [maxNum] [userId] get module usage for one user\n"; + result.append(dumpHelpMsg); +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index e5e9811a302e7118abcb9e9092154f4bfd28d449..650743041f38e061fc5fb8e08dc8da34fc4a31ab 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -38,6 +38,7 @@ ohos_unittest("DeviceUsageStatsTest") { ] external_deps = [ + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "power_manager_native:powermgr_client",