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 FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICES_H
17 #define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICES_H
18 
19 #include <list>
20 #include <map>
21 #include <memory>
22 #include <mutex>
23 #include <string>
24 #include <vector>
25 #include <atomic>
26 
27 #include <iremote_object.h>
28 #include <system_ability.h>
29 
30 #include "ability_manager_interface.h"
31 #include "system_ability_status_change_stub.h"
32 #include "work_sched_service_stub.h"
33 #include "work_status.h"
34 #include "work_event_handler.h"
35 #include "singleton.h"
36 #include "work_standby_state_change_callback.h"
37 #include "ffrt.h"
38 
39 namespace OHOS {
40 namespace WorkScheduler {
41 class WorkQueueManager;
42 class WorkPolicyManager;
43 class WorkBundleGroupChangeCallback;
44 class SchedulerBgTaskSubscriber;
45 class WorkSchedulerService final : public SystemAbility, public WorkSchedServiceStub,
46     public std::enable_shared_from_this<WorkSchedulerService> {
47     DISALLOW_COPY_AND_MOVE(WorkSchedulerService);
48     DECLARE_SYSTEM_ABILITY(WorkSchedulerService);
49     DECLARE_DELAYED_SINGLETON(WorkSchedulerService);
50 public:
51     WorkSchedulerService(const int32_t systemAbilityId, bool runOnCreate);
52 
53     /**
54      * @brief The OnStart callback.
55      */
56     void OnStart() override;
57     /**
58      * @brief The OnStop callback.
59      */
60     void OnStop() override;
61     /**
62      * @brief Start work.
63      *
64      * @param workInfo The info of work.
65      * @return error code, ERR_OK if success.
66      */
67     int32_t StartWork(WorkInfo& workInfo) override;
68     /**
69      * @brief Stop work.
70      *
71      * @param workInfo The info of work.
72      * @return error code, ERR_OK if success.
73      */
74     int32_t StopWork(WorkInfo& workInfo) override;
75     /**
76      * @brief Stop and cancel work.
77      *
78      * @param workInfo The info of work.
79      * @return error code, ERR_OK if success.
80      */
81     int32_t StopAndCancelWork(WorkInfo& workInfo) override;
82     /**
83      * @brief Stop and clear works.
84      *
85      * @return error code, ERR_OK if success.
86      */
87     int32_t StopAndClearWorks() override;
88     /**
89      * @brief The last work time out.
90      *
91      * @param workId The id of work.
92      * @param result True if the work executed time out, else false.
93      * @return error code, ERR_OK if success.
94      */
95     int32_t IsLastWorkTimeout(int32_t workId, bool &result) override;
96     /**
97      * @brief Obtain all works.
98      *
99      * @param workInfos The infos of work.
100      * @return error code, ERR_OK if success.
101      */
102     int32_t ObtainAllWorks(std::list<std::shared_ptr<WorkInfo>>& workInfos) override;
103     /**
104      * @brief Get the status of work.
105      *
106      * @param workId The id of work.
107      * @param workInfo The info of work.
108      * @return error code, ERR_OK if success.
109      */
110     int32_t GetWorkStatus(int32_t &workId, std::shared_ptr<WorkInfo>& workInfo) override;
111     /**
112      * @brief Get the Running Work Scheduler Work object
113      *
114      * @param workInfos The infos of work.
115      * @return ErrCode ERR_OK on success, others on failure
116      */
117     int32_t GetAllRunningWorks(std::list<std::shared_ptr<WorkInfo>>& workInfos) override;
118 
119     /**
120      * @brief Pause Running Works.
121      *
122      * @param uid The uid.
123      * @return The errcode. ERR_OK on success, others on failure.
124      */
125     int32_t PauseRunningWorks(int32_t uid) override;
126 
127     /**
128      * @brief Resume Paused works.
129      *
130      * @param uid The uid.
131      * @return ErrCode ERR_OK on success, others on failure
132      */
133     int32_t ResumePausedWorks(int32_t uid) override;
134 
135     /**
136      * @brief Dump.
137      *
138      * @param fd The file descriptor.
139      * @param args The dump args.
140      * @return Status code, ERR_OK if success.
141      */
142     int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
143     /**
144      * @brief Refresh persisted works.
145      */
146     void RefreshPersistedWorks();
147     /**
148      * @brief Stop and clear works by uid.
149      *
150      * @param uid The uid.
151      * @return True if success,else false.
152      */
153     bool StopAndClearWorksByUid(int32_t uid);
154     /**
155      * @brief Create node dir.
156      *
157      * @param dir The dir.
158      * @return ERR_OK.
159      */
160     int32_t CreateNodeDir(std::string dir);
161     /**
162      * @brief Create node file.
163      *
164      * @param filePath The file path.
165      * @return ERR_OK.
166      */
167     int32_t CreateNodeFile(std::string filePath);
168     /**
169      * @brief Update work before real start.
170      *
171      * @param work The work.
172      */
173     void UpdateWorkBeforeRealStart(std::shared_ptr<WorkStatus> work);
174     /**
175      * @brief The OnConditionReady callback.
176      *
177      * @param workStatusVector The work status vector.
178      */
179     void OnConditionReady(std::shared_ptr<std::vector<std::shared_ptr<WorkStatus>>> workStatusVector);
180     /**
181      * @brief Watchdog time out.
182      *
183      * @param workStatus The status of work.
184      */
185     void WatchdogTimeOut(std::shared_ptr<WorkStatus> workStatus);
186     /**
187      * @brief Init.
188      *
189      * @return True if success,else false.
190      */
191     bool Init(const std::shared_ptr<AppExecFwk::EventRunner>& runner);
192 
193     /**
194      * @brief Get handler.
195      *
196      * @return Handler.
197      */
GetHandler()198     std::shared_ptr<WorkEventHandler> GetHandler()
199     {
200         return handler_;
201     }
202 
203     /**
204      * @brief Get work queue manager.
205      *
206      * @return Work queue manager.
207      */
GetWorkQueueManager()208     std::shared_ptr<WorkQueueManager> GetWorkQueueManager()
209     {
210         return workQueueManager_;
211     }
212 
213     /**
214      * @brief Get work policy manager.
215      *
216      * @return work policy manager.
217      */
GetWorkPolicyManager()218     std::shared_ptr<WorkPolicyManager> GetWorkPolicyManager()
219     {
220         return workPolicyManager_;
221     }
222 
223     /**
224      * @brief add uid to the whitelist or delete uid from the whitelist.
225      *
226      * @param uid uid of the app.
227      * @param isAdd true if add name, else delete.
228      */
229     void UpdateEffiResApplyInfo(int32_t uid, bool isAdd);
230 
231     /**
232      * @brief init background task subscriber, subscribe self to bgtask service
233      *
234      * @return true seccess to init subscriber
235      * @return false fail to init subscriber
236      */
237     bool InitBgTaskSubscriber();
238 
239     /**
240      * @brief check uid has work_scheduler resources or not
241      *
242      * @param uid the uid of application
243      * @return true uid has work_scheduler resources or not
244      * @return false uid does not have work_scheduler resources or not
245      */
246     bool CheckEffiResApplyInfo(int32_t uid);
247 
248     /**
249      * @brief Get the efficiency resources uid List object
250      *
251      * @return std::string string consists of uid
252      */
253     std::string GetEffiResApplyUid();
254 
255     /**
256      * @brief Get the Efficiency Resources Infos object
257      *
258      * @return ErrCode ERR_OK if succeed, others if failed
259      */
260     ErrCode QueryResAppliedUid();
261     /**
262      * @brief init the preinstalled work.
263      */
264     void InitPreinstalledWork();
265     void TriggerWorkIfConditionReady();
266     /**
267      * @brief stop deepIdle works.
268      *
269      * @return success or fail.
270      */
271     int32_t StopDeepIdleWorks();
272     /**
273      * @brief load sa.
274      */
275     void LoadSa();
276     /**
277      * @brief Handle DeepIdle callback Msg.
278      */
279     void HandleDeepIdleMsg();
280 
281     /**
282      * @brief Set work scheduler config.
283      *
284      * @param configData config param.
285      * @param sourceType data source.
286      * @return ErrCode ERR_OK on success, others on failure
287      */
288     int32_t SetWorkSchedulerConfig(const std::string &configData, int32_t sourceType) override;
289     bool IsPreinstalledBundle(const std::string& checkBundleName);
290     void InitDeviceStandyWhitelist();
291 private:
292     std::set<int32_t> whitelist_;
293     ffrt::mutex whitelistMutex_;
294     std::map<int32_t, bool> saMap_;
295 #ifdef RESOURCESCHEDULE_BGTASKMGR_ENABLE
296     std::shared_ptr<SchedulerBgTaskSubscriber> subscriber_;
297 #endif
298 
299 private:
300     std::shared_ptr<WorkQueueManager> workQueueManager_;
301     std::shared_ptr<WorkPolicyManager> workPolicyManager_;
302     ffrt::mutex mutex_;
303     ffrt::mutex observerMutex_;
304     std::map<std::string, std::shared_ptr<WorkInfo>> persistedMap_;
305     bool ready_ {false};
306     std::shared_ptr<WorkEventHandler> handler_;
307     std::shared_ptr<AppExecFwk::EventRunner> eventRunner_;
308     bool checkBundle_ {true};
309     std::set<std::string> preinstalledBundles_;
310 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
311     sptr<WorkBundleGroupChangeCallback> groupObserver_;
312 #endif
313 #ifdef  DEVICE_STANDBY_ENABLE
314     sptr<WorkStandbyStateChangeCallback> standbyStateObserver_;
315 #endif
316     uint32_t minTimeCycle_ = 20 * 60 * 1000;
317     uint32_t minCheckTime_ = 0;
318     ffrt::mutex specialMutex_;
319     std::map<std::string, uint32_t> specialMap_;
320     void RegisterStandbyStateObserver();
321     void WorkQueueManagerInit(const std::shared_ptr<AppExecFwk::EventRunner>& runner);
322     bool WorkPolicyManagerInit(const std::shared_ptr<AppExecFwk::EventRunner>& runner);
323     void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
324     void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
325 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
326     void GroupObserverInit();
327 #endif
328     std::list<std::shared_ptr<WorkInfo>> ReadPersistedWorks();
329     void DumpAllInfo(std::string &result);
330     bool CheckWorkInfo(WorkInfo &workInfo, int32_t &uid);
331     bool StopWorkInner(std::shared_ptr<WorkStatus> workStatus, int32_t uid, const bool needCancel, bool isTimeOut);
332     bool CheckCondition(WorkInfo& workInfo);
333     bool IsBaseAbilityReady();
334     void DumpUsage(std::string &result);
335     void DumpParamSet(std::string &key, std::string &value, std::string &result);
336     void DumpProcessWorks(const std::string &bundleName, const std::string &abilityName, std::string &result);
337     void DumpRunningWorks(const std::string &uidStr, const std::string &option, std::string &result);
338     bool IsDebugApp(const std::string &bundleName);
339     bool AllowDump();
340     void DumpProcessForEngMode(std::vector<std::string> &argsInStr, std::string &result);
341     void DumpProcessForUserMode(std::vector<std::string> &argsInStr, std::string &result);
342     bool GetJsonFromFile(const char *filePath, Json::Value &root);
343     bool GetUidByBundleName(const std::string &bundleName, int32_t &uid);
344     void InitWorkInner();
345     void AddWorkInner(WorkInfo& workInfo);
346     std::list<std::shared_ptr<WorkInfo>> ReadPreinstalledWorks();
347     void LoadWorksFromFile(const char *path, std::list<std::shared_ptr<WorkInfo>> &workInfos);
348     void InitPersistedWork();
349     bool CheckProcessName();
350     bool GetAppIndexAndBundleNameByUid(int32_t uid, int32_t &appIndex, std::string &bundleName);
351     bool CheckExtensionInfos(WorkInfo &workInfo, int32_t uid);
352     void DumpLoadSaWorks(const std::string &saIdStr, const std::string &residentSaStr, std::string &result);
353     void LoadMinRepeatTimeFromFile(const char *path);
354 };
355 } // namespace WorkScheduler
356 } // namespace OHOS
357 #endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICES_H
358