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