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 check bundleName has device_standby allow permission or not.
263      *
264      * @param bundleName bundleName of the application.
265      * @return true mean the application has device_stadnby allow permission, false or not.
266      */
267     bool CheckStandbyApplyInfo(std::string& bundleName);
268     /**
269      * @brief init the preinstalled work.
270      */
271     void InitPreinstalledWork();
272     void TriggerWorkIfConditionReady();
273     /**
274      * @brief stop deepIdle works.
275      *
276      * @return success or fail.
277      */
278     int32_t StopDeepIdleWorks();
279     /**
280      * @brief load sa.
281      */
282     void LoadSa();
283 private:
284     void RegisterStandbyStateObserver();
285     void WorkQueueManagerInit(const std::shared_ptr<AppExecFwk::EventRunner>& runner);
286     bool WorkPolicyManagerInit(const std::shared_ptr<AppExecFwk::EventRunner>& runner);
287     void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
288     void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
289 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
290     void GroupObserverInit();
291 #endif
292     std::list<std::shared_ptr<WorkInfo>> ReadPersistedWorks();
293     void DumpAllInfo(std::string& result);
294     bool CheckWorkInfo(WorkInfo& workInfo, int32_t& uid);
295     bool StopWorkInner(std::shared_ptr<WorkStatus> workStatus, int32_t uid, const bool needCancel, bool isTimeOut);
296     bool CheckCondition(WorkInfo& workInfo);
297     bool IsBaseAbilityReady();
298     void DumpUsage(std::string& result);
299     void DumpParamSet(std::string& key, std::string& value, std::string& result);
300     void DumpProcessWorks(const std::string& bundleName, const std::string& abilityName, std::string& result);
301     void DumpRunningWorks(const std::string& uidStr, const std::string& option, std::string& result);
302     bool IsDebugApp(const std::string& bundleName);
303     bool AllowDump();
304     void DumpProcessForEngMode(std::vector<std::string>& argsInStr, std::string& result);
305     void DumpProcessForUserMode(std::vector<std::string>& argsInStr, std::string& result);
306     bool GetJsonFromFile(const char* filePath, Json::Value& root);
307     bool GetUidByBundleName(const std::string& bundleName, int32_t& uid);
308     void InitWorkInner();
309     void AddWorkInner(WorkInfo& workInfo);
310     std::list<std::shared_ptr<WorkInfo>> ReadPreinstalledWorks();
311     void LoadWorksFromFile(const char *path, std::list<std::shared_ptr<WorkInfo>> &workInfos);
312     void InitPersistedWork();
313     bool CheckProcessName();
314     bool GetAppIndexAndBundleNameByUid(int32_t uid, int32_t &appIndex, std::string &bundleName);
315     bool CheckExtensionInfos(WorkInfo &workInfo, int32_t uid);
316     void DumpLoadSaWorks(const std::string &saIdStr, const std::string &residentSaStr, std::string &result);
317 
318 private:
319     std::set<int32_t> whitelist_;
320     ffrt::mutex whitelistMutex_;
321     std::map<int32_t, bool> saMap_;
322 #ifdef RESOURCESCHEDULE_BGTASKMGR_ENABLE
323     std::shared_ptr<SchedulerBgTaskSubscriber> subscriber_;
324 #endif
325     std::shared_ptr<WorkQueueManager> workQueueManager_;
326     std::shared_ptr<WorkPolicyManager> workPolicyManager_;
327     ffrt::mutex mutex_;
328     ffrt::mutex observerMutex_;
329     std::map<std::string, std::shared_ptr<WorkInfo>> persistedMap_;
330     bool ready_ {false};
331     std::shared_ptr<WorkEventHandler> handler_;
332     std::shared_ptr<AppExecFwk::EventRunner> eventRunner_;
333     bool checkBundle_ {true};
334 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
335     sptr<WorkBundleGroupChangeCallback> groupObserver_;
336 #endif
337 #ifdef  DEVICE_STANDBY_ENABLE
338     sptr<WorkStandbyStateChangeCallback> standbyStateObserver_;
339 #endif
340 };
341 } // namespace WorkScheduler
342 } // namespace OHOS
343 #endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICES_H
344