• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
16 #include "background_task_mgr_service.h"
17 
18 #include <functional>
19 
20 #include "ability_manager_client.h"
21 #include "accesstoken_kit.h"
22 #include "bgtaskmgr_inner_errors.h"
23 #include "bundle_constants.h"
24 #include "common_event_manager.h"
25 #include "common_event_support.h"
26 #include "file_ex.h"
27 #include "ipc_skeleton.h"
28 #include "string_ex.h"
29 
30 #include "bgtaskmgr_log_wrapper.h"
31 
32 namespace OHOS {
33 namespace BackgroundTaskMgr {
34 namespace {
35 static constexpr int32_t NO_DUMP_PARAM_NUMS = 0;
36 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
37     DelayedSingleton<BackgroundTaskMgrService>::GetInstance().get());
38 }
39 
BackgroundTaskMgrService()40 BackgroundTaskMgrService::BackgroundTaskMgrService()
41     : SystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID, true) {}
42 
~BackgroundTaskMgrService()43 BackgroundTaskMgrService::~BackgroundTaskMgrService() {}
44 
OnStart()45 void BackgroundTaskMgrService::OnStart()
46 {
47     if (state_ == ServiceRunningState::STATE_RUNNING) {
48         BGTASK_LOGW("Service has already started.");
49         return;
50     }
51     Init();
52     AddSystemAbilityListener(APP_MGR_SERVICE_ID);
53     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
54     if (!Publish(DelayedSingleton<BackgroundTaskMgrService>::GetInstance().get())) {
55         BGTASK_LOGE("Service start failed!");
56         return;
57     }
58     state_ = ServiceRunningState::STATE_RUNNING;
59     BGTASK_LOGI("background task manager service start succeed!");
60 }
61 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)62 void BackgroundTaskMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
63 {
64     DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->OnAddSystemAbility(systemAbilityId, deviceId);
65 }
66 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)67 void BackgroundTaskMgrService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
68 {
69     DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->OnRemoveSystemAbility(systemAbilityId, deviceId);
70 }
71 
Init()72 void BackgroundTaskMgrService::Init()
73 {
74     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->Init();
75     DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->Init();
76     BgContinuousTaskMgr::GetInstance()->Init();
77 }
78 
OnStop()79 void BackgroundTaskMgrService::OnStop()
80 {
81     BgContinuousTaskMgr::GetInstance()->Clear();
82     DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->Clear();
83     state_ = ServiceRunningState::STATE_NOT_START;
84     BGTASK_LOGI("background task manager stop");
85 }
86 
CheckCallingToken()87 bool BackgroundTaskMgrService::CheckCallingToken()
88 {
89     Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
90     auto tokenFlag = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
91     if (tokenFlag == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
92         tokenFlag == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL) {
93         return true;
94     }
95     return false;
96 }
97 
RequestSuspendDelay(const std::u16string & reason,const sptr<IExpiredCallback> & callback,std::shared_ptr<DelaySuspendInfo> & delayInfo)98 ErrCode BackgroundTaskMgrService::RequestSuspendDelay(const std::u16string& reason,
99     const sptr<IExpiredCallback>& callback, std::shared_ptr<DelaySuspendInfo> &delayInfo)
100 {
101     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->RequestSuspendDelay(reason, callback, delayInfo);
102 }
103 
CancelSuspendDelay(int32_t requestId)104 ErrCode BackgroundTaskMgrService::CancelSuspendDelay(int32_t requestId)
105 {
106     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->CancelSuspendDelay(requestId);
107 }
108 
GetRemainingDelayTime(int32_t requestId,int32_t & delayTime)109 ErrCode BackgroundTaskMgrService::GetRemainingDelayTime(int32_t requestId, int32_t &delayTime)
110 {
111     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->GetRemainingDelayTime(requestId, delayTime);
112 }
113 
ForceCancelSuspendDelay(int32_t requestId)114 void BackgroundTaskMgrService::ForceCancelSuspendDelay(int32_t requestId)
115 {
116     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->ForceCancelSuspendDelay(requestId);
117 }
118 
StartBackgroundRunning(const sptr<ContinuousTaskParam> & taskParam)119 ErrCode BackgroundTaskMgrService::StartBackgroundRunning(const sptr<ContinuousTaskParam> &taskParam)
120 {
121     return BgContinuousTaskMgr::GetInstance()->StartBackgroundRunning(taskParam);
122 }
123 
StopBackgroundRunning(const std::string & abilityName,const sptr<IRemoteObject> & abilityToken)124 ErrCode BackgroundTaskMgrService::StopBackgroundRunning(const std::string &abilityName,
125     const sptr<IRemoteObject> &abilityToken)
126 {
127     return BgContinuousTaskMgr::GetInstance()->StopBackgroundRunning(abilityName);
128 }
129 
GetTransientTaskApps(std::vector<std::shared_ptr<TransientTaskAppInfo>> & list)130 ErrCode BackgroundTaskMgrService::GetTransientTaskApps(std::vector<std::shared_ptr<TransientTaskAppInfo>> &list)
131 {
132     if (!CheckCallingToken()) {
133         BGTASK_LOGW("GetTransientTaskApps not allowed");
134         return ERR_BGTASK_PERMISSION_DENIED;
135     }
136     return DelayedSingleton<BgTransientTaskMgr>::GetInstance()->GetTransientTaskApps(list);
137 }
138 
GetContinuousTaskApps(std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> & list)139 ErrCode BackgroundTaskMgrService::GetContinuousTaskApps(std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> &list)
140 {
141     if (!CheckCallingToken()) {
142         BGTASK_LOGW("GetContinuousTaskApps not allowed");
143         return ERR_BGTASK_PERMISSION_DENIED;
144     }
145     return BgContinuousTaskMgr::GetInstance()->GetContinuousTaskApps(list);
146 }
147 
SubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber> & subscriber)148 ErrCode BackgroundTaskMgrService::SubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber>& subscriber)
149 {
150     if (!CheckCallingToken()) {
151         BGTASK_LOGW("SubscribeBackgroundTask not allowed");
152         return ERR_BGTASK_PERMISSION_DENIED;
153     }
154     if (DelayedSingleton<BgTransientTaskMgr>::GetInstance()->SubscribeBackgroundTask(subscriber) == ERR_OK
155         && DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->AddSubscriber(subscriber) == ERR_OK
156         && BgContinuousTaskMgr::GetInstance()->AddSubscriber(subscriber) == ERR_OK) {
157         BGTASK_LOGD("all bgtask subscribe success");
158         return ERR_OK;
159     } else {
160         BGTASK_LOGD("subscribe background task failed");
161         UnsubscribeBackgroundTask(subscriber);
162     }
163     return ERR_BGTASK_SYS_NOT_READY;
164 }
165 
UnsubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber> & subscriber)166 ErrCode BackgroundTaskMgrService::UnsubscribeBackgroundTask(const sptr<IBackgroundTaskSubscriber>& subscriber)
167 {
168     if (!CheckCallingToken()) {
169         BGTASK_LOGW("UnsubscribeBackgroundTask not allowed");
170         return ERR_BGTASK_PERMISSION_DENIED;
171     }
172     if (DelayedSingleton<BgTransientTaskMgr>::GetInstance()->UnsubscribeBackgroundTask(subscriber) == ERR_OK
173         && DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->RemoveSubscriber(subscriber) == ERR_OK
174         && BgContinuousTaskMgr::GetInstance()->RemoveSubscriber(subscriber) == ERR_OK) {
175         return ERR_OK;
176     }
177     return ERR_BGTASK_SYS_NOT_READY;
178 }
179 
HandleRequestExpired(const int32_t requestId)180 void BackgroundTaskMgrService::HandleRequestExpired(const int32_t requestId)
181 {
182     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleRequestExpired(requestId);
183 }
184 
HandleExpiredCallbackDeath(const wptr<IRemoteObject> & remote)185 void BackgroundTaskMgrService::HandleExpiredCallbackDeath(const wptr<IRemoteObject>& remote)
186 {
187     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleExpiredCallbackDeath(remote);
188 }
189 
HandleSubscriberDeath(const wptr<IRemoteObject> & remote)190 void BackgroundTaskMgrService::HandleSubscriberDeath(const wptr<IRemoteObject>& remote)
191 {
192     DelayedSingleton<BgTransientTaskMgr>::GetInstance()->HandleSubscriberDeath(remote);
193 }
194 
ApplyEfficiencyResources(const sptr<EfficiencyResourceInfo> & resourceInfo)195 ErrCode BackgroundTaskMgrService::ApplyEfficiencyResources(const sptr<EfficiencyResourceInfo> &resourceInfo)
196 {
197     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ApplyEfficiencyResources(resourceInfo);
198 }
199 
ResetAllEfficiencyResources()200 ErrCode BackgroundTaskMgrService::ResetAllEfficiencyResources()
201 {
202     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ResetAllEfficiencyResources();
203 }
204 
GetEfficiencyResourcesInfos(std::vector<std::shared_ptr<ResourceCallbackInfo>> & appList,std::vector<std::shared_ptr<ResourceCallbackInfo>> & procList)205 ErrCode BackgroundTaskMgrService::GetEfficiencyResourcesInfos(
206     std::vector<std::shared_ptr<ResourceCallbackInfo>> &appList,
207     std::vector<std::shared_ptr<ResourceCallbackInfo>> &procList)
208 {
209     if (!CheckCallingToken()) {
210         BGTASK_LOGW("GetEfficiencyResourcesInfos not allowed");
211         return ERR_BGTASK_PERMISSION_DENIED;
212     }
213     return DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->GetEfficiencyResourcesInfos(appList, procList);
214 }
215 
StopContinuousTask(int32_t uid,int32_t pid,uint32_t taskType)216 ErrCode BackgroundTaskMgrService::StopContinuousTask(int32_t uid, int32_t pid, uint32_t taskType)
217 {
218     if (!CheckCallingToken()) {
219         BGTASK_LOGW("StopContinuousTask not allowed");
220         return ERR_BGTASK_PERMISSION_DENIED;
221     }
222     BgContinuousTaskMgr::GetInstance()->StopContinuousTask(uid, pid, taskType);
223     return ERR_OK;
224 }
225 
Dump(int32_t fd,const std::vector<std::u16string> & args)226 int32_t BackgroundTaskMgrService::Dump(int32_t fd, const std::vector<std::u16string> &args)
227 {
228     std::vector<std::string> argsInStr;
229     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
230         [](const std::u16string &arg) {
231         return Str16ToStr8(arg);
232     });
233     std::string result;
234 
235     int32_t ret = ERR_OK;
236 
237     if (argsInStr.size() == NO_DUMP_PARAM_NUMS) {
238         DumpUsage(result);
239     } else {
240         std::vector<std::string> infos;
241         if (argsInStr[0] == "-h") {
242             DumpUsage(result);
243         } else if (argsInStr[0] == "-T") {
244             ret = DelayedSingleton<BgTransientTaskMgr>::GetInstance()->ShellDump(argsInStr, infos);
245         } else if (argsInStr[0] == "-C") {
246             ret = BgContinuousTaskMgr::GetInstance()->ShellDump(argsInStr, infos);
247         } else if (argsInStr[0] == "-E") {
248             ret = DelayedSingleton<BgEfficiencyResourcesMgr>::GetInstance()->ShellDump(argsInStr, infos);
249         } else {
250             infos.emplace_back("Error params.\n");
251             ret = ERR_BGTASK_INVALID_PARAM;
252         }
253         for (auto info : infos) {
254             result.append(info);
255         }
256     }
257 
258     if (!SaveStringToFd(fd, result)) {
259         BGTASK_LOGE("BackgroundTaskMgrService dump save string to fd failed!");
260         ret = ERR_BGTASK_METHOD_CALLED_FAILED;
261     }
262     return ret;
263 }
264 
DumpUsage(std::string & result)265 void BackgroundTaskMgrService::DumpUsage(std::string &result)
266 {
267     std::string dumpHelpMsg =
268     "usage: bgtask dump [<options>]\n"
269     "options list:\n"
270     "    -h                                   help menu\n"
271     "    -T                                   transient task commands:\n"
272     "        BATTARY_LOW                          battary low mode\n"
273     "        BATTARY_OKAY                         battary okay mode\n"
274     "        DUMP_CANCEL                          cancel dump mode\n"
275     "        All                                  list all request\n"
276     "    -C                                   continuous task commands:\n"
277     "        --all                                list all running continuous task infos\n"
278     "        --cancel_all                         cancel all running continuous task\n"
279     "        --cancel {continuous task key}       cancel one task by specifying task key\n"
280     "    -E                                   efficiency resources commands;\n"
281     "        --all                                list all efficiency resource aplications\n"
282     "        --reset_all                          reset all efficiency resource aplications\n"
283     "        --resetapp {uid} {resources}          reset one application of uid by specifying \n"
284     "        --resetproc {pid} {resources}         reset one application of pid by specifying \n";
285 
286     result.append(dumpHelpMsg);
287 }  // namespace
288 }  // namespace BackgroundTaskMgr
289 }  // namespace OHOS
290