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