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