Debian Codegraph @

apex/jobscheduler/service/java/com/android/server/job/controllers/DeviceIdleJobsController.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17 package com.android.server.job.controllers;
18
19 import static com.android.server.job.JobSchedulerService.sElapsedRealtimeClock;
20
21 import android.app.job.JobInfo;
22 import android.content.BroadcastReceiver;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.IntentFilter;
26 import android.os.Handler;
27 import android.os.Looper;
28 import android.os.Message;
29 import android.os.PowerManager;
30 import android.os.UserHandle;
31 import android.util.ArraySet;
32 import android.util.IndentingPrintWriter;
33 import android.util.Log;
34 import android.util.Slog;
35 import android.util.SparseBooleanArray;
36 import android.util.proto.ProtoOutputStream;
37
38 import com.android.internal.util.ArrayUtils;
39 import com.android.server.DeviceIdleInternal;
40 import com.android.server.LocalServices;
41 import com.android.server.job.JobSchedulerService;
42 import com.android.server.job.StateControllerProto;
43 import com.android.server.job.StateControllerProto.DeviceIdleJobsController.TrackedJob;
44
45 import java.util.Arrays;
46 import java.util.function.Consumer;
47 import java.util.function.Predicate;
48
49 /**
50 * When device is dozing, set constraint for all jobs, except whitelisted apps, as not satisfied.
51 * When device is not dozing, set constraint for all jobs as satisfied.
52 */
53 public final class DeviceIdleJobsController extends StateController {
54 private static final String TAG = "JobScheduler.DeviceIdle";
55 private static final boolean DEBUG = JobSchedulerService.DEBUG
56 || Log.isLoggable(TAG, Log.DEBUG);
57
58 private static final long BACKGROUND_JOBS_DELAY = 3000;
59
60 static final int PROCESS_BACKGROUND_JOBS = 1;
61
62 /**
63 * These are jobs added with a special flag to indicate that they should be exempted from doze
64 * when the app is temp whitelisted or in the foreground.
65 */
66 private final ArraySet<JobStatus> mAllowInIdleJobs;
67 private final SparseBooleanArray mForegroundUids = new SparseBooleanArray();
68 private final DeviceIdleUpdateFunctor mDeviceIdleUpdateFunctor;
69 private final DeviceIdleJobsDelayHandler mHandler;
70 private final PowerManager mPowerManager;
71 private final DeviceIdleInternal mLocalDeviceIdleController;
72
73 /**
74 * True when in device idle mode, so we don't want to schedule any jobs.
75 */
76 private boolean mDeviceIdleMode;
77 private int[] mDeviceIdleWhitelistAppIds;
78 private int[] mPowerSaveTempWhitelistAppIds;
79
80 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
81 @Override
82 public void onReceive(Context context, Intent intent) {
83 switch (intent.getAction()) {
84 case PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED:
85 case PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED:
86 updateIdleMode(mPowerManager != null && (mPowerManager.isDeviceIdleMode()
87 || mPowerManager.isLightDeviceIdleMode()));
88 break;
89 case PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED:
90 synchronized (mLock) {
91 mDeviceIdleWhitelistAppIds =
92 mLocalDeviceIdleController.getPowerSaveWhitelistUserAppIds();
93 if (DEBUG) {
94 Slog.d(TAG, "Got whitelist "
95 + Arrays.toString(mDeviceIdleWhitelistAppIds));
96 }
97 }
98 break;
99 case PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED:
100 synchronized (mLock) {
101 mPowerSaveTempWhitelistAppIds =
102 mLocalDeviceIdleController.getPowerSaveTempWhitelistAppIds();
103 if (DEBUG) {
104 Slog.d(TAG, "Got temp whitelist "
105 + Arrays.toString(mPowerSaveTempWhitelistAppIds));
106 }
107 final ArraySet<JobStatus> changedJobs = new ArraySet<>();
108 final long nowElapsed = sElapsedRealtimeClock.millis();
109 for (int i = 0; i < mAllowInIdleJobs.size(); i++) {
110 if (updateTaskStateLocked(mAllowInIdleJobs.valueAt(i), nowElapsed)) {
111 changedJobs.add(mAllowInIdleJobs.valueAt(i));
112 }
113 }
114 if (changedJobs.size() > 0) {
115 mStateChangedListener.onControllerStateChanged(changedJobs);
116 }
117 }
118 break;
119 }
120 }
121 };
122
123 /** Criteria for whether or not we should a job's rush evaluation when the device exits Doze. */
124 private final Predicate<JobStatus> mShouldRushEvaluation = (jobStatus) ->
125 jobStatus.isRequestedExpeditedJob() || mForegroundUids.get(jobStatus.getSourceUid());
126
127 public DeviceIdleJobsController(JobSchedulerService service) {
128 super(service);
129
130 mHandler = new DeviceIdleJobsDelayHandler(mContext.getMainLooper());
131 // Register for device idle mode changes
132 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
133 mLocalDeviceIdleController =
134 LocalServices.getService(DeviceIdleInternal.class);
135 mDeviceIdleWhitelistAppIds = mLocalDeviceIdleController.getPowerSaveWhitelistUserAppIds();
136 mPowerSaveTempWhitelistAppIds =
137 mLocalDeviceIdleController.getPowerSaveTempWhitelistAppIds();
138 mDeviceIdleUpdateFunctor = new DeviceIdleUpdateFunctor();
139 mAllowInIdleJobs = new ArraySet<>();
140 final IntentFilter filter = new IntentFilter();
141 filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
142 filter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
143 filter.addAction(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
144 filter.addAction(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
145 mContext.registerReceiverAsUser(
146 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
147 }
148
149 void updateIdleMode(boolean enabled) {
150 boolean changed = false;
151 synchronized (mLock) {
152 if (mDeviceIdleMode != enabled) {
153 changed = true;
154 }
155 mDeviceIdleMode = enabled;
156 logDeviceWideConstraintStateToStatsd(JobStatus.CONSTRAINT_DEVICE_NOT_DOZING,
157 !mDeviceIdleMode);
158 if (DEBUG) Slog.d(TAG, "mDeviceIdleMode=" + mDeviceIdleMode);
159 mDeviceIdleUpdateFunctor.prepare();
160 if (enabled) {
161 mHandler.removeMessages(PROCESS_BACKGROUND_JOBS);
162 mService.getJobStore().forEachJob(mDeviceIdleUpdateFunctor);
163 } else {
164 // When coming out of doze, process all foreground uids and EJs immediately,
165 // while others will be processed after a delay of 3 seconds.
166 mService.getJobStore().forEachJob(mShouldRushEvaluation, mDeviceIdleUpdateFunctor);
167 mHandler.sendEmptyMessageDelayed(PROCESS_BACKGROUND_JOBS, BACKGROUND_JOBS_DELAY);
168 }
169 }
170 // Inform the job scheduler service about idle mode changes
171 if (changed) {
172 mStateChangedListener.onDeviceIdleStateChanged(enabled);
173 }
174 }
175
176 /**
177 * Called by jobscheduler service to report uid state changes between active and idle
178 */
179 public void setUidActiveLocked(int uid, boolean active) {
180 final boolean changed = (active != mForegroundUids.get(uid));
181 if (!changed) {
182 return;
183 }
184 if (DEBUG) {
185 Slog.d(TAG, "uid " + uid + " going " + (active ? "active" : "inactive"));
186 }
187 mForegroundUids.put(uid, active);
188 mDeviceIdleUpdateFunctor.prepare();
189 mService.getJobStore().forEachJobForSourceUid(uid, mDeviceIdleUpdateFunctor);
190 if (mDeviceIdleUpdateFunctor.mChangedJobs.size() > 0) {
191 mStateChangedListener.onControllerStateChanged(mDeviceIdleUpdateFunctor.mChangedJobs);
192 }
193 }
194
195 /**
196 * Checks if the given job's scheduling app id exists in the device idle user whitelist.
197 */
198 boolean isWhitelistedLocked(JobStatus job) {
199 return Arrays.binarySearch(mDeviceIdleWhitelistAppIds,
200 UserHandle.getAppId(job.getSourceUid())) >= 0;
201 }
202
203 /**
204 * Checks if the given job's scheduling app id exists in the device idle temp whitelist.
205 */
206 boolean isTempWhitelistedLocked(JobStatus job) {
207 return ArrayUtils.contains(mPowerSaveTempWhitelistAppIds,
208 UserHandle.getAppId(job.getSourceUid()));
209 }
210
211 private boolean updateTaskStateLocked(JobStatus task, final long nowElapsed) {
212 final boolean allowInIdle = ((task.getFlags()&JobInfo.FLAG_IMPORTANT_WHILE_FOREGROUND) != 0)
213 && (mForegroundUids.get(task.getSourceUid()) || isTempWhitelistedLocked(task));
214 final boolean whitelisted = isWhitelistedLocked(task);
215 final boolean enableTask = !mDeviceIdleMode || whitelisted || allowInIdle;
216 return task.setDeviceNotDozingConstraintSatisfied(nowElapsed, enableTask, whitelisted);
217 }
218
219 @Override
220 public void maybeStartTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
221 if ((jobStatus.getFlags()&JobInfo.FLAG_IMPORTANT_WHILE_FOREGROUND) != 0) {
222 mAllowInIdleJobs.add(jobStatus);
223 }
224 updateTaskStateLocked(jobStatus, sElapsedRealtimeClock.millis());
225 }
226
227 @Override
228 public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
229 boolean forUpdate) {
230 if ((jobStatus.getFlags()&JobInfo.FLAG_IMPORTANT_WHILE_FOREGROUND) != 0) {
231 mAllowInIdleJobs.remove(jobStatus);
232 }
233 }
234
235 @Override
236 public void dumpControllerStateLocked(final IndentingPrintWriter pw,
237 final Predicate<JobStatus> predicate) {
238 pw.println("Idle mode: " + mDeviceIdleMode);
239 pw.println();
240
241 mService.getJobStore().forEachJob(predicate, (jobStatus) -> {
242 pw.print("#");
243 jobStatus.printUniqueId(pw);
244 pw.print(" from ");
245 UserHandle.formatUid(pw, jobStatus.getSourceUid());
246 pw.print(": ");
247 pw.print(jobStatus.getSourcePackageName());
248 pw.print((jobStatus.satisfiedConstraints
249 & JobStatus.CONSTRAINT_DEVICE_NOT_DOZING) != 0
250 ? " RUNNABLE" : " WAITING");
251 if (jobStatus.appHasDozeExemption) {
252 pw.print(" WHITELISTED");
253 }
254 if (mAllowInIdleJobs.contains(jobStatus)) {
255 pw.print(" ALLOWED_IN_DOZE");
256 }
257 pw.println();
258 });
259 }
260
261 @Override
262 public void dumpControllerStateLocked(ProtoOutputStream proto, long fieldId,
263 Predicate<JobStatus> predicate) {
264 final long token = proto.start(fieldId);
265 final long mToken = proto.start(StateControllerProto.DEVICE_IDLE);
266
267 proto.write(StateControllerProto.DeviceIdleJobsController.IS_DEVICE_IDLE_MODE,
268 mDeviceIdleMode);
269 mService.getJobStore().forEachJob(predicate, (jobStatus) -> {
270 final long jsToken =
271 proto.start(StateControllerProto.DeviceIdleJobsController.TRACKED_JOBS);
272
273 jobStatus.writeToShortProto(proto, TrackedJob.INFO);
274 proto.write(TrackedJob.SOURCE_UID, jobStatus.getSourceUid());
275 proto.write(TrackedJob.SOURCE_PACKAGE_NAME, jobStatus.getSourcePackageName());
276 proto.write(TrackedJob.ARE_CONSTRAINTS_SATISFIED,
277 (jobStatus.satisfiedConstraints & JobStatus.CONSTRAINT_DEVICE_NOT_DOZING) != 0);
278 proto.write(TrackedJob.IS_DOZE_WHITELISTED, jobStatus.appHasDozeExemption);
279 proto.write(TrackedJob.IS_ALLOWED_IN_DOZE, mAllowInIdleJobs.contains(jobStatus));
280
281 proto.end(jsToken);
282 });
283
284 proto.end(mToken);
285 proto.end(token);
286 }
287
288 final class DeviceIdleUpdateFunctor implements Consumer<JobStatus> {
289 final ArraySet<JobStatus> mChangedJobs = new ArraySet<>();
290 long mUpdateTimeElapsed = 0;
291
292 void prepare() {
293 mChangedJobs.clear();
294 mUpdateTimeElapsed = sElapsedRealtimeClock.millis();
295 }
296
297 @Override
298 public void accept(JobStatus jobStatus) {
299 if (updateTaskStateLocked(jobStatus, mUpdateTimeElapsed)) {
300 mChangedJobs.add(jobStatus);
301 }
302 }
303 }
304
305 final class DeviceIdleJobsDelayHandler extends Handler {
306 public DeviceIdleJobsDelayHandler(Looper looper) {
307 super(looper);
308 }
309
310 @Override
311 public void handleMessage(Message msg) {
312 switch (msg.what) {
313 case PROCESS_BACKGROUND_JOBS:
314 // Just process all the jobs, the ones in foreground should already be running.
315 synchronized (mLock) {
316 mDeviceIdleUpdateFunctor.prepare();
317 mService.getJobStore().forEachJob(mDeviceIdleUpdateFunctor);
318 if (mDeviceIdleUpdateFunctor.mChangedJobs.size() > 0) {
319 mStateChangedListener.onControllerStateChanged(
320 mDeviceIdleUpdateFunctor.mChangedJobs);
321 }
322 }
323 break;
324 }
325 }
326 }
327 }