• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "bundle_active_core.h"
16 #include "accesstoken_kit.h"
17 #include "time_service_client.h"
18 
19 #include "bundle_active_log.h"
20 #include "bundle_active_event.h"
21 #include "bundle_active_event_stats.h"
22 #include "bundle_active_report_handler.h"
23 #include "bundle_active_group_common.h"
24 #include "bundle_active_bundle_mgr_helper.h"
25 #include "bundle_active_constant.h"
26 #include "bundle_constants.h"
27 
28 namespace OHOS {
29 namespace DeviceUsageStats {
30 #ifndef OS_ACCOUNT_PART_ENABLED
31 const int32_t DEFAULT_OS_ACCOUNT_ID = 0; // 0 is the default id when there is no os_account part
32 #endif // OS_ACCOUNT_PART_ENABLED
33 
BundleActiveReportHandlerObject()34 BundleActiveReportHandlerObject::BundleActiveReportHandlerObject()
35 {
36         userId_ = -1;
37         bundleName_ = "";
38 }
39 
BundleActiveReportHandlerObject(const int32_t userId,const std::string bundleName)40 BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const int32_t userId, const std::string bundleName)
41 {
42     userId_ = userId;
43     bundleName_ = bundleName;
44 }
45 
BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject & orig)46 BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig)
47 {
48     event_ = orig.event_;
49     userId_ = orig.userId_;
50     bundleName_ = orig.bundleName_;
51     uid_ = orig.uid_;
52     appIndex_ = orig.appIndex_;
53 }
54 
BundleActiveCore()55 BundleActiveCore::BundleActiveCore()
56 {
57     systemTimeShot_ = -1;
58     realTimeShot_ = -1;
59     currentUsedUser_ = -1;
60     if (DEBUG_ON) {
61         flushInterval_ = TWO_MINUTE;
62         debugCore_ = true;
63     } else {
64         flushInterval_ = THIRTY_MINUTE;
65         debugCore_ = false;
66     }
67 }
68 
~BundleActiveCore()69 BundleActiveCore::~BundleActiveCore()
70 {
71 }
72 
OnReceiveEvent(const CommonEventData & data)73 void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &data)
74 {
75     std::lock_guard<ffrt::mutex> lock(mutex_);
76     std::string action = data.GetWant().GetAction();
77     if (action == CommonEventSupport::COMMON_EVENT_SCREEN_OFF ||
78         action == CommonEventSupport::COMMON_EVENT_SCREEN_ON) {
79         if (!activeGroupController_.expired()) {
80             sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
81             bool isScreenOn = activeGroupController_.lock()->IsScreenOn();
82             BUNDLE_ACTIVE_LOGI("screen state change to %{public}d", isScreenOn);
83             activeGroupController_.lock()->OnScreenChanged(isScreenOn, timer->GetBootTimeMs());
84         }
85     } else if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) {
86         if (!bundleActiveReportHandler_.expired()) {
87             int32_t userId = data.GetCode();
88             BUNDLE_ACTIVE_LOGI("remove user id %{public}d", userId);
89             BundleActiveReportHandlerObject tmpHandlerObject(userId, "");
90             std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
91                 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
92             bundleActiveReportHandler_.lock()->SendEvent(BundleActiveReportHandler::MSG_REMOVE_USER, handlerobjToPtr);
93         }
94     } else if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
95         int32_t userId = data.GetCode();
96         BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive switched user event, user id is %{public}d", userId);
97         BundleActiveReportHandlerObject tmpHandlerObject(userId, "");
98         std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
99             std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
100         bundleActiveReportHandler_.lock()->SendEvent(BundleActiveReportHandler::MSG_SWITCH_USER, handlerobjToPtr);
101     } else if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED ||
102         action == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) {
103         int32_t userId = data.GetWant().GetIntParam("userId", 0);
104         std::string bundleName = data.GetWant().GetElement().GetBundleName();
105         BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d, bundlename is %{public}s",
106             action.c_str(), userId, bundleName.c_str());
107         if (!bundleActiveReportHandler_.expired()) {
108             BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName);
109             tmpHandlerObject.uid_ = data.GetWant().GetIntParam("uid", -1);
110             tmpHandlerObject.appIndex_ = data.GetWant().GetIntParam("appIndex", -1);
111             std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
112                 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
113             bundleActiveReportHandler_.lock()->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED,
114                 handlerobjToPtr);
115         }
116     } else if (action == COMMON_EVENT_UNLOCK_SCREEN || action == COMMON_EVENT_LOCK_SCREEN) {
117         int32_t userId = data.GetWant().GetIntParam("userId", 0);
118         HandleLockEvent(action, userId);
119     }
120 }
121 
HandleLockEvent(const std::string & action,const int32_t userId)122 void BundleActiveCommonEventSubscriber::HandleLockEvent(const std::string& action, const int32_t userId)
123 {
124     BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d", action.c_str(), userId);
125     if (bundleActiveReportHandler_.expired()) {
126         return;
127     }
128     BundleActiveReportHandlerObject tmpHandlerObject(-1, "");
129     BundleActiveEvent newEvent;
130     tmpHandlerObject.event_ = newEvent;
131     if (action == COMMON_EVENT_UNLOCK_SCREEN) {
132         tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_UNLOCK;
133     } else {
134         tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_LOCK;
135     }
136     tmpHandlerObject.userId_ = userId;
137     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
138     tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
139     auto handlerobjToPtr = std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
140     bundleActiveReportHandler_.lock()->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr);
141 }
142 
RegisterSubscriber()143 void BundleActiveCore::RegisterSubscriber()
144 {
145     MatchingSkills matchingSkills;
146     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
147     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
148     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
149     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
150     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
151     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED);
152     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED);
153     CommonEventSubscribeInfo subscriberInfo(matchingSkills);
154     commonEventSubscriber_ = std::make_shared<BundleActiveCommonEventSubscriber>(subscriberInfo,
155         bundleGroupController_, handler_);
156     bool subscribeResult = CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_);
157     SubscriberLockScreenCommonEvent();
158     BUNDLE_ACTIVE_LOGD("Register for events result is %{public}d", subscribeResult);
159 }
160 
SubscriberLockScreenCommonEvent()161 void BundleActiveCore::SubscriberLockScreenCommonEvent()
162 {
163     MatchingSkills matchingSkills;
164     matchingSkills.AddEvent(COMMON_EVENT_UNLOCK_SCREEN);
165     matchingSkills.AddEvent(COMMON_EVENT_LOCK_SCREEN);
166     CommonEventSubscribeInfo subscriberInfo(matchingSkills);
167     subscriberInfo.SetPublisherBundleName(AppExecFwk::Constants::SCENE_BOARD_BUNDLE_NAME);
168     lockScreenSubscriber_ = std::make_shared<BundleActiveCommonEventSubscriber>(subscriberInfo,
169         bundleGroupController_, handler_);
170     CommonEventManager::SubscribeCommonEvent(lockScreenSubscriber_);
171 }
172 
UnRegisterSubscriber()173 void BundleActiveCore::UnRegisterSubscriber()
174 {
175     CommonEventManager::UnSubscribeCommonEvent(commonEventSubscriber_);
176     CommonEventManager::UnSubscribeCommonEvent(lockScreenSubscriber_);
177 }
178 
Init()179 void BundleActiveCore::Init()
180 {
181     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
182     do {
183         realTimeShot_ = timer->GetBootTimeMs();
184         systemTimeShot_ = GetSystemTimeMs();
185     } while (realTimeShot_ == -1 && systemTimeShot_ == -1);
186     realTimeShot_ = timer->GetBootTimeMs();
187     systemTimeShot_ = GetSystemTimeMs();
188     bundleGroupController_ = std::make_shared<BundleActiveGroupController>(debugCore_);
189     BUNDLE_ACTIVE_LOGD("system time shot is %{public}lld", (long long)systemTimeShot_);
190 }
191 
InitBundleGroupController()192 void BundleActiveCore::InitBundleGroupController()
193 {
194     BUNDLE_ACTIVE_LOGD("InitBundleGroupController called");
195     bundleGroupHandler_ = std::make_shared<BundleActiveGroupHandler>(debugCore_);
196     if (bundleGroupHandler_ == nullptr) {
197         return;
198     }
199     if (bundleGroupController_ != nullptr) {
200         bundleGroupHandler_->Init(bundleGroupController_);
201         bundleGroupController_->SetHandlerAndCreateUserHistory(bundleGroupHandler_, realTimeShot_, shared_from_this());
202         BUNDLE_ACTIVE_LOGI("Init Set group controller and handler done");
203     } else {
204         return;
205     }
206     RegisterSubscriber();
207     std::vector<int32_t> activatedOsAccountIds;
208     bundleGroupController_->bundleGroupEnable_ = true;
209     GetAllActiveUser(activatedOsAccountIds);
210     if (activatedOsAccountIds.size() == 0) {
211         BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated");
212         return;
213     }
214     for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) {
215         bundleGroupController_->PeriodCheckBundleState(activatedOsAccountIds[i]);
216     }
217 }
218 
SetHandler(const std::shared_ptr<BundleActiveReportHandler> & reportHandler)219 void BundleActiveCore::SetHandler(const std::shared_ptr<BundleActiveReportHandler>& reportHandler)
220 {
221     handler_ = reportHandler;
222 }
223 
GetUserDataAndInitializeIfNeeded(const int32_t userId,const int64_t timeStamp,const bool debug)224 std::shared_ptr<BundleActiveUserService> WEAK_FUNC BundleActiveCore::GetUserDataAndInitializeIfNeeded(
225     const int32_t userId, const int64_t timeStamp, const bool debug)
226 {
227     BUNDLE_ACTIVE_LOGD("GetUserDataAndInitializeIfNeeded called");
228     std::map<int, std::shared_ptr<BundleActiveUserService>>::iterator it = userStatServices_.find(userId);
229     if (it == userStatServices_.end()) {
230         BUNDLE_ACTIVE_LOGI("first initialize user service");
231         std::shared_ptr<BundleActiveUserService> service = std::make_shared<BundleActiveUserService>(userId, *this,
232             debug);
233         service->Init(timeStamp);
234         userStatServices_[userId] = service;
235         BUNDLE_ACTIVE_LOGI("service is not null");
236         return service;
237     }
238     return it->second;
239 }
240 
OnBundleUninstalled(const int32_t userId,const std::string & bundleName,const int32_t uid,const int32_t appIndex)241 void BundleActiveCore::OnBundleUninstalled(const int32_t userId, const std::string& bundleName,
242     const int32_t uid, const int32_t appIndex)
243 {
244     BUNDLE_ACTIVE_LOGD("OnBundleUninstalled CALLED");
245     std::lock_guard<ffrt::mutex> lock(mutex_);
246     int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
247     if (timeNow == ERR_TIME_OPERATION_FAILED) {
248         return;
249     }
250     auto service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
251     if (service == nullptr) {
252         return;
253     }
254     service->DeleteUninstalledBundleStats(bundleName, uid, appIndex);
255     bundleGroupController_->OnBundleUninstalled(userId, bundleName, uid, appIndex);
256 }
257 
OnStatsChanged(const int32_t userId)258 void BundleActiveCore::OnStatsChanged(const int32_t userId)
259 {
260     if (!handler_.expired()) {
261         BundleActiveReportHandlerObject tmpHandlerObject;
262         tmpHandlerObject.userId_ = userId;
263         std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
264             std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
265         if (handler_.lock()->HasEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK) == false) {
266             BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event for user %{public}d", userId);
267             handler_.lock()->SendEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, handlerobjToPtr, flushInterval_);
268         }
269     }
270 }
271 
RestoreAllData()272 void BundleActiveCore::RestoreAllData()
273 {
274     for (const auto& it : userStatServices_) {
275         std::shared_ptr<BundleActiveUserService> service = it.second;
276         if (service == nullptr) {
277             BUNDLE_ACTIVE_LOGI("service in BundleActiveCore::RestoreToDatabaseLocked() is null");
278             return;
279         }
280         BUNDLE_ACTIVE_LOGI("userid is %{public}d ", service->userId_);
281         service->RestoreStats(true);
282         if (bundleGroupController_ != nullptr && bundleGroupController_->bundleUserHistory_ != nullptr) {
283             bundleGroupController_->RestoreToDatabase(it.first);
284         }
285     }
286     if (bundleGroupController_ != nullptr) {
287         bundleGroupController_->RestoreDurationToDatabase();
288     }
289     if (!handler_.expired()) {
290         BUNDLE_ACTIVE_LOGI("RestoreAllData remove flush to disk event");
291         handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
292     }
293 }
294 
RestoreToDatabase(const int32_t userId)295 void BundleActiveCore::RestoreToDatabase(const int32_t userId)
296 {
297     BUNDLE_ACTIVE_LOGD("RestoreToDatabase called");
298     BundleActiveEvent event;
299     event.eventId_ = BundleActiveEvent::FLUSH;
300     event.timeStamp_ = GetSystemTimeMs();
301     event.abilityId_ = "";
302     auto it = userStatServices_.find(userId);
303     if (it != userStatServices_.end()) {
304         it->second->ReportEvent(event);
305     }
306     RestoreToDatabaseLocked(userId);
307 }
308 
RestoreToDatabaseLocked(const int32_t userId)309 void BundleActiveCore::RestoreToDatabaseLocked(const int32_t userId)
310 {
311     BUNDLE_ACTIVE_LOGD("RestoreToDatabaseLocked called");
312     auto it = userStatServices_.find(userId);
313     if (it != userStatServices_.end()) {
314         it->second->RestoreStats(false);
315     }
316     if (bundleGroupController_ != nullptr) {
317         bundleGroupController_->RestoreDurationToDatabase();
318     }
319     if (!handler_.expired()) {
320         BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event");
321         handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
322     }
323 }
324 
PreservePowerStateInfo(const int32_t eventId)325 void BundleActiveCore::PreservePowerStateInfo(const int32_t eventId)
326 {
327     if (!handler_.expired()) {
328         int32_t userId = -1;
329         std::vector<int32_t> currentActiveUser;
330         BundleActiveCore::GetAllActiveUser(currentActiveUser);
331         if (currentActiveUser.size() == 1) {
332             userId = currentActiveUser.front();
333         }
334         BundleActiveReportHandlerObject tmpHandlerObject(userId, "");
335         BundleActiveEvent newEvent;
336         tmpHandlerObject.event_ = newEvent;
337         tmpHandlerObject.event_.eventId_ = eventId;
338         sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
339         tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
340         std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
341             std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
342         handler_.lock()->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr);
343     }
344 }
345 
ShutDown()346 void BundleActiveCore::ShutDown()
347 {
348     std::lock_guard<ffrt::mutex> lock(mutex_);
349     BUNDLE_ACTIVE_LOGD("ShutDown called");
350     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
351     int64_t timeStamp = timer->GetBootTimeMs();
352     BundleActiveEvent event(BundleActiveEvent::SHUTDOWN, timeStamp);
353     event.bundleName_ = BundleActiveEvent::DEVICE_EVENT_PACKAGE_NAME;
354     std::vector<int32_t> activatedOsAccountIds;
355     GetAllActiveUser(activatedOsAccountIds);
356     if (activatedOsAccountIds.size() == 0) {
357         BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated");
358         return;
359     }
360     for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) {
361         bundleGroupController_->ShutDown(timeStamp, activatedOsAccountIds[i]);
362     }
363     ReportEventToAllUserId(event);
364     RestoreAllData();
365 }
366 
OnStatsReload()367 void BundleActiveCore::OnStatsReload()
368 {
369     BUNDLE_ACTIVE_LOGD("OnStatsReload called");
370     bundleGroupController_->CheckIdleStatsOneTime();
371 }
372 
OnSystemUpdate(int32_t userId)373 void BundleActiveCore::OnSystemUpdate(int32_t userId)
374 {
375 }
376 
CheckTimeChangeAndGetWallTime(int32_t userId)377 int64_t WEAK_FUNC BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId)
378 {
379     BUNDLE_ACTIVE_LOGD("CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId);
380     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
381     int64_t actualSystemTime = GetSystemTimeMs();
382     int64_t actualRealTime = timer->GetBootTimeMs();
383     int64_t expectedSystemTime = (actualRealTime - realTimeShot_) + systemTimeShot_;
384     int64_t diffSystemTime = actualSystemTime - expectedSystemTime;
385     if (actualSystemTime == -1 || actualRealTime == -1) {
386         return ERR_TIME_OPERATION_FAILED;
387     }
388     BUNDLE_ACTIVE_LOGD("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, "
389         "diff is %{public}lld", (long long)actualSystemTime,
390         (long long)actualRealTime, (long long)expectedSystemTime, (long long)diffSystemTime);
391     if (std::abs(diffSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) {
392         // 时区变换逻辑
393         auto it = userStatServices_.find(userId);
394         if (it != userStatServices_.end()) {
395             BundleActiveEvent event;
396             event.eventId_ = BundleActiveEvent::FLUSH;
397             event.timeStamp_ = expectedSystemTime;
398             event.abilityId_ = "";
399             it->second->ReportEvent(event);
400             it->second->RestoreStats(true);
401             it->second->RenewTableTime(expectedSystemTime, actualSystemTime);
402             it->second->LoadActiveStats(actualSystemTime, true, true);
403             it->second->LoadModuleAndFormStats();
404             if (!handler_.expired()) {
405                 BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime remove flush to disk event");
406                 handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
407             }
408         }
409         realTimeShot_ = actualRealTime;
410         systemTimeShot_ = actualSystemTime;
411     }
412     return actualSystemTime;
413 }
414 
ConvertToSystemTimeLocked(BundleActiveEvent & event)415 void BundleActiveCore::ConvertToSystemTimeLocked(BundleActiveEvent& event)
416 {
417     BUNDLE_ACTIVE_LOGD("ConvertToSystemTimeLocked called");
418     event.timeStamp_ = std::max((int64_t)0, event.timeStamp_ - realTimeShot_) + systemTimeShot_;
419 }
420 
OnUserRemoved(const int32_t userId)421 void BundleActiveCore::OnUserRemoved(const int32_t userId)
422 {
423     BUNDLE_ACTIVE_LOGD("OnUserRemoved called");
424     std::lock_guard<ffrt::mutex> lock(mutex_);
425     auto it = userStatServices_.find(userId);
426     if (it == userStatServices_.end()) {
427         return;
428     }
429     userStatServices_[userId]->OnUserRemoved();
430     userStatServices_[userId].reset();
431     userStatServices_.erase(userId);
432     bundleGroupController_->OnUserRemoved(userId);
433 }
434 
OnUserSwitched(const int32_t userId)435 void BundleActiveCore::OnUserSwitched(const int32_t userId)
436 {
437     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
438     auto it = userStatServices_.find(currentUsedUser_);
439     if (it != userStatServices_.end()) {
440         BUNDLE_ACTIVE_LOGI("restore old user id %{public}d data when switch user", currentUsedUser_);
441         BundleActiveEvent event;
442         event.eventId_ = BundleActiveEvent::FLUSH;
443         int64_t actualRealTime = timer->GetBootTimeMs();
444         event.timeStamp_ = (actualRealTime - realTimeShot_) + systemTimeShot_;
445         event.abilityId_ = "";
446         it->second->ReportEvent(event);
447         it->second->RestoreStats(true);
448     }
449     std::vector<int32_t> activatedOsAccountIds;
450     GetAllActiveUser(activatedOsAccountIds);
451     if (activatedOsAccountIds.size() == 0) {
452         BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated");
453         return;
454     }
455     for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) {
456         BUNDLE_ACTIVE_LOGI("start to period check for userId %{public}d", activatedOsAccountIds[i]);
457         bundleGroupController_->OnUserSwitched(activatedOsAccountIds[i], currentUsedUser_);
458     }
459     currentUsedUser_ = userId;
460     OnStatsChanged(userId);
461 }
462 
ReportEvent(BundleActiveEvent & event,int32_t userId)463 int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId)
464 {
465     BUNDLE_ACTIVE_LOGD("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_);
466     ObtainSystemEventName(event);
467     event.PrintEvent(debugCore_);
468     std::lock_guard<ffrt::mutex> lock(mutex_);
469     if (userId == 0 || userId == -1) {
470         return -1;
471     }
472     if (currentUsedUser_ == -1) {
473         currentUsedUser_ = userId;
474         BUNDLE_ACTIVE_LOGI("last used id change to %{public}d", currentUsedUser_);
475     }
476     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
477     int64_t bootBasedTimeStamp = timer->GetBootTimeMs();
478     if (BundleActiveBundleMgrHelper::GetInstance()->IsLauncherApp(event.bundleName_, userId)) {
479         BUNDLE_ACTIVE_LOGI("launcher event, only update app group");
480         bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId);
481         return 0;
482     }
483     BUNDLE_ACTIVE_LOGD("report event called, bundle name %{public}s time %{public}lld userId %{public}d, "
484         "eventid %{public}d, in lock range", event.bundleName_.c_str(),
485         (long long)event.timeStamp_, userId, event.eventId_);
486     int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
487     if (timeNow == ERR_TIME_OPERATION_FAILED) {
488         return -1;
489     }
490     ConvertToSystemTimeLocked(event);
491     std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
492     if (service == nullptr) {
493         BUNDLE_ACTIVE_LOGE("get user data service failed!");
494         return -1;
495     }
496     if (event.eventId_ == BundleActiveEvent::FORM_IS_CLICKED ||
497         event.eventId_ == BundleActiveEvent::FORM_IS_REMOVED) {
498         service->ReportFormEvent(event);
499         return 0;
500     }
501     service->ReportModuleEvent(event);
502     service->ReportEvent(event);
503     bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId);
504     return 0;
505 }
506 
ObtainSystemEventName(BundleActiveEvent & event)507 void BundleActiveCore::ObtainSystemEventName(BundleActiveEvent& event)
508 {
509     switch (event.eventId_) {
510         case BundleActiveEvent::SYSTEM_LOCK:
511             event.bundleName_ = OPERATION_SYSTEM_LOCK;
512             break;
513         case BundleActiveEvent::SYSTEM_UNLOCK:
514             event.bundleName_ = OPERATION_SYSTEM_UNLOCK;
515             break;
516         case BundleActiveEvent::SYSTEM_SLEEP:
517             event.bundleName_ = OPERATION_SYSTEM_SLEEP;
518             break;
519         case BundleActiveEvent::SYSTEM_WAKEUP:
520             event.bundleName_ = OPERATION_SYSTEM_WAKEUP;
521             break;
522         default:
523             break;
524     }
525 }
526 
ReportEventToAllUserId(BundleActiveEvent & event)527 int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event)
528 {
529     BUNDLE_ACTIVE_LOGD("ReportEventToAllUserId called");
530     int64_t timeNow = CheckTimeChangeAndGetWallTime();
531     if (timeNow == ERR_TIME_OPERATION_FAILED) {
532         return -1;
533     }
534     if (userStatServices_.empty()) {
535         return DEFAULT_USER_ID;
536     }
537     for (const auto& it : userStatServices_) {
538         ConvertToSystemTimeLocked(event);
539         std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(it.first, timeNow,
540             debugCore_);
541         if (service == nullptr) {
542             BUNDLE_ACTIVE_LOGE("get user data service failed!");
543             return -1;
544         }
545         BUNDLE_ACTIVE_LOGI("ReportEventToAllUserId SERVICE user ID IS userId %{public}d", service->userId_);
546         service->ReportForShutdown(event);
547         return 0;
548     }
549     return 0;
550 }
551 
QueryBundleStatsInfos(std::vector<BundleActivePackageStats> & packageStats,const int32_t userId,const int32_t intervalType,const int64_t beginTime,const int64_t endTime,std::string bundleName)552 ErrCode BundleActiveCore::QueryBundleStatsInfos(std::vector<BundleActivePackageStats>& packageStats,
553     const int32_t userId, const int32_t intervalType, const int64_t beginTime, const int64_t endTime,
554     std::string bundleName)
555 {
556     BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfos called");
557     std::lock_guard<ffrt::mutex> lock(mutex_);
558     int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
559     if (timeNow == ERR_TIME_OPERATION_FAILED) {
560         return ERR_TIME_OPERATION_FAILED;
561     }
562 
563     BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfos begin time is %{public}lld, end time is %{public}lld, "
564         "intervaltype is %{public}d", (long long)beginTime, (long long)endTime, intervalType);
565     if (beginTime > timeNow || beginTime >= endTime) {
566         BUNDLE_ACTIVE_LOGI("QueryBundleStatsInfos time span illegal");
567         return ERR_QUERY_TIME_OUT_OF_RANGE;
568     }
569 
570     std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
571     if (service == nullptr) {
572         BUNDLE_ACTIVE_LOGI("QueryBundleStatsInfos service is null, failed");
573         return ERR_MEMORY_OPERATION_FAILED;
574     }
575     return service->QueryBundleStatsInfos(packageStats, intervalType, beginTime, endTime, userId, bundleName);
576 }
577 
QueryBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvent,const int32_t userId,const int64_t beginTime,const int64_t endTime,std::string bundleName)578 ErrCode BundleActiveCore::QueryBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvent, const int32_t userId,
579     const int64_t beginTime, const int64_t endTime, std::string bundleName)
580 {
581     BUNDLE_ACTIVE_LOGD("QueryBundleEvents called");
582     std::lock_guard<ffrt::mutex> lock(mutex_);
583     int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
584     if (timeNow == ERR_TIME_OPERATION_FAILED) {
585         return ERR_TIME_OPERATION_FAILED;
586     }
587     if (beginTime > timeNow || beginTime >= endTime) {
588         return ERR_QUERY_TIME_OUT_OF_RANGE;
589     }
590     std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
591     if (service == nullptr) {
592         return ERR_MEMORY_OPERATION_FAILED;
593     }
594     auto item = service->QueryBundleEvents(bundleActiveEvent, beginTime, endTime, userId, bundleName);
595     return item;
596 }
597 
QueryModuleUsageRecords(int32_t maxNum,std::vector<BundleActiveModuleRecord> & results,int32_t userId)598 ErrCode BundleActiveCore::QueryModuleUsageRecords(int32_t maxNum, std::vector<BundleActiveModuleRecord>& results,
599     int32_t userId)
600 {
601     std::lock_guard<ffrt::mutex> lock(mutex_);
602     int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
603     if (timeNow == ERR_TIME_OPERATION_FAILED) {
604         return ERR_TIME_OPERATION_FAILED;
605     }
606     std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
607     if (!service) {
608         return ERR_MEMORY_OPERATION_FAILED;
609     }
610     return service->QueryModuleUsageRecords(maxNum, results);
611 }
612 
QueryDeviceEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)613 ErrCode BundleActiveCore::QueryDeviceEventStats(int64_t beginTime, int64_t endTime,
614     std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
615 {
616     std::lock_guard<ffrt::mutex> lock(mutex_);
617     int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
618     if (timeNow == ERR_TIME_OPERATION_FAILED) {
619         return ERR_TIME_OPERATION_FAILED;
620     }
621     std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
622     if (!service) {
623         return ERR_MEMORY_OPERATION_FAILED;
624     }
625     return service->QueryDeviceEventStats(beginTime, endTime, eventStats, userId);
626 }
627 
QueryNotificationEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)628 ErrCode BundleActiveCore::QueryNotificationEventStats(int64_t beginTime, int64_t endTime,
629     std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
630 {
631     std::lock_guard<ffrt::mutex> lock(mutex_);
632     int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
633     if (timeNow == ERR_TIME_OPERATION_FAILED) {
634         return ERR_TIME_OPERATION_FAILED;
635     }
636     std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
637     if (!service) {
638         return ERR_MEMORY_OPERATION_FAILED;
639     }
640     return service->QueryNotificationEventStats(beginTime, endTime, eventStats, userId);
641 }
642 
SetAppGroup(const std::string & bundleName,const int32_t newGroup,const int32_t userId,const bool isFlush)643 ErrCode BundleActiveCore::SetAppGroup(
644     const std::string& bundleName, const int32_t newGroup, const int32_t userId, const bool isFlush)
645 {
646     int32_t newReason = GROUP_CONTROL_REASON_FORCED;
647     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
648     int64_t bootBasedTimeStamp = timer->GetBootTimeMs();
649     return bundleGroupController_->SetAppGroup(
650         bundleName, userId, newGroup, newReason, bootBasedTimeStamp, isFlush);
651 }
652 
QueryAppGroup(int32_t & appGroup,const std::string & bundleName,const int32_t userId)653 ErrCode BundleActiveCore::QueryAppGroup(int32_t& appGroup, const std::string& bundleName, const int32_t userId)
654 {
655     return bundleGroupController_->QueryAppGroup(appGroup, bundleName, userId);
656 }
657 
IsBundleIdle(const std::string & bundleName,const int32_t userId)658 int32_t BundleActiveCore::IsBundleIdle(const std::string& bundleName, const int32_t userId)
659 {
660     return bundleGroupController_->IsBundleIdle(bundleName, userId);
661 }
662 
GetAllActiveUser(std::vector<int32_t> & activatedOsAccountIds)663 void BundleActiveCore::GetAllActiveUser(std::vector<int32_t>& activatedOsAccountIds)
664 {
665 #ifdef OS_ACCOUNT_PART_ENABLED
666     if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds) != ERR_OK) {
667         BUNDLE_ACTIVE_LOGI("query activated account failed");
668         return;
669     }
670 #else // OS_ACCOUNT_PART_ENABLED
671     activatedOsAccountIds.clear();
672     activatedOsAccountIds.push_back(DEFAULT_OS_ACCOUNT_ID);
673     BUNDLE_ACTIVE_LOGI("os account part is not enabled, use default id.");
674 #endif // OS_ACCOUNT_PART_ENABLED
675     if (activatedOsAccountIds.size() == 0) {
676         BUNDLE_ACTIVE_LOGI("GetAllActiveUser size is 0");
677         return;
678     }
679 }
680 
GetSystemTimeMs()681 int64_t BundleActiveCore::GetSystemTimeMs()
682 {
683     time_t now;
684     (void)time(&now);  // unit is seconds.
685     if (static_cast<int64_t>(now) < 0) {
686         BUNDLE_ACTIVE_LOGE("Get now time error");
687         return 0;
688     }
689     auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now);
690     auto tarDuration = std::chrono::duration_cast<std::chrono::milliseconds>(tarEndTimePoint.time_since_epoch());
691     int64_t tarDate = tarDuration.count();
692     if (tarDate < 0) {
693         BUNDLE_ACTIVE_LOGE("tarDuration is less than 0.");
694         return -1;
695     }
696     return static_cast<int64_t>(tarDate);
697 }
698 
OnAppGroupChanged(const AppGroupCallbackInfo & callbackInfo)699 void BundleActiveCore::OnAppGroupChanged(const AppGroupCallbackInfo& callbackInfo)
700 {
701     std::shared_ptr<BundleActiveCore> bundleActiveCore = shared_from_this();
702     AccessToken::HapTokenInfo tokenInfo = AccessToken::HapTokenInfo();
703     bundleGroupHandler_->PostTask([bundleActiveCore, callbackInfo, tokenInfo]() {
704         bundleActiveCore->NotifOberserverGroupChanged(callbackInfo, tokenInfo);
705     });
706 }
707 
NotifOberserverGroupChanged(const AppGroupCallbackInfo & callbackInfo,AccessToken::HapTokenInfo tokenInfo)708 void BundleActiveCore::NotifOberserverGroupChanged(const AppGroupCallbackInfo& callbackInfo,
709     AccessToken::HapTokenInfo tokenInfo)
710 {
711     std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
712     for (const auto &item : groupChangeObservers_) {
713         auto observer = item.second;
714         if (!observer) {
715             continue;
716         }
717         BUNDLE_ACTIVE_LOGI(
718             "RegisterAppGroupCallBack will OnAppGroupChanged!,oldGroup is %{public}d, newGroup is %{public}d",
719             callbackInfo.GetOldGroup(), callbackInfo.GetNewGroup());
720         if (AccessToken::AccessTokenKit::GetTokenType(item.first) == AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
721             observer->OnAppGroupChanged(callbackInfo);
722         } else if (AccessToken::AccessTokenKit::GetTokenType(item.first) ==
723                     AccessToken::ATokenTypeEnum::TOKEN_HAP) {
724             AccessToken::AccessTokenKit::GetHapTokenInfo(item.first, tokenInfo);
725             if (tokenInfo.userID == callbackInfo.GetUserId()) {
726                 observer->OnAppGroupChanged(callbackInfo);
727             }
728         }
729     }
730 }
731 
RegisterAppGroupCallBack(const AccessToken::AccessTokenID & tokenId,const sptr<IAppGroupCallback> & observer)732 ErrCode BundleActiveCore::RegisterAppGroupCallBack(const AccessToken::AccessTokenID& tokenId,
733     const sptr<IAppGroupCallback> &observer)
734 {
735     std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
736     if (!observer) {
737         return ERR_MEMORY_OPERATION_FAILED;
738     }
739     auto item = groupChangeObservers_.find(tokenId);
740     if (item != groupChangeObservers_.end()) {
741         return ERR_REPEAT_REGISTER_OR_DEREGISTER_GROUP_CALLBACK;
742     }
743     groupChangeObservers_.emplace(tokenId, observer);
744     AddObserverDeathRecipient(observer);
745     BUNDLE_ACTIVE_LOGD("RegisterAppGroupCallBack number is %{public}d", static_cast<int>(groupChangeObservers_.size()));
746     return ERR_OK;
747 }
748 
UnRegisterAppGroupCallBack(const AccessToken::AccessTokenID & tokenId,const sptr<IAppGroupCallback> & observer)749 ErrCode BundleActiveCore::UnRegisterAppGroupCallBack(const AccessToken::AccessTokenID& tokenId,
750     const sptr<IAppGroupCallback> &observer)
751 {
752     std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
753     auto item = groupChangeObservers_.find(tokenId);
754     if (item == groupChangeObservers_.end()) {
755         BUNDLE_ACTIVE_LOGI("UnRegisterAppGroupCallBack observer is not exist, return");
756         return ERR_REPEAT_REGISTER_OR_DEREGISTER_GROUP_CALLBACK;
757     }
758     RemoveObserverDeathRecipient(item->second);
759     groupChangeObservers_.erase(tokenId);
760     return ERR_OK;
761 }
762 
AddObserverDeathRecipient(const sptr<IAppGroupCallback> & observer)763 void BundleActiveCore::AddObserverDeathRecipient(const sptr<IAppGroupCallback> &observer)
764 {
765     std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
766     if (!observer) {
767         BUNDLE_ACTIVE_LOGI("observer nullptr.");
768         return;
769     }
770     auto object = observer->AsObject();
771     if (!object) {
772         BUNDLE_ACTIVE_LOGI("observer->AsObject() nullptr.");
773         return;
774     }
775     auto it = recipientMap_.find(observer->AsObject());
776     if (it != recipientMap_.end()) {
777         BUNDLE_ACTIVE_LOGI("This death recipient has been added.");
778         return;
779     }
780     sptr<RemoteDeathRecipient> deathRecipient = new (std::nothrow) RemoteDeathRecipient(
781         [this](const wptr<IRemoteObject> &remote) { this->OnObserverDied(remote); });
782     if (!deathRecipient) {
783         BUNDLE_ACTIVE_LOGI("create death recipient failed");
784         return ;
785     }
786     observer->AsObject()->AddDeathRecipient(deathRecipient);
787     recipientMap_.emplace(observer->AsObject(), deathRecipient);
788 }
RemoveObserverDeathRecipient(const sptr<IAppGroupCallback> & observer)789 void BundleActiveCore::RemoveObserverDeathRecipient(const sptr<IAppGroupCallback> &observer)
790 {
791     std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
792     if (!observer) {
793         return;
794     }
795     auto object = observer->AsObject();
796     if (!object) {
797         return ;
798     }
799     auto iter = recipientMap_.find(observer->AsObject());
800     if (iter != recipientMap_.end()) {
801         iter->first->RemoveDeathRecipient(iter->second);
802         recipientMap_.erase(iter);
803     }
804 }
805 
OnObserverDied(const wptr<IRemoteObject> & remote)806 void BundleActiveCore::OnObserverDied(const wptr<IRemoteObject> &remote)
807 {
808     if (remote == nullptr) {
809         BUNDLE_ACTIVE_LOGE("remote object is null.");
810         return;
811     }
812     std::shared_ptr<BundleActiveCore> bundleActiveCore = shared_from_this();
813     bundleGroupHandler_->PostSyncTask([bundleActiveCore, &remote]() {
814         bundleActiveCore->OnObserverDiedInner(remote);
815     });
816 }
817 
OnObserverDiedInner(const wptr<IRemoteObject> & remote)818 void BundleActiveCore::OnObserverDiedInner(const wptr<IRemoteObject> &remote)
819 {
820     sptr<IRemoteObject> objectProxy = remote.promote();
821     if (remote == nullptr || !objectProxy) {
822         BUNDLE_ACTIVE_LOGE("get remote object failed");
823         return;
824     }
825     std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
826     for (const auto& item : groupChangeObservers_) {
827         if (!(item.second)) {
828             continue;
829         }
830         auto object = (item.second)->AsObject();
831         if (!object) {
832             continue;
833         }
834         if (object == objectProxy) {
835             groupChangeObservers_.erase(item.first);
836             break;
837         }
838     }
839     recipientMap_.erase(objectProxy);
840 }
841 }  // namespace DeviceUsageStats
842 }  // namespace OHOS
843 
844