diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h index d3caa42ea5c57ae4c1616808233a57b7a0815a70..2e3bd8c1bfed63c7b52c341cefd83c765f409b31 100644 --- a/services/common/include/bundle_active_constant.h +++ b/services/common/include/bundle_active_constant.h @@ -59,7 +59,7 @@ const int BOOT_BASED_DURATION_COLUMN_INDEX = 0; const int SCREEN_ON_DURATION_COLUMN_INDEX = 1; const int DURATION_FLAG_COLUMN_INDEX = 2; const int TWO_SECONDS = 2 * 1000; -const int64_t SIX_DAY_IN_MILLIS_MAX = 6 * 24 * 60 * 60 * 1000; +const int64_t SIX_DAY_IN_MILLIS_MAX = 1 * 6 * 10 * 60 * 1000; const int64_t LAST_TIME_IN_MILLIS_MIN = 0; const int64_t EVENT_TIME_IN_MILLIS_MIN = 0; const int64_t EVENT_BEGIN_TIME_INITIAL_VALUE = -1; diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 1956dc510ccb8fa3d437a4709fe7b1d93bf7c05e..a9b686829e11192c1d1bd21b23eca5b61e16597c 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -60,7 +60,7 @@ public: /* * function: OnStatsChanged, report flush to disk, end_of_day event to service. */ - void OnStatsChanged() override; + void OnStatsChanged(const int userId) override; /* * function: OnStatsChanged, when device reboot after more than one day, BundleActiveUserService * will use it to flush group info. @@ -91,10 +91,10 @@ public: * function: SetHandler, BundleActiveService call it to set event report handler */ void SetHandler(const std::shared_ptr& reportHandler); - // flush database. - void RestoreToDatabase(); - // flush database - void RestoreToDatabaseLocked(); + // flush database for one user data + void RestoreToDatabase(const int userId); + // flush database for one user data + void RestoreToDatabaseLocked(const int userId); // called when device shutdown, update the in-memory stat and flush the database. void ShutDown(); // query the package stat for calling user. @@ -108,7 +108,7 @@ public: // query the app group for calling app. int QueryPackageGroup(const int userId, const std::string bundleName); // get the wall time and check if the wall time is changed. - int64_t CheckTimeChangeAndGetWallTime(); + int64_t CheckTimeChangeAndGetWallTime(int userId = 0); // convert event timestamp from boot based time to wall time. void ConvertToSystemTimeLocked(BundleActiveEvent& event); // get or create BundleActiveUserService object for specifice user. @@ -122,6 +122,7 @@ public: void GetAllActiveUser(std::vector &osAccountInfos); // when service stop, call it to unregister commen event and shutdown call back. void UnRegisterSubscriber(); + int64_t GetSystemTimeMs(); private: static const int64_t FLUSH_INTERVAL = TWO_MINUTE; @@ -138,6 +139,7 @@ private: std::map> userStatServices_; void RegisterSubscriber(); std::shared_ptr commonEventSubscriber_; + void RestoreAllData(); }; } } diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h index 345a247a40e23f41d44734ef54a719a3c0c13148..f52a995c3d5046667ff34c34aa071c930d259774 100644 --- a/services/common/include/bundle_active_usage_database.h +++ b/services/common/include/bundle_active_usage_database.h @@ -81,6 +81,7 @@ private: void DeleteUninstalledInfo(const int userId, const std::string& bundleName, const std::string& tableName, unsigned int databaseType); int32_t CreateDatabasePath(); + int64_t GetSystemTimeMs(); private: std::vector databaseFiles_; diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 5f09345ebfd4174517bbd07d0b47d6d3450f5fe7..665887bd7ff007d5c6d583737a209db74e65bcb1 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -127,10 +127,10 @@ void BundleActiveCore::Init() sptr timer = MiscServices::TimeServiceClient::GetInstance(); do { realTimeShot_ = timer->GetBootTimeMs(); - systemTimeShot_ = timer->GetWallTimeMs(); + systemTimeShot_ = GetSystemTimeMs(); } while (realTimeShot_ == -1 && systemTimeShot_ == -1); realTimeShot_ = timer->GetBootTimeMs(); - systemTimeShot_ = timer->GetWallTimeMs(); + systemTimeShot_ = GetSystemTimeMs(); bundleGroupController_ = std::make_shared(); BUNDLE_ACTIVE_LOGI("system time shot is %{public}lld", systemTimeShot_); } @@ -190,7 +190,7 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string& { BUNDLE_ACTIVE_LOGI("BundleActiveCore::OnBundleUninstalled CALLED"); std::lock_guard lock(mutex_); - int64_t timeNow = CheckTimeChangeAndGetWallTime(); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); auto service = GetUserDataAndInitializeIfNeeded(userId, timeNow); if (service == nullptr) { return; @@ -199,31 +199,21 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string& bundleGroupController_->OnBundleUninstalled(userId, bundleName); } -void BundleActiveCore::OnStatsChanged() +void BundleActiveCore::OnStatsChanged(const int userId) { - auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); if (!handler_.expired()) { BUNDLE_ACTIVE_LOGI("BundleActiveCore::OnStatsChanged send flush to disk event"); + BundleActiveReportHandlerObject tmpHandlerObject; + tmpHandlerObject.userId_ = userId; + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, handlerobjToPtr); handler_.lock()->SendEvent(event, FLUSH_INTERVAL); } } -void BundleActiveCore::RestoreToDatabase() +void BundleActiveCore::RestoreAllData() { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabase called"); - std::lock_guard lock(mutex_); - sptr timer = MiscServices::TimeServiceClient::GetInstance(); - BundleActiveEvent event; - event.eventId_ = BundleActiveEvent::FLUSH; - event.timeStamp_ = timer->GetBootTimeMs(); - event.abilityId_ = ""; - ReportEventToAllUserId(event); - RestoreToDatabaseLocked(); -} - -void BundleActiveCore::RestoreToDatabaseLocked() -{ - BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked called"); for (std::map>::iterator it = userStatServices_.begin(); it != userStatServices_.end(); it++) { std::shared_ptr service = it->second; @@ -231,7 +221,7 @@ void BundleActiveCore::RestoreToDatabaseLocked() BUNDLE_ACTIVE_LOGI("service in BundleActiveCore::RestoreToDatabaseLocked() is null"); } BUNDLE_ACTIVE_LOGI("userid is %{public}d ", service->userId_); - service->RestoreStats(); + service->RestoreStats(true); if (bundleGroupController_ != nullptr && bundleGroupController_->bundleUserHistory_ != nullptr) { bundleGroupController_->RestoreToDatabase(it->first); } @@ -245,6 +235,40 @@ void BundleActiveCore::RestoreToDatabaseLocked() } } +void BundleActiveCore::RestoreToDatabase(const int userId) +{ + BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabase called"); + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + BundleActiveEvent event; + event.eventId_ = BundleActiveEvent::FLUSH; + event.timeStamp_ = GetSystemTimeMs(); + event.abilityId_ = ""; + auto it = userStatServices_.find(userId); + if (it != userStatServices_.end()) { + it->second->ReportEvent(event); + } + if (bundleGroupController_ != nullptr) { + bundleGroupController_->RestoreDurationToDatabase(); + } + RestoreToDatabaseLocked(userId); +} + +void BundleActiveCore::RestoreToDatabaseLocked(const int userId) +{ + BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked called"); + auto it = userStatServices_.find(userId); + if (it != userStatServices_.end()) { + it->second->RestoreStats(false); + } + if (bundleGroupController_ != nullptr) { + bundleGroupController_->RestoreDurationToDatabase(); + } + if (!handler_.expired()) { + BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked remove flush to disk event"); + handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); + } +} + void BundleActiveCore::ShutDown() { BUNDLE_ACTIVE_LOGI("BundleActiveCore::ShutDown called"); @@ -255,7 +279,7 @@ void BundleActiveCore::ShutDown() event.bundleName_ = BundleActiveEvent::DEVICE_EVENT_PACKAGE_NAME; bundleGroupController_->ShutDown(timeStamp); ReportEventToAllUserId(event); - RestoreToDatabaseLocked(); + RestoreAllData(); } void BundleActiveCore::OnStatsReload() @@ -268,22 +292,33 @@ void BundleActiveCore::OnSystemUpdate(int userId) { } -int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime() +int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int userId) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::CheckTimeChangeAndGetWallTime called"); + BUNDLE_ACTIVE_LOGI("BundleActiveCore::CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t actualSystemTime = timer->GetWallTimeMs(); + int64_t actualSystemTime = GetSystemTimeMs(); int64_t actualRealTime = timer->GetBootTimeMs(); int64_t expectedSystemTime = (actualRealTime - realTimeShot_) + systemTimeShot_; int64_t diffSystemTime = actualSystemTime - expectedSystemTime; + BUNDLE_ACTIVE_LOGI("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, " + "diff is %{public}lld", + actualSystemTime, actualRealTime, expectedSystemTime, diffSystemTime); if (std::abs(diffSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) { // 时区变换逻辑 - BUNDLE_ACTIVE_LOGI("time changed!"); - for (std::map>::iterator it = userStatServices_.begin(); - it != userStatServices_.end(); it++) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::CheckTimeChangeAndGetWallTime in update time loop"); - std::shared_ptr service = it->second; - service->RenewTableTime(expectedSystemTime, actualSystemTime); + auto it = userStatServices_.find(userId); + if (it != userStatServices_.end()) { + BundleActiveEvent event; + event.eventId_ = BundleActiveEvent::FLUSH; + event.timeStamp_ = expectedSystemTime; + event.abilityId_ = ""; + it->second->ReportEvent(event); + it->second->RestoreStats(true); + it->second->RenewTableTime(expectedSystemTime, actualSystemTime); + it->second->LoadActiveStats(actualSystemTime, true, true); + if (!handler_.expired()) { + BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked remove flush to disk event"); + handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); + } } realTimeShot_ = actualRealTime; systemTimeShot_ = actualSystemTime; @@ -314,11 +349,14 @@ void BundleActiveCore::OnUserRemoved(const int userId) int BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int userId) { std::lock_guard lock(mutex_); + if (userId == 0) { + return -1; + } BUNDLE_ACTIVE_LOGI("BundleActiveCore::ReportEvent called"); BUNDLE_ACTIVE_LOGI("report event called bundle name %{public}s time %{public}lld userId %{public}d, " "eventid %{public}d, in lock range", event.bundleName_.c_str(), event.timeStamp_, userId, event.eventId_); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t timeNow = CheckTimeChangeAndGetWallTime(); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); ConvertToSystemTimeLocked(event); std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow); @@ -348,7 +386,7 @@ int BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) } BUNDLE_ACTIVE_LOGI("BundleActiveCore::ReportEventToAllUserId SERVICE user ID IS userId %{public}d", service->userId_); - service->ReportForFlushAndShutdown(event); + service->ReportForShutdown(event); return 0; } return 0; @@ -360,7 +398,7 @@ std::vector BundleActiveCore::QueryPackageStats(const BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryPackageStats called"); std::lock_guard lock(mutex_); std::vector result; - int64_t timeNow = CheckTimeChangeAndGetWallTime(); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryPackageStats begin time is %{public}lld, end time is %{public}lld, " "intervaltype is %{public}d", beginTime, endTime, intervalType); if (beginTime > timeNow || beginTime >= endTime) { @@ -382,7 +420,7 @@ std::vector BundleActiveCore::QueryEvents(const int userId, c BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryEvents called"); std::vector result; std::lock_guard lock(mutex_); - int64_t timeNow = CheckTimeChangeAndGetWallTime(); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); if (beginTime > timeNow || beginTime >= endTime) { return result; } @@ -424,5 +462,23 @@ void BundleActiveCore::GetAllActiveUser(std::vector(now) < 0) { + BUNDLE_ACTIVE_LOGE("Get now time error"); + return 0; + } + auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now); + auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch()); + int64_t tarDate = tarDuration.count(); + if (tarDate < 0) { + BUNDLE_ACTIVE_LOGE("tarDuration is less than 0."); + return -1; + } + return static_cast(tarDate); +} +} } -} \ No newline at end of file diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 9b7bfd26662bbd3b9cbac0a797f3e3e7b34d34e5..412bd31835a6ccaddc006f3920dc1c5c1dcc39ed 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -164,20 +164,26 @@ bool BundleActiveService::SubscribeContinuousTask() return true; } + void BundleActiveService::OnStop() { if (shutdownCallback_ != nullptr) { auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); powerManagerClient.UnRegisterShutdownCallback(shutdownCallback_); + delete shutdownCallback_; + shutdownCallback_ = nullptr; } else { shutdownCallback_ = new BundleActiveShutdownCallbackService(bundleActiveCore_); } auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); powerManagerClient.UnRegisterShutdownCallback(shutdownCallback_); bundleActiveCore_->UnRegisterSubscriber(); + delete shutdownCallback_; + shutdownCallback_ = nullptr; BUNDLE_ACTIVE_LOGI("[Server] OnStop"); } + int BundleActiveService::ReportEvent(std::string& bundleName, std::string& abilityName, std::string abilityId, const std::string& continuousTask, const int userId, const int eventId) { diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 9a378e53c7dee6f4d000bc7540d298a12ee2cf02..f6cd89c3b7a74839b1303a6f4e662152a9010ef9 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -683,8 +683,12 @@ void BundleActiveUsageDatabase::FlushPackageInfo(unsigned int databaseType, cons queryCondition.push_back(iter->first); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_BUNDLE_STARTED_COUNT, iter->second->bundleStartedCount_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME, (iter->second->lastTimeUsed_ - stats.beginTime_)); - valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_ - - stats.beginTime_)); + if (iter->second->lastContiniousTaskUsed_ == -1) { + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_)); + } else { + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_ - + stats.beginTime_)); + } valuesBucket.PutLong(BUNDLE_ACTIVE_DB_TOTAL_TIME, iter->second->totalInFrontTime_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_TOTAL_TIME_CONTINUOUS_TASK, iter->second->totalContiniousTaskUsedTime_); rdbStore->Update(changeRow, tableName, valuesBucket, "userId = ? and bundleName = ?", queryCondition); @@ -741,7 +745,11 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed); usageStats->lastTimeUsed_ = relativeLastTimeUsed + currentPackageTime; bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed); - usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + currentPackageTime; + if (relativeLastTimeFrontServiceUsed == -1) { + usageStats->lastContiniousTaskUsed_ = -1; + } else { + usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + currentPackageTime; + } bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats->totalInFrontTime_); bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX, usageStats->totalContiniousTaskUsedTime_); bundleStats.insert(pair>(usageStats->bundleName_, @@ -753,7 +761,7 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa eventBeginTime_ = currentPackageTime; } sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t systemTime = timer->GetWallTimeMs(); + int64_t systemTime = GetSystemTimeMs(); intervalStats->lastTimeSaved_ = systemTime; return intervalStats; } @@ -936,6 +944,7 @@ void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime) vector tableArray = sortedTableArray_.at(i); for (unsigned int j = 0; j < tableArray.size(); j++) { int64_t newTime = tableArray.at(j) + changedTime; + BUNDLE_ACTIVE_LOGI("new table time is %{public}lld", newTime); if (newTime < 0) { DeleteInvalidTable(i, tableArray.at(j)); } else { @@ -990,7 +999,7 @@ void BundleActiveUsageDatabase::UpdateUsageData(int32_t databaseType, BundleActi } FlushPackageInfo(databaseType, stats); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t systemTime = timer->GetWallTimeMs(); + int64_t systemTime = GetSystemTimeMs(); stats.lastTimeSaved_ = systemTime; } @@ -1073,7 +1082,11 @@ vector BundleActiveUsageDatabase::QueryDatabaseUsageSt bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed); usageStats.lastTimeUsed_ = relativeLastTimeUsed + packageTableTime; bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed); - usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + packageTableTime; + if (relativeLastTimeFrontServiceUsed == -1) { + usageStats.lastContiniousTaskUsed_ = -1; + } else { + usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + packageTableTime; + } bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats.totalInFrontTime_); bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX, usageStats.totalContiniousTaskUsedTime_); @@ -1179,5 +1192,23 @@ void BundleActiveUsageDatabase::DeleteUninstalledInfo(const int userId, const st rdbStore->Delete(deletedRows, tableName, "userId = ? and bundleName = ?", queryCondition); } } + +int64_t BundleActiveUsageDatabase::GetSystemTimeMs() +{ + time_t now; + (void)time(&now); // unit is seconds. + if (static_cast(now) < 0) { + BUNDLE_ACTIVE_LOGE("Get now time error"); + return 0; + } + auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now); + auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch()); + int64_t tarDate = tarDuration.count(); + if (tarDate < 0) { + BUNDLE_ACTIVE_LOGE("tarDuration is less than 0."); + return -1; + } + return static_cast(tarDate); +} } } \ No newline at end of file diff --git a/services/packagegroup/include/bundle_active_group_handler.h b/services/packagegroup/include/bundle_active_group_handler.h index cb9ec0ddfb1df08d979a49472428dba0b5ebefde..a954957c59204f98b830fc5bbd76977ba40f8832 100644 --- a/services/packagegroup/include/bundle_active_group_handler.h +++ b/services/packagegroup/include/bundle_active_group_handler.h @@ -48,7 +48,7 @@ public: static const int MSG_CHECK_BUNDLE_STATE = 0; static const int MSG_ONE_TIME_CHECK_BUNDLE_STATE = 1; static const int MSG_CHECK_IDLE_STATE = 2; - static const int CHECK_IDLE_INTERVAL = TEN_MINUTE; + static const int CHECK_IDLE_INTERVAL = ONE_MINUTE; private: std::shared_ptr bundleActiveGroupController_; diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index ca79fead8deee27763ffbc680d3a25f559bdab55..070c8e3b555629ffa8dfba29311fe089d8c85695 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -126,7 +126,6 @@ bool BundleActiveGroupController::CheckEachBundleState(const int userId) for (auto oneBundleName : bundleNamesOfUser) { CheckAndUpdateGroup(oneBundleName, userId, bootBasedTimeStamp); } - bundleUserHistory_->printdata(userId); return true; } diff --git a/services/packageusage/include/bundle_active_calendar.h b/services/packageusage/include/bundle_active_calendar.h index fa0d88db5bddc7f69b3df984243630d4c259aab9..2e7a2f4e57d002bcb980e07a1d497afc0df07654 100644 --- a/services/packageusage/include/bundle_active_calendar.h +++ b/services/packageusage/include/bundle_active_calendar.h @@ -23,10 +23,10 @@ namespace DeviceUsageStats { class BundleActiveCalendar { public: static const int64_t ONE_SECOND_MILLISECONDS = 1000; - static const int64_t DAY_MILLISECONDS = (int64_t)1 * 1 * 30 * 60 * 1000; - static const int64_t WEEK_MILLISECONDS = (int64_t)7 * 24 * 60 * 60 * 1000; - static const int64_t MONTH_MILLISECONDS = (int64_t)30 * 24 * 60 * 60 * 1000; - static const int64_t YEAR_MILLISECONDS = (int64_t)365 * 24 * 60 * 60 * 1000; + static const int64_t DAY_MILLISECONDS = (int64_t)1 * 1 * 10 * 60 * 1000; + static const int64_t WEEK_MILLISECONDS = (int64_t)1 * 1 * 20 * 60 * 1000; + static const int64_t MONTH_MILLISECONDS = (int64_t)1 * 1 * 30 * 60 * 1000; + static const int64_t YEAR_MILLISECONDS = (int64_t)1 * 1 * 40 * 60 * 1000; BundleActiveCalendar(const int64_t timeStamp); BundleActiveCalendar() { diff --git a/services/packageusage/include/bundle_active_stats_update_listener.h b/services/packageusage/include/bundle_active_stats_update_listener.h index 5f0b3b82e58617f21fd65fd7c5cacb35737e48fd..6968b6cec6be60fe586a735c89c9d913e93d2365 100644 --- a/services/packageusage/include/bundle_active_stats_update_listener.h +++ b/services/packageusage/include/bundle_active_stats_update_listener.h @@ -19,7 +19,7 @@ namespace OHOS { namespace DeviceUsageStats { class BundleActiveStatsUpdateListener { - virtual void OnStatsChanged() = 0; + virtual void OnStatsChanged(const int userId) = 0; virtual void OnStatsReload() = 0; virtual void OnSystemUpdate(int userId) = 0; }; diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index 1f4dfcf103db15f22844fdc91c42d4e7c77d2621..6aa13e79464ec01e237502bc8d9580eb69d15800 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -44,9 +44,9 @@ public: } void Init(const int64_t timeStamp); ~BundleActiveUserService() {}; - void ReportForFlushAndShutdown(const BundleActiveEvent& event); + void ReportForShutdown(const BundleActiveEvent& event); void ReportEvent(const BundleActiveEvent& event); - void RestoreStats(); + void RestoreStats(bool forced); void RenewStatsInMemory(const int64_t timeStamp); void RenewTableTime(int64_t oldTime, int64_t newTime); void OnUserRemoved(); @@ -57,6 +57,7 @@ public: const int64_t endTime, const int userId, const std::string& bundleName); std::vector QueryEvents(const int64_t beginTime, const int64_t endTime, const int userId, const std::string& bundleName); + void LoadActiveStats(const int64_t timeStamp, const bool& force, const bool& timeChanged); private: static const int64_t ONE_SECOND_MILLISECONDS = 1000; @@ -68,7 +69,6 @@ private: inline static const std::vector PERIOD_LENGTH = {BundleActiveCalendar::DAY_MILLISECONDS, BundleActiveCalendar::WEEK_MILLISECONDS, BundleActiveCalendar::MONTH_MILLISECONDS, BundleActiveCalendar::YEAR_MILLISECONDS}; - void LoadActiveStats(const int64_t timeStamp, const bool& force); void NotifyStatsChanged(); void NotifyNewUpdate(); void printstat(); diff --git a/services/packageusage/src/bundle_active_event_tracker.cpp b/services/packageusage/src/bundle_active_event_tracker.cpp index 85d828bb2ce916b784d66b956e52eb242ff95f48..caea54dd95861f0c6cab241d415119f6950f993d 100644 --- a/services/packageusage/src/bundle_active_event_tracker.cpp +++ b/services/packageusage/src/bundle_active_event_tracker.cpp @@ -27,7 +27,7 @@ BundleActiveEventTracker::BundleActiveEventTracker() void BundleActiveEventTracker::CommitTime(const int64_t timeStamp) { - if (curStartTime_ != 0) { + if (curStartTime_) { duration_ += timeStamp - curStartTime_; curStartTime_ = 0; } @@ -35,7 +35,7 @@ void BundleActiveEventTracker::CommitTime(const int64_t timeStamp) void BundleActiveEventTracker::Update(int64_t timeStamp) { - if (curStartTime_ == 0) { + if (!curStartTime_) { count_++; } CommitTime(timeStamp); @@ -46,7 +46,7 @@ void BundleActiveEventTracker::Update(int64_t timeStamp) void BundleActiveEventTracker::AddToEventStats(std::vector& eventStatsList, int eventId, int64_t beginTime, int64_t endTime) { - if (count_ != 0 || duration_ != 0) { + if (count_ || duration_) { BundleActiveEventStats newEvent; newEvent.eventId_ = eventId; newEvent.count_ = count_; diff --git a/services/packageusage/src/bundle_active_package_stats.cpp b/services/packageusage/src/bundle_active_package_stats.cpp index 01048a2b0e44e06a530a8a0b6ec9a09c42fec7f8..95205f0dee2e2571c838a55899b65fb42557e952 100644 --- a/services/packageusage/src/bundle_active_package_stats.cpp +++ b/services/packageusage/src/bundle_active_package_stats.cpp @@ -24,7 +24,7 @@ BundleActivePackageStats::BundleActivePackageStats() endTimeStamp_ = 0; // stop time of counting lastTimeUsed_ = 0; // the timestamp of last launch totalInFrontTime_ = 0; // the total time of bundle in front. - lastContiniousTaskUsed_ = 0; // the timestamp of bundle calling a continuous task. + lastContiniousTaskUsed_ = -1; // the timestamp of bundle calling a continuous task. totalContiniousTaskUsedTime_ = 0; // the total time of bundle use continuous tasks. startCount_ = 0; bundleStartedCount_ = 0; @@ -141,7 +141,7 @@ void BundleActivePackageStats::UpdateAbility(const int64_t timeStamp, const int std::map::iterator it = abilities_.find(abilityId); if (it != abilities_.end()) { int lastEventId = it->second; - // When we recieve a new event, first update the time stats according to the last event in map. + // When we receive a new event, first update the time stats according to the last event in map. switch (lastEventId) { case BundleActiveEvent::ABILITY_FOREGROUND: IncrementTimeUsed(timeStamp); @@ -175,7 +175,7 @@ void BundleActivePackageStats::UpdateLongTimeTask(const std::string& longTimeTas return; } - // When we recieve a new event, first update the time stats according to the last service event in map. + // When we receive a new event, first update the time stats according to the last service event in map. std::map::iterator it = longTimeTasks_.find(longTimeTaskName); if (it != longTimeTasks_.end()) { int lastEventId = it->second; diff --git a/services/packageusage/src/bundle_active_report_handler.cpp b/services/packageusage/src/bundle_active_report_handler.cpp index 87b149657d1f52af62093f8aeee383f22d22f083..d02a40d18cdee7cbb6443cd1c4810529c6789aa5 100644 --- a/services/packageusage/src/bundle_active_report_handler.cpp +++ b/services/packageusage/src/bundle_active_report_handler.cpp @@ -50,7 +50,9 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point } case MSG_FLUSH_TO_DISK: { BUNDLE_ACTIVE_LOGI("FLUSH TO DISK HANDLE"); - bundleActiveCore_->RestoreToDatabase(); + auto ptrToHandlerobj = event->GetSharedObject(); + BundleActiveReportHandlerObject tmpHandlerobj = *ptrToHandlerobj; + bundleActiveCore_->RestoreToDatabase(tmpHandlerobj.userId_); break; } case MSG_REMOVE_USER: { diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index cdc163937ced6cc91e990018a7f2ce21eb1920db..386804ddaf8fa4c655ef28ce98305cbe1d8dea70 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -22,7 +22,7 @@ void BundleActiveUserService::Init(const int64_t timeStamp) { database_.InitDatabaseTableInfo(timeStamp); BUNDLE_ACTIVE_LOGI("BundleActiveUserService::Init called"); - LoadActiveStats(timeStamp, false); + LoadActiveStats(timeStamp, false, false); std::shared_ptr currentDailyStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; if (currentDailyStats != nullptr) { BundleActiveEvent startupEvent(BundleActiveEvent::STARTUP, timeStamp - ONE_SECOND_MILLISECONDS); @@ -64,9 +64,9 @@ void BundleActiveUserService::DeleteUninstalledBundleStats(const std::string& bu void BundleActiveUserService::RenewTableTime(int64_t oldTime, int64_t newTime) { BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RenewTableTime called"); - RestoreStats(); + BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RenewTableTime called current event size is %{public}d", + currentStats_[0]->events_.Size()); database_.RenewTableTime(newTime - oldTime); - LoadActiveStats(newTime, true); } void BundleActiveUserService::NotifyStatsChanged() @@ -74,7 +74,7 @@ void BundleActiveUserService::NotifyStatsChanged() if (!statsChanged_) { BUNDLE_ACTIVE_LOGI("BundleActiveUserService::NotifyStatsChanged() set stats changed to true"); statsChanged_ = true; - listener_.OnStatsChanged(); + listener_.OnStatsChanged(userId_); } } @@ -85,12 +85,13 @@ void BundleActiveUserService::NotifyNewUpdate() void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportEvent called"); + BUNDLE_ACTIVE_LOGI(" BundleActiveUserService::ReportEvent later than daily expire, B time is %{public}lld," + "E time is %{public}lld", + currentStats_[0]->beginTime_, dailyExpiryDate_.GetMilliseconds()); if (event.timeStamp_ >= dailyExpiryDate_.GetMilliseconds()) { - BUNDLE_ACTIVE_LOGI(" BundleActiveUserService::ReportEvent later than daily expire"); + BUNDLE_ACTIVE_LOGI(" BundleActiveUserService::ReportEvent later than daily expire, renew data in memory"); RenewStatsInMemory(event.timeStamp_); } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportEvent later than daily expire check done"); std::shared_ptr currentDailyStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; if (!currentDailyStats) { return; @@ -126,20 +127,18 @@ void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event) it->Update(event.bundleName_, event.continuousTaskAbilityName_, event.timeStamp_, event.eventId_, event.abilityId_); if (incrementBundleLaunch) { - BUNDLE_ACTIVE_LOGI(" BundleActiveUserService::ReportEvent increase bundle started count"); it->bundleStats_[event.bundleName_]->IncrementBundleLaunchedCount(); } break; } } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportEvent called notify"); NotifyStatsChanged(); } -void BundleActiveUserService::ReportForFlushAndShutdown(const BundleActiveEvent& event) +void BundleActiveUserService::ReportForShutdown(const BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForFlushAndShutdown() called"); - if (event.eventId_ != BundleActiveEvent::FLUSH && event.eventId_ != BundleActiveEvent::SHUTDOWN) { + BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForShutdown() called"); + if (event.eventId_ != BundleActiveEvent::SHUTDOWN) { return; } if (event.eventId_ == BundleActiveEvent::SHUTDOWN) { @@ -153,24 +152,28 @@ void BundleActiveUserService::ReportForFlushAndShutdown(const BundleActiveEvent& it->Update(event.bundleName_, event.continuousTaskAbilityName_, event.timeStamp_, event.eventId_, event.abilityId_); } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForFlushAndShutdown called notify"); + BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForShutdown called notify"); NotifyStatsChanged(); } -void BundleActiveUserService::RestoreStats() +void BundleActiveUserService::RestoreStats(bool forced) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RestoreStats() called"); - if (statsChanged_) { + BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RestoreStats() called, userId is %{public}d", userId_); + if (statsChanged_ || forced) { BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RestoreStats() stat changed is true"); for (int i = 0; i < currentStats_.size(); i++) { database_.UpdateUsageData(i, *(currentStats_[i])); + if (i == 0) { + BUNDLE_ACTIVE_LOGI("RESOTRE EVENT SIZE IS %{public}d, USER ID IS %{public}d", + currentStats_[i]->events_.Size(), userId_); + } } currentStats_[BundleActivePeriodStats::PERIOD_DAILY]->events_.Clear(); statsChanged_ = false; } } -void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const bool& force) +void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const bool& force, const bool& timeChanged) { BUNDLE_ACTIVE_LOGI("BundleActiveUserService::LoadActiveStats called"); BundleActiveCalendar tmpCalendar(0); @@ -205,9 +208,15 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo } statsChanged_ = false; // 延长统计时间到第二天0点 - dailyExpiryDate_.SetMilliseconds(timeStamp); + if (timeChanged) { + dailyExpiryDate_.SetMilliseconds(currentStats_[BundleActivePeriodStats::PERIOD_DAILY]->beginTime_); + } else { + dailyExpiryDate_.SetMilliseconds(timeStamp); + } dailyExpiryDate_.IncreaseDays(1); - dailyExpiryDate_.TruncateToDay(); + if (!timeChanged) { + dailyExpiryDate_.TruncateToDay(); + } listener_.OnStatsReload(); BUNDLE_ACTIVE_LOGI("BundleActiveUserService::LoadActiveStats current expire time is %{public}lld, " "begin time is %{public}lld", dailyExpiryDate_.GetMilliseconds(), tmpCalendar.GetMilliseconds()); @@ -241,9 +250,9 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp) } (*it)->CommitTime(dailyExpiryDate_.GetMilliseconds() - 1); } - RestoreStats(); + RestoreStats(true); database_.RemoveOldData(timeStamp); - LoadActiveStats(timeStamp, false); // 新建intervalstat或加载当前数据库数据 + LoadActiveStats(timeStamp, false, false); // 新建intervalstat或加载当前数据库数据 for (std::string continueBundleName : continueBundles) { // 更新所有事件的时间戳到新的begintime int64_t beginTime = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]->beginTime_; for (std::vector>::iterator itInterval = currentStats_.begin(); @@ -260,10 +269,9 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp) (*itInterval)->Update(continueBundleName, it->first, beginTime, it->second, ""); } } - NotifyStatsChanged(); } } - RestoreStats(); + RestoreStats(true); } std::vector BundleActiveUserService::QueryPackageStats(int intervalType, @@ -279,11 +287,7 @@ std::vector BundleActiveUserService::QueryPackageStats if (intervalType < 0 || intervalType >= currentStats_.size()) { return result; } - auto currentStats = currentStats_[intervalType]; - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats, intervaltype is %{public}d, " - "current begin time is %{public}lld, current end time is %{public}lld", - intervalType, currentStats->beginTime_, currentStats->endTime_); if (currentStats == nullptr) { BUNDLE_ACTIVE_LOGE("current interval stat is null!"); return result; @@ -299,10 +303,7 @@ std::vector BundleActiveUserService::QueryPackageStats return result; } int64_t truncatedEndTime = std::min(currentStats->beginTime_, endTime); - - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats bundle name is %{public}s", bundleName.c_str()); result = database_.QueryDatabaseUsageStats(intervalType, beginTime, truncatedEndTime, userId); - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats is %{public}d", result.size()); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats need in memory stats"); @@ -339,6 +340,7 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ } BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryEvents bundle name is %{public}s", bundleName.c_str()); result = database_.QueryDatabaseEvents(beginTime, endTime, userId, bundleName); + BUNDLE_ACTIVE_LOGI("event database query size is %{public}d", result.size()); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryEvents need in memory stats");