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 16 #ifndef BUNDLE_ACTIVE_CORE_H 17 #define BUNDLE_ACTIVE_CORE_H 18 19 #ifdef DEVICE_USAGE_UNIT_TEST 20 #define WEAK_FUNC __attribute__((weak)) 21 #else 22 #define WEAK_FUNC 23 #endif 24 25 #include <mutex> 26 #ifdef DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE 27 #include "power_mgr_client.h" 28 #endif 29 #include "accesstoken_kit.h" 30 #ifdef OS_ACCOUNT_PART_ENABLED 31 #include "os_account_manager.h" 32 #endif // OS_ACCOUNT_PART_ENABLED 33 #include "ibundle_active_service.h" 34 #include "remote_death_recipient.h" 35 #include "iapp_group_callback.h" 36 #include "ffrt.h" 37 #include "bundle_active_debug_mode.h" 38 #include "bundle_active_stats_update_listener.h" 39 #include "bundle_state_inner_errors.h" 40 #include "bundle_active_user_service.h" 41 #include "bundle_active_group_controller.h" 42 #include "bundle_active_group_handler.h" 43 #include "bundle_active_common_event_subscriber.h" 44 #include "bundle_active_constant.h" 45 46 namespace OHOS { 47 namespace DeviceUsageStats { 48 using namespace OHOS::Security; 49 50 class BundleActiveReportHandlerObject { 51 public: 52 BundleActiveEvent event_; 53 int32_t userId_; 54 std::string bundleName_; 55 int32_t uid_ = 0; 56 int32_t appIndex_ = 0; 57 BundleActiveReportHandlerObject(); 58 BundleActiveReportHandlerObject(const int32_t userId, const std::string bundleName); 59 BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig); ~BundleActiveReportHandlerObject()60 ~BundleActiveReportHandlerObject() {} 61 ToString()62 std::string ToString() 63 { 64 std::string result; 65 result += "userid is " + std::to_string(userId_) + ", " + event_.ToString(); 66 return result; 67 } 68 }; 69 70 class BundleActiveReportHandler; 71 72 class BundleActiveCore : public BundleActiveStatsUpdateListener, 73 public std::enable_shared_from_this<BundleActiveCore> { 74 public: 75 BundleActiveCore(); 76 virtual ~BundleActiveCore(); 77 78 /* 79 * function: ReportEvent, used to report ability fourground/background/destroy event. 80 * parameters: event, userId 81 */ 82 int32_t ReportEvent(BundleActiveEvent& event, int32_t userId); 83 84 /* 85 * function: ReportEventToAllUserId, report flush to disk, end_of_day event to service. 86 * parameters: event 87 */ 88 int32_t ReportEventToAllUserId(BundleActiveEvent& event); 89 90 /* 91 * function: OnStatsChanged, report flush to disk, end_of_day event to service. 92 * parameters: userId 93 */ 94 void OnStatsChanged(const int32_t userId) override; 95 96 /* 97 * function: OnStatsChanged, when device reboot after more than one day, BundleActiveUserService 98 * will use it to flush group info. 99 */ 100 void OnStatsReload() override; 101 102 /* 103 * function: OnSystemUpdate, now is emtpy, later will called when system is updated. 104 * parameters: userId 105 */ 106 void OnSystemUpdate(int32_t userId) override; 107 108 /* 109 * function: OnBundleUninstalled when received a PACKATE_REMOVED commen event, 110 * BundleActiveCommonEventSubscriber call it to remove data. 111 * parameters: userId, bundleName 112 */ 113 void OnBundleUninstalled(const int32_t userId, const std::string& bundleName, const int32_t uid, 114 const int32_t appIndex); 115 116 /* 117 * function: Init, BundleAciveService call it to init systemTimeShot_, realTimeShot_, 118 * create bundleGroupController_ object. 119 */ 120 void Init(); 121 122 /* 123 * function: InitBundleGroupController, BundleAciveService call it to init bundleGroupController_ object, 124 * set its handler and subscribe needed common event. 125 * create bundleGroupController_ object. 126 */ 127 void InitBundleGroupController(); 128 129 /* 130 * function: SetHandler, BundleActiveService call it to set event report handler 131 * parameters: reportHandler 132 */ 133 void SetHandler(const std::shared_ptr<BundleActiveReportHandler>& reportHandler); 134 135 /* 136 * function: RestoreToDatabase, restore bundle usage data and form data to database 137 * parameters: userId 138 */ 139 void RestoreToDatabase(const int32_t userId); 140 141 /* 142 * function: RestoreToDatabaseLocked, flush database for one user data 143 * parameters: userId 144 */ 145 void RestoreToDatabaseLocked(const int32_t userId); 146 147 /* 148 * function: ShutDown, called when device shutdown, update the in-memory stat and flush the database. 149 */ 150 void ShutDown(); 151 /* 152 * function: PreservePowerStateInfo, called when device change power state, preserve power state info. 153 */ 154 void PreservePowerStateInfo(const int32_t eventId); 155 156 /* 157 * function: queryBundleStatsInfos, query the package stat for calling user. 158 * parameters: userId, intervalType, beginTime, endTime, bundleName 159 * return: vector of BundleActivePackageStats 160 */ 161 ErrCode QueryBundleStatsInfos(std::vector<BundleActivePackageStats>& packageStats, const int32_t userId, 162 const int32_t intervalType, const int64_t beginTime, const int64_t endTime, std::string bundleName); 163 164 // query the event stat for calling user. 165 ErrCode QueryBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvent, const int32_t userId, 166 const int64_t beginTime, const int64_t endTime, std::string bundleName); 167 168 // check the app idle state for calling user. 169 int32_t IsBundleIdle(const std::string& bundleName, const int32_t userId); 170 171 // query the app group for calling app. 172 ErrCode QueryAppGroup(int32_t& appGroup, const std::string& bundleName, const int32_t userId); 173 174 ErrCode QueryModuleUsageRecords(int32_t maxNum, std::vector<BundleActiveModuleRecord>& results, int32_t userId); 175 176 /* 177 * function: QueryDeviceEventStats, query all from event stats in specific time span for calling user. 178 * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, 179 * if other SAs call this API, they should explicit define userId. 180 * return: errorcode. 181 */ 182 ErrCode QueryDeviceEventStats(int64_t beginTime, int64_t endTime, 183 std::vector<BundleActiveEventStats>& eventStats, int32_t userId); 184 185 /* 186 * function: QueryNotificationEventStats, query all app notification number in specific time span for calling user. 187 * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, 188 * if other SAs call this API, they should explicit define userId. 189 * return: errorcode. 190 */ 191 ErrCode QueryNotificationEventStats(int64_t beginTime, int64_t endTime, 192 std::vector<BundleActiveEventStats>& eventStats, int32_t userId); 193 194 // get the wall time and check if the wall time is changed. 195 int64_t CheckTimeChangeAndGetWallTime(int32_t userId = 0); 196 197 // convert event timestamp from boot based time to wall time. 198 void ConvertToSystemTimeLocked(BundleActiveEvent& event); 199 200 // get or create BundleActiveUserService object for specifice user. 201 std::shared_ptr<BundleActiveUserService> GetUserDataAndInitializeIfNeeded(const int32_t userId, 202 const int64_t timeStamp, const bool debug); 203 204 // when received a USER_REMOVED commen event, call it to remove data. 205 void OnUserRemoved(const int32_t userId); 206 207 // when user switched, restore old userdata. 208 void OnUserSwitched(const int32_t userId); 209 210 /* 211 * function: SetAppGroup, change bundleGroup to the newGroup. 212 * parameters: bundleName, newGroup, userId, isFlush, 213 * return: errorcode. 214 */ 215 ErrCode SetAppGroup( 216 const std::string& bundleName, const int32_t newGroup, const int32_t userId, const bool isFlush); 217 218 // get all user in device. 219 void GetAllActiveUser(std::vector<int32_t>& activatedOsAccountIds); 220 221 // when service stop, call it to unregister commen event and shutdown call back. 222 void UnRegisterSubscriber(); 223 224 // get system time in MS. 225 int64_t GetSystemTimeMs(); 226 227 /* 228 * function: RegisterAppGroupCallBack, register the observer to groupObservers. 229 * parameters: observer 230 * return: errCode. 231 */ 232 ErrCode RegisterAppGroupCallBack(const AccessToken::AccessTokenID& tokenId, 233 const sptr<IAppGroupCallback> &observer); 234 235 /* 236 * function: UnRegisterAppGroupCallBack, remove the observer from groupObservers. 237 * parameters: observer 238 * return: errCode. 239 */ 240 ErrCode UnRegisterAppGroupCallBack(const AccessToken::AccessTokenID& tokenId, 241 const sptr<IAppGroupCallback> &observer); 242 243 int32_t currentUsedUser_; 244 void OnAppGroupChanged(const AppGroupCallbackInfo& callbackInfo); 245 246 private: 247 void NotifOberserverGroupChanged(const AppGroupCallbackInfo& callbackInfo, AccessToken::HapTokenInfo tokenInfo); 248 void AddObserverDeathRecipient(const sptr<IAppGroupCallback> &observer); 249 void RemoveObserverDeathRecipient(const sptr<IAppGroupCallback> &observer); 250 void OnObserverDied(const wptr<IRemoteObject> &remote); 251 void OnObserverDiedInner(const wptr<IRemoteObject> &remote); 252 int64_t flushInterval_; 253 static const int64_t TIME_CHANGE_THRESHOLD_MILLIS = TWO_SECONDS; 254 const int32_t DEFAULT_USER_ID = -1; 255 std::map<int32_t, std::string> visibleActivities_; 256 // use weak_ptr to avoid circulate reference of core and handler. 257 std::weak_ptr<BundleActiveReportHandler> handler_; 258 std::shared_ptr<BundleActiveGroupController> bundleGroupController_; 259 std::shared_ptr<BundleActiveGroupHandler> bundleGroupHandler_; 260 int64_t systemTimeShot_; 261 int64_t realTimeShot_; 262 ffrt::mutex mutex_; 263 ffrt::recursive_mutex callbackMutex_; 264 std::map<int32_t, std::shared_ptr<BundleActiveUserService>> userStatServices_; 265 void RegisterSubscriber(); 266 void SubscriberLockScreenCommonEvent(); 267 std::shared_ptr<BundleActiveCommonEventSubscriber> commonEventSubscriber_; 268 std::shared_ptr<BundleActiveCommonEventSubscriber> lockScreenSubscriber_; 269 void RestoreAllData(); 270 std::map<AccessToken::AccessTokenID, sptr<IAppGroupCallback>> groupChangeObservers_; 271 std::map<sptr<IRemoteObject>, sptr<RemoteDeathRecipient>> recipientMap_; 272 void ObtainSystemEventName(BundleActiveEvent& event); 273 bool debugCore_; 274 }; 275 } // namespace DeviceUsageStats 276 } // namespace OHOS 277 #endif // BUNDLE_ACTIVE_CORE_H 278 279