blob: a0d0d777637ffe3e8152bc6a19153c895c0c87ba [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 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
17package com.android.server.job;
18
Christopher Tateb5c07882016-05-26 17:11:09 -070019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21
Shreyas Basarge5db09082016-01-07 13:38:29 +000022import java.io.FileDescriptor;
23import java.io.PrintWriter;
24import java.util.ArrayList;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070025import java.util.Arrays;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070026import java.util.Collections;
27import java.util.Comparator;
Shreyas Basarge5db09082016-01-07 13:38:29 +000028import java.util.Iterator;
29import java.util.List;
30
Christopher Tateee7805b2016-07-15 16:56:56 -070031import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070032import android.app.ActivityManager;
Christopher Tate5568f542014-06-18 13:53:31 -070033import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070034import android.app.IUidObserver;
Christopher Tate7060b042014-06-09 19:50:00 -070035import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000036import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070037import android.app.job.JobScheduler;
38import android.app.job.JobService;
Shreyas Basarge5db09082016-01-07 13:38:29 +000039import android.app.job.IJobScheduler;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070040import android.app.job.JobWorkItem;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.content.BroadcastReceiver;
42import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070043import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070044import android.content.Context;
45import android.content.Intent;
46import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070047import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070048import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070049import android.content.pm.ServiceInfo;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060050import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070051import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070052import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070053import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070054import android.os.Binder;
55import android.os.Handler;
56import android.os.Looper;
57import android.os.Message;
Shreyas Basargecbf5ae92016-03-08 16:13:06 +000058import android.os.Process;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070059import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070060import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080061import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070062import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070063import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070064import android.os.SystemClock;
65import android.os.UserHandle;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070066import android.provider.Settings;
67import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070068import android.util.Slog;
69import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080070import android.util.SparseIntArray;
71import android.util.TimeUtils;
Christopher Tate5d346052016-03-08 12:56:08 -080072
Dianne Hackbornfdb19562014-07-11 16:03:36 -070073import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070074import com.android.internal.app.procstats.ProcessStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070075import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060076import com.android.internal.util.DumpUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080077import com.android.server.DeviceIdleController;
78import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080079import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080080import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070081import com.android.server.job.controllers.BatteryController;
82import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080083import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070084import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070085import com.android.server.job.controllers.IdleController;
86import com.android.server.job.controllers.JobStatus;
87import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070088import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070089import com.android.server.job.controllers.TimeController;
90
Jeff Sharkey822cbd12016-02-25 11:09:55 -070091import libcore.util.EmptyArray;
92
Christopher Tate7060b042014-06-09 19:50:00 -070093/**
94 * Responsible for taking jobs representing work to be performed by a client app, and determining
95 * based on the criteria specified when that job should be run against the client application's
96 * endpoint.
97 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
98 * about constraints, or the state of active jobs. It receives callbacks from the various
99 * controllers and completed jobs and operates accordingly.
100 *
101 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
102 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
103 * @hide
104 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800105public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700106 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800107 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700108 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800109
Dianne Hackborn970510b2016-02-24 16:56:42 -0800110 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700111 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800112 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800113 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800114 /** The maximum number of jobs that we allow an unprivileged app to schedule */
115 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700116
Christopher Tate2f36fd62016-02-18 18:36:08 -0800117
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800118 /** Global local for all job scheduler state. */
119 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700120 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700121 final JobStore mJobs;
Dianne Hackborn807de782016-04-07 17:54:41 -0700122 /** Tracking amount of time each package runs for. */
123 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700124
125 static final int MSG_JOB_EXPIRED = 0;
126 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700127 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000128 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700129
Christopher Tate7060b042014-06-09 19:50:00 -0700130 /**
131 * Track Services that have currently active or pending jobs. The index is provided by
132 * {@link JobStatus#getServiceToken()}
133 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700134 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700135 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700136 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800137 /** Need direct access to this for testing. */
138 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700139 /** Need direct access to this for testing. */
140 StorageController mStorageController;
Christopher Tate7060b042014-06-09 19:50:00 -0700141 /**
142 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
143 * when ready to execute them.
144 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700145 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700146
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700147 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700148
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700149 final JobHandler mHandler;
150 final JobSchedulerStub mJobSchedulerStub;
151
152 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700153 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800154 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700155
156 /**
157 * Set to true once we are allowed to run third party apps.
158 */
159 boolean mReadyToRock;
160
Christopher Tate7060b042014-06-09 19:50:00 -0700161 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800162 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800163 */
164 boolean mReportedActive;
165
166 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800167 * Current limit on the number of concurrent JobServiceContext entries we want to
168 * keep actively running a job.
169 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700170 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800171
172 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800173 * Which uids are currently in the foreground.
174 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800175 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
176
177 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
178
179 /**
180 * This array essentially stores the state of mActiveServices array.
181 * The ith index stores the job present on the ith JobServiceContext.
182 * We manipulate this array until we arrive at what jobs should be running on
183 * what JobServiceContext.
184 */
185 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
186 /**
187 * Indicates whether we need to act on this jobContext id
188 */
189 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
190 /**
191 * The uid whose jobs we would like to assign to a context.
192 */
193 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800194
195 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700196 * All times are in milliseconds. These constants are kept synchronized with the system
197 * global Settings. Any access to this class or its fields should be done while
198 * holding the JobSchedulerService.mLock lock.
199 */
200 private final class Constants extends ContentObserver {
201 // Key names stored in the settings value.
202 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
203 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800204 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700205 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700206 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
207 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
208 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
209 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
210 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
211 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
212 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
213 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
214 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
215 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
216
217 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
218 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800219 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700220 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700221 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
222 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
223 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
224 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
225 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
226 private static final int DEFAULT_FG_JOB_COUNT = 4;
227 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
228 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700229 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700230 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
231
232 /**
233 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
234 * early.
235 */
236 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
237 /**
238 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
239 * things early.
240 */
241 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
242 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800243 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
244 * schedule things early.
245 */
246 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
247 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700248 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
249 * schedule things early.
250 */
251 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
252 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700253 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
254 * things early. 1 == Run connectivity jobs as soon as ready.
255 */
256 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
257 /**
258 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
259 * schedule things early.
260 */
261 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
262 /**
263 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
264 * running some work early. This (and thus the other min counts) is now set to 1, to
265 * prevent any batching at this level. Since we now do batching through doze, that is
266 * a much better mechanism.
267 */
268 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
269 /**
270 * This is the job execution factor that is considered to be heavy use of the system.
271 */
272 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
273 /**
274 * This is the job execution factor that is considered to be moderate use of the system.
275 */
276 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
277 /**
278 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
279 */
280 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
281 /**
282 * The maximum number of background jobs we allow when the system is in a normal
283 * memory state.
284 */
285 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
286 /**
287 * The maximum number of background jobs we allow when the system is in a moderate
288 * memory state.
289 */
290 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
291 /**
292 * The maximum number of background jobs we allow when the system is in a low
293 * memory state.
294 */
295 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
296 /**
297 * The maximum number of background jobs we allow when the system is in a critical
298 * memory state.
299 */
300 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
301
302 private ContentResolver mResolver;
303 private final KeyValueListParser mParser = new KeyValueListParser(',');
304
305 public Constants(Handler handler) {
306 super(handler);
307 }
308
309 public void start(ContentResolver resolver) {
310 mResolver = resolver;
311 mResolver.registerContentObserver(Settings.Global.getUriFor(
312 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
313 updateConstants();
314 }
315
316 @Override
317 public void onChange(boolean selfChange, Uri uri) {
318 updateConstants();
319 }
320
321 private void updateConstants() {
322 synchronized (mLock) {
323 try {
324 mParser.setString(Settings.Global.getString(mResolver,
325 Settings.Global.ALARM_MANAGER_CONSTANTS));
326 } catch (IllegalArgumentException e) {
327 // Failed to parse the settings string, log this and move on
328 // with defaults.
329 Slog.e(TAG, "Bad device idle settings", e);
330 }
331
332 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
333 DEFAULT_MIN_IDLE_COUNT);
334 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
335 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800336 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
337 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700338 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
339 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700340 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
341 DEFAULT_MIN_CONNECTIVITY_COUNT);
342 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
343 DEFAULT_MIN_CONTENT_COUNT);
344 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
345 DEFAULT_MIN_READY_JOBS_COUNT);
346 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
347 DEFAULT_HEAVY_USE_FACTOR);
348 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
349 DEFAULT_MODERATE_USE_FACTOR);
350 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
351 DEFAULT_FG_JOB_COUNT);
352 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
353 DEFAULT_BG_NORMAL_JOB_COUNT);
354 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
355 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
356 }
357 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
358 DEFAULT_BG_MODERATE_JOB_COUNT);
359 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
360 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
361 }
362 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
363 DEFAULT_BG_LOW_JOB_COUNT);
364 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
365 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
366 }
367 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
368 DEFAULT_BG_CRITICAL_JOB_COUNT);
369 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
370 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
371 }
372 }
373 }
374
375 void dump(PrintWriter pw) {
376 pw.println(" Settings:");
377
378 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
379 pw.print(MIN_IDLE_COUNT); pw.println();
380
381 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
382 pw.print(MIN_CHARGING_COUNT); pw.println();
383
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800384 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
385 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
386
Dianne Hackborn532ea262017-03-17 17:50:55 -0700387 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
388 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
389
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700390 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
391 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
392
393 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
394 pw.print(MIN_CONTENT_COUNT); pw.println();
395
396 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
397 pw.print(MIN_READY_JOBS_COUNT); pw.println();
398
399 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
400 pw.print(HEAVY_USE_FACTOR); pw.println();
401
402 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
403 pw.print(MODERATE_USE_FACTOR); pw.println();
404
405 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
406 pw.print(FG_JOB_COUNT); pw.println();
407
408 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
409 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
410
411 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
412 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
413
414 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
415 pw.print(BG_LOW_JOB_COUNT); pw.println();
416
417 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
418 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
419 }
420 }
421
422 final Constants mConstants;
423
424 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700425 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
426 * still clean up. On reinstall the package will have a new uid.
427 */
428 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
429 @Override
430 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700431 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700432 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700433 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700434 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700435 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700436 // Purge the app's jobs if the whole package was just disabled. When this is
437 // the case the component name will be a bare package name.
438 final String pkgName = getPackageName(intent);
439 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
440 if (pkgName != null && pkgUid != -1) {
441 final String[] changedComponents = intent.getStringArrayExtra(
442 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
443 if (changedComponents != null) {
444 for (String component : changedComponents) {
445 if (component.equals(pkgName)) {
446 if (DEBUG) {
447 Slog.d(TAG, "Package state change: " + pkgName);
448 }
449 try {
450 final int userId = UserHandle.getUserId(pkgUid);
451 IPackageManager pm = AppGlobals.getPackageManager();
452 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
453 if (state == COMPONENT_ENABLED_STATE_DISABLED
454 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
455 if (DEBUG) {
456 Slog.d(TAG, "Removing jobs for package " + pkgName
457 + " in user " + userId);
458 }
Dianne Hackborne07641d2016-11-09 15:07:23 -0800459 cancelJobsForUid(pkgUid);
Christopher Tateb5c07882016-05-26 17:11:09 -0700460 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700461 } catch (RemoteException|IllegalArgumentException e) {
462 /*
463 * IllegalArgumentException means that the package doesn't exist.
464 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
465 * behind outright uninstall, so by the time we try to act it's gone.
466 * We don't need to act on this PACKAGE_CHANGED when this happens;
467 * we'll get a PACKAGE_REMOVED later and clean up then.
468 *
469 * RemoteException can't actually happen; the package manager is
470 * running in this same process.
471 */
472 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700473 break;
474 }
475 }
476 }
477 } else {
478 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
479 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700480 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700481 // If this is an outright uninstall rather than the first half of an
482 // app update sequence, cancel the jobs associated with the app.
483 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
484 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
485 if (DEBUG) {
486 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
487 }
Dianne Hackborne07641d2016-11-09 15:07:23 -0800488 cancelJobsForUid(uidRemoved);
Christopher Tate7060b042014-06-09 19:50:00 -0700489 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700490 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700491 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
492 if (DEBUG) {
493 Slog.d(TAG, "Removing jobs for user: " + userId);
494 }
495 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700496 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
497 // Has this package scheduled any jobs, such that we will take action
498 // if it were to be force-stopped?
499 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
500 final String pkgName = intent.getData().getSchemeSpecificPart();
501 if (pkgUid != -1) {
502 List<JobStatus> jobsForUid;
503 synchronized (mLock) {
504 jobsForUid = mJobs.getJobsByUid(pkgUid);
505 }
506 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
507 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
508 if (DEBUG) {
509 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
510 + pkgUid + " has jobs");
511 }
512 setResultCode(Activity.RESULT_OK);
513 break;
514 }
515 }
516 }
517 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
518 // possible force-stop
519 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
520 final String pkgName = intent.getData().getSchemeSpecificPart();
521 if (pkgUid != -1) {
522 if (DEBUG) {
523 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
524 }
525 cancelJobsForPackageAndUid(pkgName, pkgUid);
526 }
Christopher Tate7060b042014-06-09 19:50:00 -0700527 }
528 }
529 };
530
Christopher Tateb5c07882016-05-26 17:11:09 -0700531 private String getPackageName(Intent intent) {
532 Uri uri = intent.getData();
533 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
534 return pkg;
535 }
536
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700537 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Sudheer Shanka80255802017-03-04 14:48:53 -0800538 @Override public void onUidStateChanged(int uid, int procState,
539 long procStateSeq) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800540 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700541 }
542
Dianne Hackborne07641d2016-11-09 15:07:23 -0800543 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800544 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800545 if (disabled) {
546 cancelJobsForUid(uid);
547 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700548 }
549
550 @Override public void onUidActive(int uid) throws RemoteException {
551 }
552
Dianne Hackborne07641d2016-11-09 15:07:23 -0800553 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
554 if (disabled) {
555 cancelJobsForUid(uid);
556 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700557 }
558 };
559
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800560 public Object getLock() {
561 return mLock;
562 }
563
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700564 public JobStore getJobStore() {
565 return mJobs;
566 }
567
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700568 @Override
569 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700570 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
571 // Let's kick any outstanding jobs for this user.
572 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
573 }
574
575 @Override
576 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700577 // Let's kick any outstanding jobs for this user.
578 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
579 }
580
581 @Override
582 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700583 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700584 }
585
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700586 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
587 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700588 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800589 if (ActivityManager.getService().isAppStartModeDisabled(uId,
590 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700591 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
592 + " -- package not allowed to start");
593 return JobScheduler.RESULT_FAILURE;
594 }
595 } catch (RemoteException e) {
596 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800597 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700598 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
599
600 if (work != null && toCancel != null) {
601 // Fast path: we are adding work to an existing job, and the JobInfo is not
602 // changing. We can just directly enqueue this work in to the job.
603 if (toCancel.getJob().equals(job)) {
604 toCancel.enqueueWorkLocked(work);
605 return JobScheduler.RESULT_SUCCESS;
606 }
607 }
608
609 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
610 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800611 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800612 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800613 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
614 Slog.w(TAG, "Too many jobs for uid " + uId);
615 throw new IllegalStateException("Apps may not schedule more than "
616 + MAX_JOBS_PER_APP + " distinct jobs");
617 }
618 }
619
Dianne Hackborna47223f2017-03-30 13:49:13 -0700620 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700621 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700622
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700623 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700624 cancelJobImpl(toCancel, jobStatus);
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700625 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700626 if (work != null) {
627 // If work has been supplied, enqueue it into the new job.
628 jobStatus.enqueueWorkLocked(work);
629 }
630 startTrackingJobLocked(jobStatus, toCancel);
631 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800632 }
Christopher Tate7060b042014-06-09 19:50:00 -0700633 return JobScheduler.RESULT_SUCCESS;
634 }
635
636 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800637 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800638 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
639 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
640 for (int i = jobs.size() - 1; i >= 0; i--) {
641 JobStatus job = jobs.get(i);
642 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700643 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800644 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700645 }
Christopher Tate7060b042014-06-09 19:50:00 -0700646 }
647
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600648 public JobInfo getPendingJob(int uid, int jobId) {
649 synchronized (mLock) {
650 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
651 for (int i = jobs.size() - 1; i >= 0; i--) {
652 JobStatus job = jobs.get(i);
653 if (job.getJobId() == jobId) {
654 return job.getJob();
655 }
656 }
657 return null;
658 }
659 }
660
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700661 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700662 List<JobStatus> jobsForUser;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800663 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700664 jobsForUser = mJobs.getJobsByUser(userHandle);
665 }
666 for (int i=0; i<jobsForUser.size(); i++) {
667 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700668 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700669 }
670 }
671
Christopher Tateee7805b2016-07-15 16:56:56 -0700672 void cancelJobsForPackageAndUid(String pkgName, int uid) {
673 List<JobStatus> jobsForUid;
674 synchronized (mLock) {
675 jobsForUid = mJobs.getJobsByUid(uid);
676 }
677 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
678 final JobStatus job = jobsForUid.get(i);
679 if (job.getSourcePackageName().equals(pkgName)) {
680 cancelJobImpl(job, null);
681 }
682 }
683 }
684
Christopher Tate7060b042014-06-09 19:50:00 -0700685 /**
686 * Entry point from client to cancel all jobs originating from their uid.
687 * This will remove the job from the master list, and cancel the job if it was staged for
688 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700689 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800690 *
Christopher Tate7060b042014-06-09 19:50:00 -0700691 */
Dianne Hackborne07641d2016-11-09 15:07:23 -0800692 public void cancelJobsForUid(int uid) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700693 List<JobStatus> jobsForUid;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800694 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700695 jobsForUid = mJobs.getJobsByUid(uid);
696 }
697 for (int i=0; i<jobsForUid.size(); i++) {
698 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700699 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700700 }
701 }
702
703 /**
704 * Entry point from client to cancel the job corresponding to the jobId provided.
705 * This will remove the job from the master list, and cancel the job if it was staged for
706 * execution or being executed.
707 * @param uid Uid of the calling client.
708 * @param jobId Id of the job, provided at schedule-time.
709 */
710 public void cancelJob(int uid, int jobId) {
711 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800712 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700713 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700714 }
715 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700716 cancelJobImpl(toCancel, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700717 }
718 }
719
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700720 private void cancelJobImpl(JobStatus cancelled, JobStatus incomingJob) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800721 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700722 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
723 cancelled.unprepareLocked(ActivityManager.getService());
724 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
Matthew Williams48a30db2014-09-23 13:39:36 -0700725 // Remove from pending queue.
Dianne Hackborn807de782016-04-07 17:54:41 -0700726 if (mPendingJobs.remove(cancelled)) {
727 mJobPackageTracker.noteNonpending(cancelled);
728 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700729 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000730 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700731 reportActiveLocked();
Matthew Williams48a30db2014-09-23 13:39:36 -0700732 }
Christopher Tate7060b042014-06-09 19:50:00 -0700733 }
734
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800735 void updateUidState(int uid, int procState) {
736 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800737 if (procState == ActivityManager.PROCESS_STATE_TOP) {
738 // Only use this if we are exactly the top app. All others can live
739 // with just the foreground priority. This means that persistent processes
740 // can never be the top app priority... that is fine.
741 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
742 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
743 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800744 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800745 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800746 }
747 }
748 }
749
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700750 @Override
751 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800752 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700753 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600754 // When becoming idle, make sure no jobs are actively running,
755 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700756 for (int i=0; i<mActiveServices.size(); i++) {
757 JobServiceContext jsc = mActiveServices.get(i);
758 final JobStatus executing = jsc.getRunningJob();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600759 if (executing != null
760 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700761 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
762 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700763 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700764 } else {
765 // When coming out of idle, allow thing to start back up.
766 if (mReadyToRock) {
767 if (mLocalDeviceIdleController != null) {
768 if (!mReportedActive) {
769 mReportedActive = true;
770 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700771 }
772 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700773 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700774 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700775 }
776 }
777 }
778
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700779 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000780 // active is true if pending queue contains jobs OR some job is running.
781 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800782 if (mPendingJobs.size() <= 0) {
783 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700784 final JobServiceContext jsc = mActiveServices.get(i);
785 final JobStatus job = jsc.getRunningJob();
786 if (job != null
787 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
788 && !job.dozeWhitelisted) {
789 // We will report active if we have a job running and it is not an exception
790 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800791 active = true;
792 break;
793 }
794 }
795 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000796
797 if (mReportedActive != active) {
798 mReportedActive = active;
799 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800800 mLocalDeviceIdleController.setJobsActive(active);
801 }
802 }
803 }
804
Christopher Tate7060b042014-06-09 19:50:00 -0700805 /**
806 * Initializes the system service.
807 * <p>
808 * Subclasses must define a single argument constructor that accepts the context
809 * and passes it to super.
810 * </p>
811 *
812 * @param context The system server context.
813 */
814 public JobSchedulerService(Context context) {
815 super(context);
Dianne Hackborn970e3f42016-06-01 10:55:13 -0700816 mHandler = new JobHandler(context.getMainLooper());
817 mConstants = new Constants(mHandler);
818 mJobSchedulerStub = new JobSchedulerStub();
819 mJobs = JobStore.initAndGet(this);
820
Christopher Tate7060b042014-06-09 19:50:00 -0700821 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700822 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700823 mControllers.add(ConnectivityController.get(this));
824 mControllers.add(TimeController.get(this));
825 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800826 mBatteryController = BatteryController.get(this);
827 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700828 mStorageController = StorageController.get(this);
829 mControllers.add(mStorageController);
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800830 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800831 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700832 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700833 }
834
835 @Override
836 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000837 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -0700838 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
839 }
840
841 @Override
842 public void onBootPhase(int phase) {
843 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700844 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +0000845 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -0700846 final IntentFilter filter = new IntentFilter();
847 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
848 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -0700849 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
850 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -0700851 filter.addDataScheme("package");
852 getContext().registerReceiverAsUser(
853 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
854 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
855 getContext().registerReceiverAsUser(
856 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000857 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700858 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800859 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800860 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800861 | ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN,
862 null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700863 } catch (RemoteException e) {
864 // ignored; both services live in system_server
865 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700866 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800867 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700868 // Let's go!
869 mReadyToRock = true;
870 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
871 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800872 mLocalDeviceIdleController
873 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700874 // Create the "runners".
875 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
876 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -0700877 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700878 getContext().getMainLooper()));
879 }
880 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -0800881 mJobs.forEachJob(new JobStatusFunctor() {
882 @Override
883 public void process(JobStatus job) {
884 for (int controller = 0; controller < mControllers.size(); controller++) {
885 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800886 sc.maybeStartTrackingJobLocked(job, null);
887 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700888 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800889 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700890 // GO GO GO!
891 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
892 }
Christopher Tate7060b042014-06-09 19:50:00 -0700893 }
894 }
895
896 /**
897 * Called when we have a job status object that we need to insert in our
898 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
899 * about.
900 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700901 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
902 if (!jobStatus.isPreparedLocked()) {
903 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
904 }
905 final boolean update = mJobs.add(jobStatus);
906 if (mReadyToRock) {
907 for (int i = 0; i < mControllers.size(); i++) {
908 StateController controller = mControllers.get(i);
909 if (update) {
910 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700911 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700912 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -0700913 }
Christopher Tate7060b042014-06-09 19:50:00 -0700914 }
915 }
916
917 /**
918 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
919 * object removed.
920 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700921 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700922 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700923 // Deal with any remaining work items in the old job.
924 jobStatus.stopTrackingJobLocked(incomingJob);
925
926 // Remove from store as well as controllers.
927 final boolean removed = mJobs.remove(jobStatus, writeBack);
928 if (removed && mReadyToRock) {
929 for (int i=0; i<mControllers.size(); i++) {
930 StateController controller = mControllers.get(i);
931 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -0700932 }
933 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700934 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -0700935 }
936
Shreyas Basarge5db09082016-01-07 13:38:29 +0000937 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700938 for (int i=0; i<mActiveServices.size(); i++) {
939 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700940 final JobStatus executing = jsc.getRunningJob();
941 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000942 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700943 return true;
944 }
945 }
946 return false;
947 }
948
949 /**
950 * @param job JobStatus we are querying against.
951 * @return Whether or not the job represented by the status object is currently being run or
952 * is pending.
953 */
954 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700955 for (int i=0; i<mActiveServices.size(); i++) {
956 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tateeafb5352016-10-04 16:34:48 -0700957 // The 'unsafe' direct-internal-reference running-job inspector is okay to
958 // use here because we are already holding the necessary lock *and* we
959 // immediately discard the returned object reference, if any; we return
960 // only a boolean state indicator to the caller.
961 final JobStatus running = serviceContext.getRunningJobUnsafeLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700962 if (running != null && running.matches(job.getUid(), job.getJobId())) {
963 return true;
964 }
965 }
966 return false;
967 }
968
Dianne Hackborn807de782016-04-07 17:54:41 -0700969 void noteJobsPending(List<JobStatus> jobs) {
970 for (int i = jobs.size() - 1; i >= 0; i--) {
971 JobStatus job = jobs.get(i);
972 mJobPackageTracker.notePending(job);
973 }
974 }
975
976 void noteJobsNonpending(List<JobStatus> jobs) {
977 for (int i = jobs.size() - 1; i >= 0; i--) {
978 JobStatus job = jobs.get(i);
979 mJobPackageTracker.noteNonpending(job);
980 }
981 }
982
Christopher Tate7060b042014-06-09 19:50:00 -0700983 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700984 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
985 * specify an override deadline on a failed job (the failed job will run even though it's not
986 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
987 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
988 *
Christopher Tate7060b042014-06-09 19:50:00 -0700989 * @param failureToReschedule Provided job status that we will reschedule.
990 * @return A newly instantiated JobStatus with the same constraints as the last job except
991 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700992 *
993 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700994 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700995 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -0700996 final long elapsedNowMillis = SystemClock.elapsedRealtime();
997 final JobInfo job = failureToReschedule.getJob();
998
999 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001000 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1001 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001002
1003 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -07001004 case JobInfo.BACKOFF_POLICY_LINEAR:
1005 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -07001006 break;
1007 default:
1008 if (DEBUG) {
1009 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1010 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001011 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
1012 delayMillis =
1013 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -07001014 break;
1015 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001016 delayMillis =
1017 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001018 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -07001019 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001020 for (int ic=0; ic<mControllers.size(); ic++) {
1021 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001022 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001023 }
1024 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001025 }
1026
1027 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001028 * Called after a periodic has executed so we can reschedule it. We take the last execution
1029 * time of the job to be the time of completion (i.e. the time at which this function is
1030 * called).
Christopher Tate7060b042014-06-09 19:50:00 -07001031 * This could be inaccurate b/c the job can run for as long as
1032 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1033 * to underscheduling at least, rather than if we had taken the last execution time to be the
1034 * start of the execution.
1035 * @return A new job representing the execution criteria for this instantiation of the
1036 * recurring job.
1037 */
1038 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
1039 final long elapsedNow = SystemClock.elapsedRealtime();
1040 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001041 long runEarly = 0L;
1042
1043 // If this periodic was rescheduled it won't have a deadline.
1044 if (periodicToReschedule.hasDeadlineConstraint()) {
1045 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1046 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001047 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001048 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001049 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1050 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001051
1052 if (DEBUG) {
1053 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1054 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1055 }
1056 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
1057 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
1058 }
1059
1060 // JobCompletedListener implementations.
1061
1062 /**
1063 * A job just finished executing. We fetch the
1064 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1065 * whether we want to reschedule we readd it to the controllers.
1066 * @param jobStatus Completed job.
1067 * @param needsReschedule Whether the implementing class should reschedule this job.
1068 */
1069 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001070 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001071 if (DEBUG) {
1072 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1073 }
Shreyas Basarge73f10252016-02-11 17:06:13 +00001074 // Do not write back immediately if this is a periodic job. The job may get lost if system
1075 // shuts down before it is added back.
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001076 if (!stopTrackingJobLocked(jobStatus, null, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001077 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001078 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001079 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001080 // We still want to check for jobs to execute, because this job may have
1081 // scheduled a new job under the same job id, and now we can run it.
1082 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001083 return;
1084 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001085 // Note: there is a small window of time in here where, when rescheduling a job,
1086 // we will stop monitoring its content providers. This should be fixed by stopping
1087 // the old job after scheduling the new one, but since we have no lock held here
1088 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -07001089 if (needsReschedule) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001090 JobStatus rescheduled = getRescheduleJobForFailureLocked(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001091 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001092 rescheduled.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001093 } catch (SecurityException e) {
1094 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduled);
1095 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001096 startTrackingJobLocked(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001097 } else if (jobStatus.getJob().isPeriodic()) {
1098 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001099 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001100 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001101 } catch (SecurityException e) {
1102 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1103 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001104 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001105 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001106 jobStatus.unprepareLocked(ActivityManager.getService());
1107 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001108 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001109 }
1110
1111 // StateChangedListener implementations.
1112
1113 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001114 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1115 * some controller's state has changed, so as to run through the list of jobs and start/stop
1116 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001117 */
1118 @Override
1119 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001120 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001121 }
1122
1123 @Override
1124 public void onRunJobNow(JobStatus jobStatus) {
1125 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1126 }
1127
Christopher Tate7060b042014-06-09 19:50:00 -07001128 private class JobHandler extends Handler {
1129
1130 public JobHandler(Looper looper) {
1131 super(looper);
1132 }
1133
1134 @Override
1135 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001136 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001137 if (!mReadyToRock) {
1138 return;
1139 }
1140 }
Christopher Tate7060b042014-06-09 19:50:00 -07001141 switch (message.what) {
1142 case MSG_JOB_EXPIRED:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001143 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -07001144 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001145 // runNow can be null, which is a controller's way of indicating that its
1146 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001147 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001148 mJobPackageTracker.notePending(runNow);
Christopher Tate7060b042014-06-09 19:50:00 -07001149 mPendingJobs.add(runNow);
1150 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001151 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -07001152 }
Christopher Tate7060b042014-06-09 19:50:00 -07001153 break;
1154 case MSG_CHECK_JOB:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001155 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001156 if (mReportedActive) {
1157 // if jobs are currently being run, queue all ready jobs for execution.
1158 queueReadyJobsForExecutionLockedH();
1159 } else {
1160 // Check the list of jobs and run some of them if we feel inclined.
1161 maybeQueueReadyJobsForExecutionLockedH();
1162 }
1163 }
1164 break;
1165 case MSG_CHECK_JOB_GREEDY:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001166 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001167 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -07001168 }
Christopher Tate7060b042014-06-09 19:50:00 -07001169 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001170 case MSG_STOP_JOB:
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001171 cancelJobImpl((JobStatus)message.obj, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001172 break;
Christopher Tate7060b042014-06-09 19:50:00 -07001173 }
1174 maybeRunPendingJobsH();
1175 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1176 removeMessages(MSG_CHECK_JOB);
1177 }
1178
1179 /**
1180 * Run through list of jobs and execute all possible - at least one is expired so we do
1181 * as many as we can.
1182 */
Matthew Williams48a30db2014-09-23 13:39:36 -07001183 private void queueReadyJobsForExecutionLockedH() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001184 if (DEBUG) {
1185 Slog.d(TAG, "queuing all ready jobs for execution:");
1186 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001187 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001188 mPendingJobs.clear();
1189 mJobs.forEachJob(mReadyQueueFunctor);
1190 mReadyQueueFunctor.postProcess();
1191
Matthew Williams48a30db2014-09-23 13:39:36 -07001192 if (DEBUG) {
1193 final int queuedJobs = mPendingJobs.size();
1194 if (queuedJobs == 0) {
1195 Slog.d(TAG, "No jobs pending.");
1196 } else {
1197 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -07001198 }
Christopher Tate7060b042014-06-09 19:50:00 -07001199 }
1200 }
1201
Christopher Tate2f36fd62016-02-18 18:36:08 -08001202 class ReadyJobQueueFunctor implements JobStatusFunctor {
1203 ArrayList<JobStatus> newReadyJobs;
1204
1205 @Override
1206 public void process(JobStatus job) {
1207 if (isReadyToBeExecutedLocked(job)) {
1208 if (DEBUG) {
1209 Slog.d(TAG, " queued " + job.toShortString());
1210 }
1211 if (newReadyJobs == null) {
1212 newReadyJobs = new ArrayList<JobStatus>();
1213 }
1214 newReadyJobs.add(job);
1215 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
1216 stopJobOnServiceContextLocked(job,
1217 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
1218 }
1219 }
1220
1221 public void postProcess() {
1222 if (newReadyJobs != null) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001223 noteJobsPending(newReadyJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001224 mPendingJobs.addAll(newReadyJobs);
1225 }
1226 newReadyJobs = null;
1227 }
1228 }
1229 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1230
Christopher Tate7060b042014-06-09 19:50:00 -07001231 /**
1232 * The state of at least one job has changed. Here is where we could enforce various
1233 * policies on when we want to execute jobs.
1234 * Right now the policy is such:
1235 * If >1 of the ready jobs is idle mode we send all of them off
1236 * if more than 2 network connectivity jobs are ready we send them all off.
1237 * If more than 4 jobs total are ready we send them all off.
1238 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1239 */
Christopher Tate2f36fd62016-02-18 18:36:08 -08001240 class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1241 int chargingCount;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001242 int batteryNotLowCount;
Dianne Hackborn532ea262017-03-17 17:50:55 -07001243 int storageNotLowCount;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001244 int idleCount;
1245 int backoffCount;
1246 int connectivityCount;
1247 int contentCount;
1248 List<JobStatus> runnableJobs;
1249
1250 public MaybeReadyJobQueueFunctor() {
1251 reset();
1252 }
1253
1254 // Functor method invoked for each job via JobStore.forEachJob()
1255 @Override
1256 public void process(JobStatus job) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001257 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001258 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001259 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1260 job.getJob().getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001261 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1262 + job.getJob().toString() + " -- package not allowed to start");
1263 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001264 return;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001265 }
1266 } catch (RemoteException e) {
1267 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001268 if (job.getNumFailures() > 0) {
1269 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -07001270 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001271 if (job.hasIdleConstraint()) {
1272 idleCount++;
1273 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001274 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()
1275 || job.hasNotRoamingConstraint()) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001276 connectivityCount++;
1277 }
1278 if (job.hasChargingConstraint()) {
1279 chargingCount++;
1280 }
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001281 if (job.hasBatteryNotLowConstraint()) {
1282 batteryNotLowCount++;
1283 }
Dianne Hackborn532ea262017-03-17 17:50:55 -07001284 if (job.hasStorageNotLowConstraint()) {
1285 storageNotLowCount++;
1286 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001287 if (job.hasContentTriggerConstraint()) {
1288 contentCount++;
1289 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001290 if (runnableJobs == null) {
1291 runnableJobs = new ArrayList<>();
1292 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001293 runnableJobs.add(job);
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001294 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001295 stopJobOnServiceContextLocked(job,
1296 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -07001297 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001298 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001299
1300 public void postProcess() {
1301 if (backoffCount > 0 ||
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001302 idleCount >= mConstants.MIN_IDLE_COUNT ||
1303 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1304 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001305 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
Dianne Hackborn532ea262017-03-17 17:50:55 -07001306 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001307 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1308 (runnableJobs != null
1309 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001310 if (DEBUG) {
1311 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
1312 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001313 noteJobsPending(runnableJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001314 mPendingJobs.addAll(runnableJobs);
1315 } else {
1316 if (DEBUG) {
1317 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
1318 }
Christopher Tate7060b042014-06-09 19:50:00 -07001319 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001320
1321 // Be ready for next time
1322 reset();
Matthew Williams48a30db2014-09-23 13:39:36 -07001323 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001324
1325 private void reset() {
1326 chargingCount = 0;
1327 idleCount = 0;
1328 backoffCount = 0;
1329 connectivityCount = 0;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001330 batteryNotLowCount = 0;
Dianne Hackborn532ea262017-03-17 17:50:55 -07001331 storageNotLowCount = 0;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001332 contentCount = 0;
1333 runnableJobs = null;
1334 }
1335 }
1336 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1337
1338 private void maybeQueueReadyJobsForExecutionLockedH() {
1339 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1340
Dianne Hackborn807de782016-04-07 17:54:41 -07001341 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001342 mPendingJobs.clear();
1343 mJobs.forEachJob(mMaybeQueueFunctor);
1344 mMaybeQueueFunctor.postProcess();
Christopher Tate7060b042014-06-09 19:50:00 -07001345 }
1346
1347 /**
1348 * Criteria for moving a job into the pending queue:
1349 * - It's ready.
1350 * - It's not pending.
1351 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001352 * - The user that requested the job is running.
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001353 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -07001354 */
1355 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Christopher Tateb1d64482017-03-15 12:01:22 -07001356 final boolean jobExists = mJobs.containsJob(job);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001357 final boolean jobReady = job.isReady();
1358 final boolean jobPending = mPendingJobs.contains(job);
1359 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001360
1361 final int userId = job.getUserId();
1362 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
Christopher Tateb1d64482017-03-15 12:01:22 -07001363
1364 if (DEBUG) {
1365 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1366 + " exists=" + jobExists
1367 + " ready=" + jobReady + " pending=" + jobPending
1368 + " active=" + jobActive + " userStarted=" + userStarted);
1369 }
1370
1371 // Short circuit: don't do the expensive PM check unless we really think
1372 // we might need to run this job now.
1373 if (!jobExists || !userStarted || !jobReady || jobPending || jobActive) {
1374 return false;
1375 }
1376
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001377 final boolean componentPresent;
1378 try {
1379 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1380 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1381 userId) != null);
1382 } catch (RemoteException e) {
1383 throw e.rethrowAsRuntimeException();
1384 }
1385
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001386 if (DEBUG) {
1387 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001388 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001389 }
Christopher Tateb1d64482017-03-15 12:01:22 -07001390
1391 // Everything else checked out so far, so this is the final yes/no check
1392 return componentPresent;
Christopher Tate7060b042014-06-09 19:50:00 -07001393 }
1394
1395 /**
1396 * Criteria for cancelling an active job:
1397 * - It's not ready
1398 * - It's running on a JSC.
1399 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001400 private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -07001401 return !job.isReady() && isCurrentlyActiveLocked(job);
1402 }
1403
1404 /**
1405 * Reconcile jobs in the pending queue against available execution contexts.
1406 * A controller can force a job into the pending queue even if it's already running, but
1407 * here is where we decide whether to actually execute it.
1408 */
1409 private void maybeRunPendingJobsH() {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001410 synchronized (mLock) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001411 if (DEBUG) {
1412 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1413 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001414 assignJobsToContextsLocked();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001415 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001416 }
1417 }
1418 }
1419
Dianne Hackborn807de782016-04-07 17:54:41 -07001420 private int adjustJobPriority(int curPriority, JobStatus job) {
1421 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1422 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001423 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001424 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001425 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001426 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1427 }
1428 }
1429 return curPriority;
1430 }
1431
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001432 private int evaluateJobPriorityLocked(JobStatus job) {
1433 int priority = job.getPriority();
1434 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001435 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001436 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001437 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1438 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001439 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001440 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001441 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001442 }
1443
Christopher Tate7060b042014-06-09 19:50:00 -07001444 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001445 * Takes jobs from pending queue and runs them on available contexts.
1446 * If no contexts are available, preempts lower priority jobs to
1447 * run higher priority ones.
1448 * Lock on mJobs before calling this function.
1449 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001450 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001451 if (DEBUG) {
1452 Slog.d(TAG, printPendingQueue());
1453 }
1454
Dianne Hackborn970510b2016-02-24 16:56:42 -08001455 int memLevel;
1456 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001457 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001458 } catch (RemoteException e) {
1459 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1460 }
1461 switch (memLevel) {
1462 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001463 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001464 break;
1465 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001466 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001467 break;
1468 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001469 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001470 break;
1471 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001472 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001473 break;
1474 }
1475
1476 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1477 boolean[] act = mTmpAssignAct;
1478 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1479 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001480 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001481 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1482 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001483 final JobStatus status = js.getRunningJob();
1484 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001485 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001486 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1487 numForeground++;
1488 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001489 }
1490 act[i] = false;
1491 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001492 }
1493 if (DEBUG) {
1494 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1495 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001496 for (int i=0; i<mPendingJobs.size(); i++) {
1497 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001498
1499 // If job is already running, go to next job.
1500 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1501 if (jobRunningContext != -1) {
1502 continue;
1503 }
1504
Dianne Hackborn970510b2016-02-24 16:56:42 -08001505 final int priority = evaluateJobPriorityLocked(nextPending);
1506 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001507
Shreyas Basarge5db09082016-01-07 13:38:29 +00001508 // Find a context for nextPending. The context should be available OR
1509 // it should have lowest priority among all running jobs
1510 // (sharing the same Uid as nextPending)
1511 int minPriority = Integer.MAX_VALUE;
1512 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001513 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1514 JobStatus job = contextIdToJobMap[j];
1515 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001516 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001517 if ((numActive < mMaxActiveJobs ||
1518 (priority >= JobInfo.PRIORITY_TOP_APP &&
1519 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001520 (preferredUid == nextPending.getUid() ||
1521 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1522 // This slot is free, and we haven't yet hit the limit on
1523 // concurrent jobs... we can just throw the job in to here.
1524 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001525 break;
1526 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001527 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001528 // the context has a preferred Uid or we have reached the limit on
1529 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001530 continue;
1531 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001532 if (job.getUid() != nextPending.getUid()) {
1533 continue;
1534 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001535 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001536 continue;
1537 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001538 if (minPriority > nextPending.lastEvaluatedPriority) {
1539 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001540 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001541 }
1542 }
1543 if (minPriorityContextId != -1) {
1544 contextIdToJobMap[minPriorityContextId] = nextPending;
1545 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001546 numActive++;
1547 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1548 numForeground++;
1549 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001550 }
1551 }
1552 if (DEBUG) {
1553 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1554 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001555 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001556 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001557 boolean preservePreferredUid = false;
1558 if (act[i]) {
1559 JobStatus js = mActiveServices.get(i).getRunningJob();
1560 if (js != null) {
1561 if (DEBUG) {
1562 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
1563 }
1564 // preferredUid will be set to uid of currently running job.
1565 mActiveServices.get(i).preemptExecutingJob();
1566 preservePreferredUid = true;
1567 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001568 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001569 if (DEBUG) {
1570 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001571 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001572 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001573 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001574 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001575 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001576 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1577 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001578 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001579 if (mPendingJobs.remove(pendingJob)) {
1580 mJobPackageTracker.noteNonpending(pendingJob);
1581 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001582 }
1583 }
1584 if (!preservePreferredUid) {
1585 mActiveServices.get(i).clearPreferredUid();
1586 }
1587 }
1588 }
1589
1590 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1591 for (int i=0; i<map.length; i++) {
1592 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1593 return i;
1594 }
1595 }
1596 return -1;
1597 }
1598
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001599 final class LocalService implements JobSchedulerInternal {
1600
1601 /**
1602 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1603 * jobs are always considered pending.
1604 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001605 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001606 public List<JobInfo> getSystemScheduledPendingJobs() {
1607 synchronized (mLock) {
1608 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1609 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1610 @Override
1611 public void process(JobStatus job) {
1612 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1613 pendingJobs.add(job.getJob());
1614 }
1615 }
1616 });
1617 return pendingJobs;
1618 }
1619 }
1620 }
1621
Shreyas Basarge5db09082016-01-07 13:38:29 +00001622 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001623 * Binder stub trampoline implementation
1624 */
1625 final class JobSchedulerStub extends IJobScheduler.Stub {
1626 /** Cache determination of whether a given app can persist jobs
1627 * key is uid of the calling app; value is undetermined/true/false
1628 */
1629 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1630
1631 // Enforce that only the app itself (or shared uid participant) can schedule a
1632 // job that runs one of the app's services, as well as verifying that the
1633 // named service properly requires the BIND_JOB_SERVICE permission
1634 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001635 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001636 final ComponentName service = job.getService();
1637 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001638 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001639 PackageManager.MATCH_DIRECT_BOOT_AWARE
1640 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001641 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001642 if (si == null) {
1643 throw new IllegalArgumentException("No such service " + service);
1644 }
Christopher Tate7060b042014-06-09 19:50:00 -07001645 if (si.applicationInfo.uid != uid) {
1646 throw new IllegalArgumentException("uid " + uid +
1647 " cannot schedule job in " + service.getPackageName());
1648 }
1649 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1650 throw new IllegalArgumentException("Scheduled service " + service
1651 + " does not require android.permission.BIND_JOB_SERVICE permission");
1652 }
Christopher Tate5568f542014-06-18 13:53:31 -07001653 } catch (RemoteException e) {
1654 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001655 }
1656 }
1657
1658 private boolean canPersistJobs(int pid, int uid) {
1659 // If we get this far we're good to go; all we need to do now is check
1660 // whether the app is allowed to persist its scheduled work.
1661 final boolean canPersist;
1662 synchronized (mPersistCache) {
1663 Boolean cached = mPersistCache.get(uid);
1664 if (cached != null) {
1665 canPersist = cached.booleanValue();
1666 } else {
1667 // Persisting jobs is tantamount to running at boot, so we permit
1668 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1669 // permission
1670 int result = getContext().checkPermission(
1671 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1672 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1673 mPersistCache.put(uid, canPersist);
1674 }
1675 }
1676 return canPersist;
1677 }
1678
1679 // IJobScheduler implementation
1680 @Override
1681 public int schedule(JobInfo job) throws RemoteException {
1682 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001683 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001684 }
1685 final int pid = Binder.getCallingPid();
1686 final int uid = Binder.getCallingUid();
1687
1688 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001689 if (job.isPersisted()) {
1690 if (!canPersistJobs(pid, uid)) {
1691 throw new IllegalArgumentException("Error: requested job be persisted without"
1692 + " holding RECEIVE_BOOT_COMPLETED permission.");
1693 }
1694 }
Christopher Tate7060b042014-06-09 19:50:00 -07001695
Jeff Sharkey785f4942016-07-14 10:31:15 -06001696 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1697 getContext().enforceCallingOrSelfPermission(
1698 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1699 }
1700
Christopher Tate7060b042014-06-09 19:50:00 -07001701 long ident = Binder.clearCallingIdentity();
1702 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001703 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, -1, null);
1704 } finally {
1705 Binder.restoreCallingIdentity(ident);
1706 }
1707 }
1708
1709 // IJobScheduler implementation
1710 @Override
1711 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
1712 if (DEBUG) {
1713 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
1714 }
1715 final int pid = Binder.getCallingPid();
1716 final int uid = Binder.getCallingUid();
1717
1718 enforceValidJobRequest(uid, job);
1719 if (job.isPersisted()) {
1720 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
1721 }
1722 if (work == null) {
1723 throw new NullPointerException("work is null");
1724 }
1725
1726 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1727 getContext().enforceCallingOrSelfPermission(
1728 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1729 }
1730
1731 long ident = Binder.clearCallingIdentity();
1732 try {
1733 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, -1, null);
Christopher Tate7060b042014-06-09 19:50:00 -07001734 } finally {
1735 Binder.restoreCallingIdentity(ident);
1736 }
1737 }
1738
1739 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001740 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001741 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001742 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001743 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001744 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1745 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001746 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001747
1748 if (packageName == null) {
1749 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001750 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001751
1752 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1753 android.Manifest.permission.UPDATE_DEVICE_STATS);
1754 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1755 throw new SecurityException("Caller uid " + callerUid
1756 + " not permitted to schedule jobs for other apps");
1757 }
1758
Jeff Sharkey4f100402016-05-03 17:44:23 -06001759 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1760 getContext().enforceCallingOrSelfPermission(
1761 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1762 }
1763
Shreyas Basarge968ac752016-01-11 23:09:26 +00001764 long ident = Binder.clearCallingIdentity();
1765 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001766 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001767 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001768 } finally {
1769 Binder.restoreCallingIdentity(ident);
1770 }
1771 }
1772
1773 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001774 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1775 final int uid = Binder.getCallingUid();
1776
1777 long ident = Binder.clearCallingIdentity();
1778 try {
1779 return JobSchedulerService.this.getPendingJobs(uid);
1780 } finally {
1781 Binder.restoreCallingIdentity(ident);
1782 }
1783 }
1784
1785 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001786 public JobInfo getPendingJob(int jobId) throws RemoteException {
1787 final int uid = Binder.getCallingUid();
1788
1789 long ident = Binder.clearCallingIdentity();
1790 try {
1791 return JobSchedulerService.this.getPendingJob(uid, jobId);
1792 } finally {
1793 Binder.restoreCallingIdentity(ident);
1794 }
1795 }
1796
1797 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001798 public void cancelAll() throws RemoteException {
1799 final int uid = Binder.getCallingUid();
1800
1801 long ident = Binder.clearCallingIdentity();
1802 try {
Dianne Hackborne07641d2016-11-09 15:07:23 -08001803 JobSchedulerService.this.cancelJobsForUid(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001804 } finally {
1805 Binder.restoreCallingIdentity(ident);
1806 }
1807 }
1808
1809 @Override
1810 public void cancel(int jobId) throws RemoteException {
1811 final int uid = Binder.getCallingUid();
1812
1813 long ident = Binder.clearCallingIdentity();
1814 try {
1815 JobSchedulerService.this.cancelJob(uid, jobId);
1816 } finally {
1817 Binder.restoreCallingIdentity(ident);
1818 }
1819 }
1820
1821 /**
1822 * "dumpsys" infrastructure
1823 */
1824 @Override
1825 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001826 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07001827
1828 long identityToken = Binder.clearCallingIdentity();
1829 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001830 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07001831 } finally {
1832 Binder.restoreCallingIdentity(identityToken);
1833 }
1834 }
Christopher Tate5d346052016-03-08 12:56:08 -08001835
1836 @Override
1837 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001838 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08001839 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07001840 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08001841 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001842 };
1843
Christopher Tate5d346052016-03-08 12:56:08 -08001844 // Shell command infrastructure: run the given job immediately
1845 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
1846 if (DEBUG) {
1847 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
1848 + " " + jobId + " f=" + force);
1849 }
1850
1851 try {
1852 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0, userId);
1853 if (uid < 0) {
1854 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
1855 }
1856
1857 synchronized (mLock) {
1858 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
1859 if (js == null) {
1860 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
1861 }
1862
1863 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
1864 if (!js.isConstraintsSatisfied()) {
1865 js.overrideState = 0;
1866 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
1867 }
1868
1869 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
1870 }
1871 } catch (RemoteException e) {
1872 // can't happen
1873 }
1874 return 0;
1875 }
1876
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001877 void setMonitorBattery(boolean enabled) {
1878 synchronized (mLock) {
1879 if (mBatteryController != null) {
1880 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
1881 }
1882 }
1883 }
1884
1885 int getBatterySeq() {
1886 synchronized (mLock) {
1887 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
1888 }
1889 }
1890
1891 boolean getBatteryCharging() {
1892 synchronized (mLock) {
1893 return mBatteryController != null
1894 ? mBatteryController.getTracker().isOnStablePower() : false;
1895 }
1896 }
1897
1898 boolean getBatteryNotLow() {
1899 synchronized (mLock) {
1900 return mBatteryController != null
1901 ? mBatteryController.getTracker().isBatteryNotLow() : false;
1902 }
1903 }
1904
Dianne Hackborn532ea262017-03-17 17:50:55 -07001905 int getStorageSeq() {
1906 synchronized (mLock) {
1907 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
1908 }
1909 }
1910
1911 boolean getStorageNotLow() {
1912 synchronized (mLock) {
1913 return mStorageController != null
1914 ? mStorageController.getTracker().isStorageNotLow() : false;
1915 }
1916 }
1917
Shreyas Basarge5db09082016-01-07 13:38:29 +00001918 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1919 StringBuilder s = new StringBuilder(initial + ": ");
1920 for (int i=0; i<map.length; i++) {
1921 s.append("(")
1922 .append(map[i] == null? -1: map[i].getJobId())
1923 .append(map[i] == null? -1: map[i].getUid())
1924 .append(")" );
1925 }
1926 return s.toString();
1927 }
1928
1929 private String printPendingQueue() {
1930 StringBuilder s = new StringBuilder("Pending queue: ");
1931 Iterator<JobStatus> it = mPendingJobs.iterator();
1932 while (it.hasNext()) {
1933 JobStatus js = it.next();
1934 s.append("(")
1935 .append(js.getJob().getId())
1936 .append(", ")
1937 .append(js.getUid())
1938 .append(") ");
1939 }
1940 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001941 }
Christopher Tate7060b042014-06-09 19:50:00 -07001942
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001943 static void dumpHelp(PrintWriter pw) {
1944 pw.println("Job Scheduler (jobscheduler) dump options:");
1945 pw.println(" [-h] [package] ...");
1946 pw.println(" -h: print this help");
1947 pw.println(" [package] is an optional package name to limit the output to.");
1948 }
1949
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001950 void dumpInternal(final PrintWriter pw, String[] args) {
1951 int filterUid = -1;
1952 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001953 int opti = 0;
1954 while (opti < args.length) {
1955 String arg = args[opti];
1956 if ("-h".equals(arg)) {
1957 dumpHelp(pw);
1958 return;
1959 } else if ("-a".equals(arg)) {
1960 // Ignore, we always dump all.
1961 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
1962 pw.println("Unknown option: " + arg);
1963 return;
1964 } else {
1965 break;
1966 }
1967 opti++;
1968 }
1969 if (opti < args.length) {
1970 String pkg = args[opti];
1971 try {
1972 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001973 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001974 } catch (NameNotFoundException ignored) {
1975 pw.println("Invalid package: " + pkg);
1976 return;
1977 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001978 }
1979 }
1980
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001981 final int filterUidFinal = UserHandle.getAppId(filterUid);
Christopher Tatef973a7b2014-08-29 12:54:08 -07001982 final long now = SystemClock.elapsedRealtime();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001983 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001984 mConstants.dump(pw);
1985 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001986 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001987 pw.print("Registered ");
1988 pw.print(mJobs.size());
1989 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07001990 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001991 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
1992 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001993 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001994 public int compare(JobStatus o1, JobStatus o2) {
1995 int uid1 = o1.getUid();
1996 int uid2 = o2.getUid();
1997 int id1 = o1.getJobId();
1998 int id2 = o2.getJobId();
1999 if (uid1 != uid2) {
2000 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002001 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002002 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08002003 }
2004 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002005 for (JobStatus job : jobs) {
2006 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2007 pw.println(job.toShortStringExceptUniqueId());
2008
2009 // Skip printing details if the caller requested a filter
2010 if (!job.shouldDump(filterUidFinal)) {
2011 continue;
2012 }
2013
2014 job.dump(pw, " ", true);
2015 pw.print(" Ready: ");
2016 pw.print(mHandler.isReadyToBeExecutedLocked(job));
2017 pw.print(" (job=");
2018 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002019 pw.print(" user=");
2020 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002021 pw.print(" !pending=");
2022 pw.print(!mPendingJobs.contains(job));
2023 pw.print(" !active=");
2024 pw.print(!isCurrentlyActiveLocked(job));
2025 pw.print(" comp=");
2026 boolean componentPresent = false;
2027 try {
2028 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2029 job.getServiceComponent(),
2030 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2031 job.getUserId()) != null);
2032 } catch (RemoteException e) {
2033 }
2034 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002035 pw.println(")");
2036 }
Christopher Tate7060b042014-06-09 19:50:00 -07002037 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002038 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002039 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002040 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002041 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002042 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002043 }
2044 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002045 pw.println("Uid priority overrides:");
2046 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002047 int uid = mUidPriorityOverride.keyAt(i);
2048 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2049 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2050 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2051 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002052 }
2053 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002054 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002055 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002056 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2057 pw.println();
2058 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002059 pw.println("Pending queue:");
2060 for (int i=0; i<mPendingJobs.size(); i++) {
2061 JobStatus job = mPendingJobs.get(i);
2062 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2063 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002064 job.dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002065 int priority = evaluateJobPriorityLocked(job);
2066 if (priority != JobInfo.PRIORITY_DEFAULT) {
2067 pw.print(" Evaluated priority: "); pw.println(priority);
2068 }
2069 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002070 pw.print(" Enq: ");
2071 TimeUtils.formatDuration(now - job.madePending, pw);
2072 pw.println(" ago");
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002073 }
Christopher Tate7060b042014-06-09 19:50:00 -07002074 pw.println();
2075 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002076 for (int i=0; i<mActiveServices.size(); i++) {
2077 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002078 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002079 final JobStatus job = jsc.getRunningJob();
2080 if (job == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002081 pw.println("inactive");
Christopher Tate7060b042014-06-09 19:50:00 -07002082 continue;
2083 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002084 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002085 pw.print(" Running for: ");
2086 TimeUtils.formatDuration(now - jsc.getExecutionStartTimeElapsed(), pw);
2087 pw.print(", timeout at: ");
2088 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - now, pw);
2089 pw.println();
Christopher Tate7234fc62017-04-03 17:36:07 -07002090 job.dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002091 int priority = evaluateJobPriorityLocked(jsc.getRunningJob());
2092 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002093 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002094 }
Christopher Tate7234fc62017-04-03 17:36:07 -07002095 pw.print(" Active at "); pw.println(job.madeActive);
2096 pw.print(" Pending for ");
2097 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2098 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002099 }
2100 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002101 if (filterUid == -1) {
2102 pw.println();
2103 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2104 pw.print("mReportedActive="); pw.println(mReportedActive);
2105 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2106 }
Christopher Tate7060b042014-06-09 19:50:00 -07002107 }
2108 pw.println();
2109 }
2110}