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