blob: 260f05f809cff4c830537294b31748be755abf2c [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;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070066import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070067import android.provider.Settings;
68import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070069import android.util.Slog;
70import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080071import android.util.SparseIntArray;
72import android.util.TimeUtils;
Christopher Tate5d346052016-03-08 12:56:08 -080073
Dianne Hackbornfdb19562014-07-11 16:03:36 -070074import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070075import com.android.internal.app.procstats.ProcessStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070076import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060077import com.android.internal.util.DumpUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080078import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070079import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080080import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080081import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080082import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070083import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070084import com.android.server.job.controllers.BatteryController;
85import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080086import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070087import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070088import com.android.server.job.controllers.IdleController;
89import com.android.server.job.controllers.JobStatus;
90import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070091import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070092import com.android.server.job.controllers.TimeController;
93
Jeff Sharkey822cbd12016-02-25 11:09:55 -070094import libcore.util.EmptyArray;
95
Christopher Tate7060b042014-06-09 19:50:00 -070096/**
97 * Responsible for taking jobs representing work to be performed by a client app, and determining
98 * based on the criteria specified when that job should be run against the client application's
99 * endpoint.
100 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
101 * about constraints, or the state of active jobs. It receives callbacks from the various
102 * controllers and completed jobs and operates accordingly.
103 *
104 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
105 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
106 * @hide
107 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800108public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700109 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800110 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700111 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800112
Dianne Hackborn970510b2016-02-24 16:56:42 -0800113 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700114 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800115 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800116 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800117 /** The maximum number of jobs that we allow an unprivileged app to schedule */
118 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700119
Christopher Tate2f36fd62016-02-18 18:36:08 -0800120
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800121 /** Global local for all job scheduler state. */
122 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700123 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700124 final JobStore mJobs;
Dianne Hackborn807de782016-04-07 17:54:41 -0700125 /** Tracking amount of time each package runs for. */
126 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700127
128 static final int MSG_JOB_EXPIRED = 0;
129 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700130 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000131 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700132
Christopher Tate7060b042014-06-09 19:50:00 -0700133 /**
134 * Track Services that have currently active or pending jobs. The index is provided by
135 * {@link JobStatus#getServiceToken()}
136 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700137 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700138 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700139 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800140 /** Need direct access to this for testing. */
141 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700142 /** Need direct access to this for testing. */
143 StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700144 /** Need directly for sending uid state changes */
145 private BackgroundJobsController mBackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700146 /**
147 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
148 * when ready to execute them.
149 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700150 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700151
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700152 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700153
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700154 final JobHandler mHandler;
155 final JobSchedulerStub mJobSchedulerStub;
156
157 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700158 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800159 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700160
161 /**
162 * Set to true once we are allowed to run third party apps.
163 */
164 boolean mReadyToRock;
165
Christopher Tate7060b042014-06-09 19:50:00 -0700166 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800167 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800168 */
169 boolean mReportedActive;
170
171 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800172 * Current limit on the number of concurrent JobServiceContext entries we want to
173 * keep actively running a job.
174 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700175 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800176
177 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800178 * Which uids are currently in the foreground.
179 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800180 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
181
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700182 /**
183 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
184 */
185 final SparseIntArray mBackingUpUids = new SparseIntArray();
186
Dianne Hackborn970510b2016-02-24 16:56:42 -0800187 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
188
189 /**
190 * This array essentially stores the state of mActiveServices array.
191 * The ith index stores the job present on the ith JobServiceContext.
192 * We manipulate this array until we arrive at what jobs should be running on
193 * what JobServiceContext.
194 */
195 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
196 /**
197 * Indicates whether we need to act on this jobContext id
198 */
199 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
200 /**
201 * The uid whose jobs we would like to assign to a context.
202 */
203 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800204
205 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700206 * All times are in milliseconds. These constants are kept synchronized with the system
207 * global Settings. Any access to this class or its fields should be done while
208 * holding the JobSchedulerService.mLock lock.
209 */
210 private final class Constants extends ContentObserver {
211 // Key names stored in the settings value.
212 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
213 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800214 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700215 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700216 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
217 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
218 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
219 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
220 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
221 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
222 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
223 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
224 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
225 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700226 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
227 = "max_standard_reschedule_count";
228 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
229 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
230 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700231 private static final String KEY_BG_JOBS_RESTRICTED = "bg_jobs_restricted";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700232
233 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
234 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800235 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700236 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700237 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
238 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
239 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
240 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
241 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
242 private static final int DEFAULT_FG_JOB_COUNT = 4;
243 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
244 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700245 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700246 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700247 private static final boolean DEFAULT_BG_JOBS_RESTRICTED = false;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700248 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
249 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
250 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
251 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700252
253 /**
254 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
255 * early.
256 */
257 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
258 /**
259 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
260 * things early.
261 */
262 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
263 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800264 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
265 * schedule things early.
266 */
267 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
268 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700269 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
270 * schedule things early.
271 */
272 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
273 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700274 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
275 * things early. 1 == Run connectivity jobs as soon as ready.
276 */
277 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
278 /**
279 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
280 * schedule things early.
281 */
282 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
283 /**
284 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
285 * running some work early. This (and thus the other min counts) is now set to 1, to
286 * prevent any batching at this level. Since we now do batching through doze, that is
287 * a much better mechanism.
288 */
289 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
290 /**
291 * This is the job execution factor that is considered to be heavy use of the system.
292 */
293 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
294 /**
295 * This is the job execution factor that is considered to be moderate use of the system.
296 */
297 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
298 /**
299 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
300 */
301 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
302 /**
303 * The maximum number of background jobs we allow when the system is in a normal
304 * memory state.
305 */
306 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
307 /**
308 * The maximum number of background jobs we allow when the system is in a moderate
309 * memory state.
310 */
311 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
312 /**
313 * The maximum number of background jobs we allow when the system is in a low
314 * memory state.
315 */
316 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
317 /**
318 * The maximum number of background jobs we allow when the system is in a critical
319 * memory state.
320 */
321 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700322 /**
323 * The maximum number of times we allow a job to have itself rescheduled before
324 * giving up on it, for standard jobs.
325 */
326 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
327 /**
328 * The maximum number of times we allow a job to have itself rescheduled before
329 * giving up on it, for jobs that are executing work.
330 */
331 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
332 /**
333 * The minimum backoff time to allow for linear backoff.
334 */
335 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
336 /**
337 * The minimum backoff time to allow for exponential backoff.
338 */
339 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700340
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700341 /**
342 * Runtime switch for throttling background jobs
343 */
344 boolean BACKGROUND_JOBS_RESTRICTED = DEFAULT_BG_JOBS_RESTRICTED;
345
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700346 private ContentResolver mResolver;
347 private final KeyValueListParser mParser = new KeyValueListParser(',');
348
349 public Constants(Handler handler) {
350 super(handler);
351 }
352
353 public void start(ContentResolver resolver) {
354 mResolver = resolver;
355 mResolver.registerContentObserver(Settings.Global.getUriFor(
356 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
357 updateConstants();
358 }
359
360 @Override
361 public void onChange(boolean selfChange, Uri uri) {
362 updateConstants();
363 }
364
365 private void updateConstants() {
366 synchronized (mLock) {
367 try {
368 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000369 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700370 } catch (IllegalArgumentException e) {
371 // Failed to parse the settings string, log this and move on
372 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000373 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700374 }
375
376 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
377 DEFAULT_MIN_IDLE_COUNT);
378 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
379 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800380 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
381 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700382 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
383 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700384 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
385 DEFAULT_MIN_CONNECTIVITY_COUNT);
386 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
387 DEFAULT_MIN_CONTENT_COUNT);
388 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
389 DEFAULT_MIN_READY_JOBS_COUNT);
390 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
391 DEFAULT_HEAVY_USE_FACTOR);
392 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
393 DEFAULT_MODERATE_USE_FACTOR);
394 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
395 DEFAULT_FG_JOB_COUNT);
396 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
397 DEFAULT_BG_NORMAL_JOB_COUNT);
398 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
399 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
400 }
401 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
402 DEFAULT_BG_MODERATE_JOB_COUNT);
403 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
404 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
405 }
406 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
407 DEFAULT_BG_LOW_JOB_COUNT);
408 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
409 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
410 }
411 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
412 DEFAULT_BG_CRITICAL_JOB_COUNT);
413 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
414 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
415 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700416 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
417 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
418 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
419 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
420 MIN_LINEAR_BACKOFF_TIME = mParser.getLong(KEY_MIN_LINEAR_BACKOFF_TIME,
421 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
422 MIN_EXP_BACKOFF_TIME = mParser.getLong(KEY_MIN_EXP_BACKOFF_TIME,
423 DEFAULT_MIN_EXP_BACKOFF_TIME);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700424 final boolean bgJobsRestricted = mParser.getBoolean(KEY_BG_JOBS_RESTRICTED,
425 DEFAULT_BG_JOBS_RESTRICTED);
426 if (bgJobsRestricted != BACKGROUND_JOBS_RESTRICTED) {
427 mBackgroundJobsController.enableRestrictionsLocked(
428 BACKGROUND_JOBS_RESTRICTED = bgJobsRestricted);
429 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700430 }
431 }
432
433 void dump(PrintWriter pw) {
434 pw.println(" Settings:");
435
436 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
437 pw.print(MIN_IDLE_COUNT); pw.println();
438
439 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
440 pw.print(MIN_CHARGING_COUNT); pw.println();
441
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800442 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
443 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
444
Dianne Hackborn532ea262017-03-17 17:50:55 -0700445 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
446 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
447
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700448 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
449 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
450
451 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
452 pw.print(MIN_CONTENT_COUNT); pw.println();
453
454 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
455 pw.print(MIN_READY_JOBS_COUNT); pw.println();
456
457 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
458 pw.print(HEAVY_USE_FACTOR); pw.println();
459
460 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
461 pw.print(MODERATE_USE_FACTOR); pw.println();
462
463 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
464 pw.print(FG_JOB_COUNT); pw.println();
465
466 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
467 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
468
469 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
470 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
471
472 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
473 pw.print(BG_LOW_JOB_COUNT); pw.println();
474
475 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
476 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700477
478 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
479 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
480
481 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
482 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
483
484 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
485 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
486
487 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
488 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700489
490 pw.print(" "); pw.print(KEY_BG_JOBS_RESTRICTED); pw.print("=");
491 pw.print(BACKGROUND_JOBS_RESTRICTED); pw.println();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700492 }
493 }
494
495 final Constants mConstants;
496
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700497 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
498 if (o1.enqueueTime < o2.enqueueTime) {
499 return -1;
500 }
501 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
502 };
503
504 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
505 int where = Collections.binarySearch(array, newItem, comparator);
506 if (where < 0) {
507 where = ~where;
508 }
509 array.add(where, newItem);
510 }
511
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700512 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700513 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
514 * still clean up. On reinstall the package will have a new uid.
515 */
516 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
517 @Override
518 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700519 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700520 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700521 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700522 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700523 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700524 // Purge the app's jobs if the whole package was just disabled. When this is
525 // the case the component name will be a bare package name.
526 final String pkgName = getPackageName(intent);
527 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
528 if (pkgName != null && pkgUid != -1) {
529 final String[] changedComponents = intent.getStringArrayExtra(
530 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
531 if (changedComponents != null) {
532 for (String component : changedComponents) {
533 if (component.equals(pkgName)) {
534 if (DEBUG) {
535 Slog.d(TAG, "Package state change: " + pkgName);
536 }
537 try {
538 final int userId = UserHandle.getUserId(pkgUid);
539 IPackageManager pm = AppGlobals.getPackageManager();
540 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
541 if (state == COMPONENT_ENABLED_STATE_DISABLED
542 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
543 if (DEBUG) {
544 Slog.d(TAG, "Removing jobs for package " + pkgName
545 + " in user " + userId);
546 }
Dianne Hackborn729a3282017-06-09 16:06:01 -0700547 cancelJobsForUid(pkgUid, "app package state changed");
Christopher Tateb5c07882016-05-26 17:11:09 -0700548 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700549 } catch (RemoteException|IllegalArgumentException e) {
550 /*
551 * IllegalArgumentException means that the package doesn't exist.
552 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
553 * behind outright uninstall, so by the time we try to act it's gone.
554 * We don't need to act on this PACKAGE_CHANGED when this happens;
555 * we'll get a PACKAGE_REMOVED later and clean up then.
556 *
557 * RemoteException can't actually happen; the package manager is
558 * running in this same process.
559 */
560 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700561 break;
562 }
563 }
564 }
565 } else {
566 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
567 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700568 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700569 // If this is an outright uninstall rather than the first half of an
570 // app update sequence, cancel the jobs associated with the app.
571 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
572 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
573 if (DEBUG) {
574 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
575 }
Dianne Hackborn729a3282017-06-09 16:06:01 -0700576 cancelJobsForUid(uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700577 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700578 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700579 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
580 if (DEBUG) {
581 Slog.d(TAG, "Removing jobs for user: " + userId);
582 }
583 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700584 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
585 // Has this package scheduled any jobs, such that we will take action
586 // if it were to be force-stopped?
587 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
588 final String pkgName = intent.getData().getSchemeSpecificPart();
589 if (pkgUid != -1) {
590 List<JobStatus> jobsForUid;
591 synchronized (mLock) {
592 jobsForUid = mJobs.getJobsByUid(pkgUid);
593 }
594 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
595 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
596 if (DEBUG) {
597 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
598 + pkgUid + " has jobs");
599 }
600 setResultCode(Activity.RESULT_OK);
601 break;
602 }
603 }
604 }
605 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
606 // possible force-stop
607 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
608 final String pkgName = intent.getData().getSchemeSpecificPart();
609 if (pkgUid != -1) {
610 if (DEBUG) {
611 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
612 }
613 cancelJobsForPackageAndUid(pkgName, pkgUid);
614 }
Christopher Tate7060b042014-06-09 19:50:00 -0700615 }
616 }
617 };
618
Christopher Tateb5c07882016-05-26 17:11:09 -0700619 private String getPackageName(Intent intent) {
620 Uri uri = intent.getData();
621 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
622 return pkg;
623 }
624
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700625 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700626 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800627 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700628 }
629
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700630 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800631 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800632 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700633 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800634 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700635 synchronized (mLock) {
636 mBackgroundJobsController.setUidActiveLocked(uid, false);
637 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700638 }
639
640 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700641 synchronized (mLock) {
642 mBackgroundJobsController.setUidActiveLocked(uid, true);
643 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700644 }
645
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700646 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800647 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700648 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800649 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700650 synchronized (mLock) {
651 mBackgroundJobsController.setUidActiveLocked(uid, false);
652 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700653 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700654
655 @Override public void onUidCachedChanged(int uid, boolean cached) {
656 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700657 };
658
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800659 public Object getLock() {
660 return mLock;
661 }
662
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700663 public JobStore getJobStore() {
664 return mJobs;
665 }
666
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700667 @Override
668 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700669 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
670 // Let's kick any outstanding jobs for this user.
671 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
672 }
673
674 @Override
675 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700676 // Let's kick any outstanding jobs for this user.
677 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
678 }
679
680 @Override
681 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700682 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700683 }
684
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700685 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
686 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700687 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800688 if (ActivityManager.getService().isAppStartModeDisabled(uId,
689 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700690 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
691 + " -- package not allowed to start");
692 return JobScheduler.RESULT_FAILURE;
693 }
694 } catch (RemoteException e) {
695 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800696 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700697 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
698
699 if (work != null && toCancel != null) {
700 // Fast path: we are adding work to an existing job, and the JobInfo is not
701 // changing. We can just directly enqueue this work in to the job.
702 if (toCancel.getJob().equals(job)) {
Dianne Hackborn342e6032017-04-13 18:04:31 -0700703 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700704 return JobScheduler.RESULT_SUCCESS;
705 }
706 }
707
708 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
709 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800710 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800711 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800712 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
713 Slog.w(TAG, "Too many jobs for uid " + uId);
714 throw new IllegalStateException("Apps may not schedule more than "
715 + MAX_JOBS_PER_APP + " distinct jobs");
716 }
717 }
718
Dianne Hackborna47223f2017-03-30 13:49:13 -0700719 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700720 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700721
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700722 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700723 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700724 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700725 if (work != null) {
726 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700727 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700728 }
729 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700730
731 // If the job is immediately ready to run, then we can just immediately
732 // put it in the pending list and try to schedule it. This is especially
733 // important for jobs with a 0 deadline constraint, since they will happen a fair
734 // amount, we want to handle them as quickly as possible, and semantically we want to
735 // make sure we have started holding the wake lock for the job before returning to
736 // the caller.
737 // If the job is not yet ready to run, there is nothing more to do -- we are
738 // now just waiting for one of its controllers to change state and schedule
739 // the job appropriately.
740 if (isReadyToBeExecutedLocked(jobStatus)) {
741 // This is a new job, we can just immediately put it on the pending
742 // list and try to run it.
743 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700744 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700745 maybeRunPendingJobsLocked();
746 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800747 }
Christopher Tate7060b042014-06-09 19:50:00 -0700748 return JobScheduler.RESULT_SUCCESS;
749 }
750
751 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800752 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800753 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
754 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
755 for (int i = jobs.size() - 1; i >= 0; i--) {
756 JobStatus job = jobs.get(i);
757 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700758 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800759 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700760 }
Christopher Tate7060b042014-06-09 19:50:00 -0700761 }
762
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600763 public JobInfo getPendingJob(int uid, int jobId) {
764 synchronized (mLock) {
765 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
766 for (int i = jobs.size() - 1; i >= 0; i--) {
767 JobStatus job = jobs.get(i);
768 if (job.getJobId() == jobId) {
769 return job.getJob();
770 }
771 }
772 return null;
773 }
774 }
775
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700776 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800777 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700778 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
779 for (int i=0; i<jobsForUser.size(); i++) {
780 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700781 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700782 }
Christopher Tate7060b042014-06-09 19:50:00 -0700783 }
784 }
785
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700786 private void cancelJobsForNonExistentUsers() {
787 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
788 synchronized (mLock) {
789 mJobs.removeJobsOfNonUsers(umi.getUserIds());
790 }
791 }
792
Christopher Tateee7805b2016-07-15 16:56:56 -0700793 void cancelJobsForPackageAndUid(String pkgName, int uid) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700794 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700795 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
796 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
797 final JobStatus job = jobsForUid.get(i);
798 if (job.getSourcePackageName().equals(pkgName)) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700799 cancelJobImplLocked(job, null, "app force stopped");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700800 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700801 }
802 }
803 }
804
Christopher Tate7060b042014-06-09 19:50:00 -0700805 /**
806 * Entry point from client to cancel all jobs originating from their uid.
807 * This will remove the job from the master list, and cancel the job if it was staged for
808 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700809 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800810 *
Christopher Tate7060b042014-06-09 19:50:00 -0700811 */
Dianne Hackborn729a3282017-06-09 16:06:01 -0700812 public void cancelJobsForUid(int uid, String reason) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800813 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700814 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
815 for (int i=0; i<jobsForUid.size(); i++) {
816 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700817 cancelJobImplLocked(toRemove, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700818 }
Christopher Tate7060b042014-06-09 19:50:00 -0700819 }
820 }
821
822 /**
823 * Entry point from client to cancel the job corresponding to the jobId provided.
824 * This will remove the job from the master list, and cancel the job if it was staged for
825 * execution or being executed.
826 * @param uid Uid of the calling client.
827 * @param jobId Id of the job, provided at schedule-time.
828 */
829 public void cancelJob(int uid, int jobId) {
830 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800831 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700832 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700833 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700834 cancelJobImplLocked(toCancel, null, "cancel() called by app");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700835 }
Christopher Tate7060b042014-06-09 19:50:00 -0700836 }
837 }
838
Dianne Hackborn729a3282017-06-09 16:06:01 -0700839 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700840 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
841 cancelled.unprepareLocked(ActivityManager.getService());
842 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
843 // Remove from pending queue.
844 if (mPendingJobs.remove(cancelled)) {
845 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700846 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700847 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700848 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700849 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700850 }
851
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800852 void updateUidState(int uid, int procState) {
853 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800854 if (procState == ActivityManager.PROCESS_STATE_TOP) {
855 // Only use this if we are exactly the top app. All others can live
856 // with just the foreground priority. This means that persistent processes
857 // can never be the top app priority... that is fine.
858 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
859 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
860 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800861 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800862 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800863 }
864 }
865 }
866
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700867 @Override
868 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800869 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700870 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600871 // When becoming idle, make sure no jobs are actively running,
872 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700873 for (int i=0; i<mActiveServices.size(); i++) {
874 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700875 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600876 if (executing != null
877 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700878 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
879 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700880 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700881 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700882 } else {
883 // When coming out of idle, allow thing to start back up.
884 if (mReadyToRock) {
885 if (mLocalDeviceIdleController != null) {
886 if (!mReportedActive) {
887 mReportedActive = true;
888 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700889 }
890 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700891 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700892 }
893 }
894 }
895 }
896
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700897 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000898 // active is true if pending queue contains jobs OR some job is running.
899 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800900 if (mPendingJobs.size() <= 0) {
901 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700902 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700903 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700904 if (job != null
905 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
906 && !job.dozeWhitelisted) {
907 // We will report active if we have a job running and it is not an exception
908 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800909 active = true;
910 break;
911 }
912 }
913 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000914
915 if (mReportedActive != active) {
916 mReportedActive = active;
917 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800918 mLocalDeviceIdleController.setJobsActive(active);
919 }
920 }
921 }
922
Christopher Tate7060b042014-06-09 19:50:00 -0700923 /**
924 * Initializes the system service.
925 * <p>
926 * Subclasses must define a single argument constructor that accepts the context
927 * and passes it to super.
928 * </p>
929 *
930 * @param context The system server context.
931 */
932 public JobSchedulerService(Context context) {
933 super(context);
Dianne Hackborn970e3f42016-06-01 10:55:13 -0700934 mHandler = new JobHandler(context.getMainLooper());
935 mConstants = new Constants(mHandler);
936 mJobSchedulerStub = new JobSchedulerStub();
937 mJobs = JobStore.initAndGet(this);
938
Christopher Tate7060b042014-06-09 19:50:00 -0700939 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700940 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700941 mControllers.add(ConnectivityController.get(this));
942 mControllers.add(TimeController.get(this));
943 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800944 mBatteryController = BatteryController.get(this);
945 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700946 mStorageController = StorageController.get(this);
947 mControllers.add(mStorageController);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700948 mBackgroundJobsController = BackgroundJobsController.get(this);
949 mControllers.add(mBackgroundJobsController);
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800950 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800951 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700952 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate616541d2017-07-26 14:27:38 -0700953
954 // If the job store determined that it can't yet reschedule persisted jobs,
955 // we need to start watching the clock.
956 if (!mJobs.jobTimesInflatedValid()) {
957 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
958 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
959 }
Christopher Tate7060b042014-06-09 19:50:00 -0700960 }
961
Christopher Tate616541d2017-07-26 14:27:38 -0700962 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
963 @Override
964 public void onReceive(Context context, Intent intent) {
965 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
966 // When we reach clock sanity, recalculate the temporal windows
967 // of all affected jobs.
968 if (mJobs.clockNowValidToInflate(System.currentTimeMillis())) {
969 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
970
971 // We've done our job now, so stop watching the time.
972 context.unregisterReceiver(this);
973
974 // And kick off the work to update the affected jobs, using a secondary
975 // thread instead of chugging away here on the main looper thread.
976 FgThread.getHandler().post(mJobTimeUpdater);
977 }
978 }
979 }
980 };
981
982 private final Runnable mJobTimeUpdater = () -> {
983 final ArrayList<JobStatus> toRemove = new ArrayList<>();
984 final ArrayList<JobStatus> toAdd = new ArrayList<>();
985 synchronized (mLock) {
986 // Note: we intentionally both look up the existing affected jobs and replace them
987 // with recalculated ones inside the same lock lifetime.
988 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
989
990 // Now, at each position [i], we have both the existing JobStatus
991 // and the one that replaces it.
992 final int N = toAdd.size();
993 for (int i = 0; i < N; i++) {
994 final JobStatus oldJob = toRemove.get(i);
995 final JobStatus newJob = toAdd.get(i);
996 if (DEBUG) {
997 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
998 }
999 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1000 }
1001 }
1002 };
1003
Christopher Tate7060b042014-06-09 19:50:00 -07001004 @Override
1005 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001006 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -07001007 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1008 }
1009
1010 @Override
1011 public void onBootPhase(int phase) {
1012 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001013 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001014 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001015 final IntentFilter filter = new IntentFilter();
1016 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1017 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001018 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1019 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001020 filter.addDataScheme("package");
1021 getContext().registerReceiverAsUser(
1022 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1023 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1024 getContext().registerReceiverAsUser(
1025 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001026 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001027 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001028 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001029 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001030 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1031 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001032 } catch (RemoteException e) {
1033 // ignored; both services live in system_server
1034 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001035 // Remove any jobs that are not associated with any of the current users.
1036 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001037 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001038 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001039 // Let's go!
1040 mReadyToRock = true;
1041 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1042 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001043 mLocalDeviceIdleController
1044 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001045 // Create the "runners".
1046 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1047 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001048 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001049 getContext().getMainLooper()));
1050 }
1051 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001052 mJobs.forEachJob(new JobStatusFunctor() {
1053 @Override
1054 public void process(JobStatus job) {
1055 for (int controller = 0; controller < mControllers.size(); controller++) {
1056 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001057 sc.maybeStartTrackingJobLocked(job, null);
1058 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001059 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001060 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001061 // GO GO GO!
1062 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1063 }
Christopher Tate7060b042014-06-09 19:50:00 -07001064 }
1065 }
1066
1067 /**
1068 * Called when we have a job status object that we need to insert in our
1069 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1070 * about.
1071 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001072 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1073 if (!jobStatus.isPreparedLocked()) {
1074 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1075 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001076 jobStatus.enqueueTime = SystemClock.elapsedRealtime();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001077 final boolean update = mJobs.add(jobStatus);
1078 if (mReadyToRock) {
1079 for (int i = 0; i < mControllers.size(); i++) {
1080 StateController controller = mControllers.get(i);
1081 if (update) {
1082 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001083 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001084 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001085 }
Christopher Tate7060b042014-06-09 19:50:00 -07001086 }
1087 }
1088
1089 /**
1090 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1091 * object removed.
1092 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001093 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001094 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001095 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001096 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001097
1098 // Remove from store as well as controllers.
1099 final boolean removed = mJobs.remove(jobStatus, writeBack);
1100 if (removed && mReadyToRock) {
1101 for (int i=0; i<mControllers.size(); i++) {
1102 StateController controller = mControllers.get(i);
1103 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001104 }
1105 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001106 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001107 }
1108
Dianne Hackborn729a3282017-06-09 16:06:01 -07001109 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001110 for (int i=0; i<mActiveServices.size(); i++) {
1111 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001112 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001113 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001114 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001115 return true;
1116 }
1117 }
1118 return false;
1119 }
1120
1121 /**
1122 * @param job JobStatus we are querying against.
1123 * @return Whether or not the job represented by the status object is currently being run or
1124 * is pending.
1125 */
1126 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001127 for (int i=0; i<mActiveServices.size(); i++) {
1128 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001129 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001130 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1131 return true;
1132 }
1133 }
1134 return false;
1135 }
1136
Dianne Hackborn807de782016-04-07 17:54:41 -07001137 void noteJobsPending(List<JobStatus> jobs) {
1138 for (int i = jobs.size() - 1; i >= 0; i--) {
1139 JobStatus job = jobs.get(i);
1140 mJobPackageTracker.notePending(job);
1141 }
1142 }
1143
1144 void noteJobsNonpending(List<JobStatus> jobs) {
1145 for (int i = jobs.size() - 1; i >= 0; i--) {
1146 JobStatus job = jobs.get(i);
1147 mJobPackageTracker.noteNonpending(job);
1148 }
1149 }
1150
Christopher Tate7060b042014-06-09 19:50:00 -07001151 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001152 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1153 * specify an override deadline on a failed job (the failed job will run even though it's not
1154 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1155 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1156 *
Christopher Tate7060b042014-06-09 19:50:00 -07001157 * @param failureToReschedule Provided job status that we will reschedule.
1158 * @return A newly instantiated JobStatus with the same constraints as the last job except
1159 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001160 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001161 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001162 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001163 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001164 final long elapsedNowMillis = SystemClock.elapsedRealtime();
1165 final JobInfo job = failureToReschedule.getJob();
1166
1167 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001168 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1169 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001170
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001171 if (failureToReschedule.hasWorkLocked()) {
1172 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1173 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1174 + backoffAttempts + " > work limit "
1175 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1176 return null;
1177 }
1178 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1179 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1180 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1181 return null;
1182 }
1183
Christopher Tate7060b042014-06-09 19:50:00 -07001184 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001185 case JobInfo.BACKOFF_POLICY_LINEAR: {
1186 long backoff = initialBackoffMillis;
1187 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1188 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1189 }
1190 delayMillis = backoff * backoffAttempts;
1191 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001192 default:
1193 if (DEBUG) {
1194 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1195 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001196 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1197 long backoff = initialBackoffMillis;
1198 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1199 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1200 }
1201 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1202 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001203 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001204 delayMillis =
1205 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001206 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001207 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
1208 failureToReschedule.getLastSuccessfulRunTime(), System.currentTimeMillis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001209 for (int ic=0; ic<mControllers.size(); ic++) {
1210 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001211 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001212 }
1213 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001214 }
1215
1216 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001217 * Called after a periodic has executed so we can reschedule it. We take the last execution
1218 * time of the job to be the time of completion (i.e. the time at which this function is
1219 * called).
Christopher Tate7060b042014-06-09 19:50:00 -07001220 * This could be inaccurate b/c the job can run for as long as
1221 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1222 * to underscheduling at least, rather than if we had taken the last execution time to be the
1223 * start of the execution.
1224 * @return A new job representing the execution criteria for this instantiation of the
1225 * recurring job.
1226 */
1227 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
1228 final long elapsedNow = SystemClock.elapsedRealtime();
1229 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001230 long runEarly = 0L;
1231
1232 // If this periodic was rescheduled it won't have a deadline.
1233 if (periodicToReschedule.hasDeadlineConstraint()) {
1234 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1235 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001236 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001237 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001238 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1239 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001240
1241 if (DEBUG) {
1242 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1243 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1244 }
1245 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001246 newLatestRuntimeElapsed, 0 /* backoffAttempt */,
1247 System.currentTimeMillis() /* lastSuccessfulRunTime */,
1248 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001249 }
1250
1251 // JobCompletedListener implementations.
1252
1253 /**
1254 * A job just finished executing. We fetch the
1255 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1256 * whether we want to reschedule we readd it to the controllers.
1257 * @param jobStatus Completed job.
1258 * @param needsReschedule Whether the implementing class should reschedule this job.
1259 */
1260 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001261 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001262 if (DEBUG) {
1263 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1264 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001265
1266 // If the job wants to be rescheduled, we first need to make the next upcoming
1267 // job so we can transfer any appropriate state over from the previous job when
1268 // we stop it.
1269 final JobStatus rescheduledJob = needsReschedule
1270 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1271
Shreyas Basarge73f10252016-02-11 17:06:13 +00001272 // Do not write back immediately if this is a periodic job. The job may get lost if system
1273 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001274 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001275 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001276 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001277 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001278 // We still want to check for jobs to execute, because this job may have
1279 // scheduled a new job under the same job id, and now we can run it.
1280 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001281 return;
1282 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001283
1284 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001285 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001286 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001287 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001288 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001289 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001290 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001291 } else if (jobStatus.getJob().isPeriodic()) {
1292 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001293 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001294 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001295 } catch (SecurityException e) {
1296 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1297 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001298 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001299 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001300 jobStatus.unprepareLocked(ActivityManager.getService());
1301 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001302 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001303 }
1304
1305 // StateChangedListener implementations.
1306
1307 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001308 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1309 * some controller's state has changed, so as to run through the list of jobs and start/stop
1310 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001311 */
1312 @Override
1313 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001314 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001315 }
1316
1317 @Override
1318 public void onRunJobNow(JobStatus jobStatus) {
1319 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1320 }
1321
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001322 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001323
1324 public JobHandler(Looper looper) {
1325 super(looper);
1326 }
1327
1328 @Override
1329 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001330 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001331 if (!mReadyToRock) {
1332 return;
1333 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001334 switch (message.what) {
1335 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001336 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001337 // runNow can be null, which is a controller's way of indicating that its
1338 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001339 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001340 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001341 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001342 } else {
1343 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001344 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001345 } break;
1346 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001347 if (mReportedActive) {
1348 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001349 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001350 } else {
1351 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001352 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001353 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001354 break;
1355 case MSG_CHECK_JOB_GREEDY:
1356 queueReadyJobsForExecutionLocked();
1357 break;
1358 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001359 cancelJobImplLocked((JobStatus) message.obj, null,
1360 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001361 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001362 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001363 maybeRunPendingJobsLocked();
1364 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1365 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001366 }
1367 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001368 }
Christopher Tate7060b042014-06-09 19:50:00 -07001369
Dianne Hackborn6d068262017-05-16 13:14:37 -07001370 private void stopNonReadyActiveJobsLocked() {
1371 for (int i=0; i<mActiveServices.size(); i++) {
1372 JobServiceContext serviceContext = mActiveServices.get(i);
1373 final JobStatus running = serviceContext.getRunningJobLocked();
1374 if (running != null && !running.isReady()) {
1375 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001376 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1377 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001378 }
1379 }
1380 }
1381
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001382 /**
1383 * Run through list of jobs and execute all possible - at least one is expired so we do
1384 * as many as we can.
1385 */
1386 private void queueReadyJobsForExecutionLocked() {
1387 if (DEBUG) {
1388 Slog.d(TAG, "queuing all ready jobs for execution:");
1389 }
1390 noteJobsNonpending(mPendingJobs);
1391 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001392 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001393 mJobs.forEachJob(mReadyQueueFunctor);
1394 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001395
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001396 if (DEBUG) {
1397 final int queuedJobs = mPendingJobs.size();
1398 if (queuedJobs == 0) {
1399 Slog.d(TAG, "No jobs pending.");
1400 } else {
1401 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001402 }
1403 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001404 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001405
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001406 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1407 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001408
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001409 @Override
1410 public void process(JobStatus job) {
1411 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001412 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001413 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001414 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001415 if (newReadyJobs == null) {
1416 newReadyJobs = new ArrayList<JobStatus>();
1417 }
1418 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001419 }
1420 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001421
1422 public void postProcess() {
1423 if (newReadyJobs != null) {
1424 noteJobsPending(newReadyJobs);
1425 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001426 if (mPendingJobs.size() > 1) {
1427 mPendingJobs.sort(mEnqueueTimeComparator);
1428 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001429 }
1430 newReadyJobs = null;
1431 }
1432 }
1433 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1434
1435 /**
1436 * The state of at least one job has changed. Here is where we could enforce various
1437 * policies on when we want to execute jobs.
1438 * Right now the policy is such:
1439 * If >1 of the ready jobs is idle mode we send all of them off
1440 * if more than 2 network connectivity jobs are ready we send them all off.
1441 * If more than 4 jobs total are ready we send them all off.
1442 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1443 */
1444 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1445 int chargingCount;
1446 int batteryNotLowCount;
1447 int storageNotLowCount;
1448 int idleCount;
1449 int backoffCount;
1450 int connectivityCount;
1451 int contentCount;
1452 List<JobStatus> runnableJobs;
1453
1454 public MaybeReadyJobQueueFunctor() {
1455 reset();
1456 }
1457
1458 // Functor method invoked for each job via JobStore.forEachJob()
1459 @Override
1460 public void process(JobStatus job) {
1461 if (isReadyToBeExecutedLocked(job)) {
1462 try {
1463 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1464 job.getJob().getService().getPackageName())) {
1465 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1466 + job.getJob().toString() + " -- package not allowed to start");
1467 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1468 return;
1469 }
1470 } catch (RemoteException e) {
1471 }
1472 if (job.getNumFailures() > 0) {
1473 backoffCount++;
1474 }
1475 if (job.hasIdleConstraint()) {
1476 idleCount++;
1477 }
1478 if (job.hasConnectivityConstraint()) {
1479 connectivityCount++;
1480 }
1481 if (job.hasChargingConstraint()) {
1482 chargingCount++;
1483 }
1484 if (job.hasBatteryNotLowConstraint()) {
1485 batteryNotLowCount++;
1486 }
1487 if (job.hasStorageNotLowConstraint()) {
1488 storageNotLowCount++;
1489 }
1490 if (job.hasContentTriggerConstraint()) {
1491 contentCount++;
1492 }
1493 if (runnableJobs == null) {
1494 runnableJobs = new ArrayList<>();
1495 }
1496 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001497 }
1498 }
1499
1500 public void postProcess() {
1501 if (backoffCount > 0 ||
1502 idleCount >= mConstants.MIN_IDLE_COUNT ||
1503 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1504 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1505 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1506 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1507 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1508 (runnableJobs != null
1509 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1510 if (DEBUG) {
1511 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1512 }
1513 noteJobsPending(runnableJobs);
1514 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001515 if (mPendingJobs.size() > 1) {
1516 mPendingJobs.sort(mEnqueueTimeComparator);
1517 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001518 } else {
1519 if (DEBUG) {
1520 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1521 }
1522 }
1523
1524 // Be ready for next time
1525 reset();
1526 }
1527
1528 private void reset() {
1529 chargingCount = 0;
1530 idleCount = 0;
1531 backoffCount = 0;
1532 connectivityCount = 0;
1533 batteryNotLowCount = 0;
1534 storageNotLowCount = 0;
1535 contentCount = 0;
1536 runnableJobs = null;
1537 }
1538 }
1539 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1540
1541 private void maybeQueueReadyJobsForExecutionLocked() {
1542 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1543
1544 noteJobsNonpending(mPendingJobs);
1545 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001546 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001547 mJobs.forEachJob(mMaybeQueueFunctor);
1548 mMaybeQueueFunctor.postProcess();
1549 }
1550
1551 /**
1552 * Criteria for moving a job into the pending queue:
1553 * - It's ready.
1554 * - It's not pending.
1555 * - It's not already running on a JSC.
1556 * - The user that requested the job is running.
1557 * - The component is enabled and runnable.
1558 */
1559 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001560 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001561
1562 if (DEBUG) {
1563 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1564 + " ready=" + jobReady);
1565 }
1566
1567 // This is a condition that is very likely to be false (most jobs that are
1568 // scheduled are sitting there, not ready yet) and very cheap to check (just
1569 // a few conditions on data in JobStatus).
1570 if (!jobReady) {
1571 return false;
1572 }
1573
1574 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001575
1576 final int userId = job.getUserId();
1577 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1578
1579 if (DEBUG) {
1580 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001581 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001582 }
1583
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001584 // These are also fairly cheap to check, though they typically will not
1585 // be conditions we fail.
1586 if (!jobExists || !userStarted) {
1587 return false;
1588 }
1589
1590 final boolean jobPending = mPendingJobs.contains(job);
1591 final boolean jobActive = isCurrentlyActiveLocked(job);
1592
1593 if (DEBUG) {
1594 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1595 + " pending=" + jobPending + " active=" + jobActive);
1596 }
1597
1598 // These can be a little more expensive (especially jobActive, since we need to
1599 // go through the array of all potentially active jobs), so we are doing them
1600 // later... but still before checking with the package manager!
1601 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001602 return false;
1603 }
1604
1605 final boolean componentPresent;
1606 try {
1607 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1608 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1609 userId) != null);
1610 } catch (RemoteException e) {
1611 throw e.rethrowAsRuntimeException();
1612 }
1613
1614 if (DEBUG) {
1615 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1616 + " componentPresent=" + componentPresent);
1617 }
1618
1619 // Everything else checked out so far, so this is the final yes/no check
1620 return componentPresent;
1621 }
1622
1623 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001624 * Reconcile jobs in the pending queue against available execution contexts.
1625 * A controller can force a job into the pending queue even if it's already running, but
1626 * here is where we decide whether to actually execute it.
1627 */
1628 private void maybeRunPendingJobsLocked() {
1629 if (DEBUG) {
1630 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1631 }
1632 assignJobsToContextsLocked();
1633 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001634 }
1635
Dianne Hackborn807de782016-04-07 17:54:41 -07001636 private int adjustJobPriority(int curPriority, JobStatus job) {
1637 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1638 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001639 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001640 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001641 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001642 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1643 }
1644 }
1645 return curPriority;
1646 }
1647
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001648 private int evaluateJobPriorityLocked(JobStatus job) {
1649 int priority = job.getPriority();
1650 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001651 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001652 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001653 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1654 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001655 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001656 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001657 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001658 }
1659
Christopher Tate7060b042014-06-09 19:50:00 -07001660 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001661 * Takes jobs from pending queue and runs them on available contexts.
1662 * If no contexts are available, preempts lower priority jobs to
1663 * run higher priority ones.
1664 * Lock on mJobs before calling this function.
1665 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001666 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001667 if (DEBUG) {
1668 Slog.d(TAG, printPendingQueue());
1669 }
1670
Dianne Hackborn970510b2016-02-24 16:56:42 -08001671 int memLevel;
1672 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001673 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001674 } catch (RemoteException e) {
1675 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1676 }
1677 switch (memLevel) {
1678 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001679 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001680 break;
1681 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001682 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001683 break;
1684 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001685 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001686 break;
1687 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001688 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001689 break;
1690 }
1691
1692 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1693 boolean[] act = mTmpAssignAct;
1694 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1695 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001696 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001697 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1698 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001699 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001700 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001701 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001702 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1703 numForeground++;
1704 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001705 }
1706 act[i] = false;
1707 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001708 }
1709 if (DEBUG) {
1710 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1711 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001712 for (int i=0; i<mPendingJobs.size(); i++) {
1713 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001714
1715 // If job is already running, go to next job.
1716 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1717 if (jobRunningContext != -1) {
1718 continue;
1719 }
1720
Dianne Hackborn970510b2016-02-24 16:56:42 -08001721 final int priority = evaluateJobPriorityLocked(nextPending);
1722 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001723
Shreyas Basarge5db09082016-01-07 13:38:29 +00001724 // Find a context for nextPending. The context should be available OR
1725 // it should have lowest priority among all running jobs
1726 // (sharing the same Uid as nextPending)
1727 int minPriority = Integer.MAX_VALUE;
1728 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001729 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1730 JobStatus job = contextIdToJobMap[j];
1731 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001732 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001733 if ((numActive < mMaxActiveJobs ||
1734 (priority >= JobInfo.PRIORITY_TOP_APP &&
1735 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001736 (preferredUid == nextPending.getUid() ||
1737 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1738 // This slot is free, and we haven't yet hit the limit on
1739 // concurrent jobs... we can just throw the job in to here.
1740 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001741 break;
1742 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001743 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001744 // the context has a preferred Uid or we have reached the limit on
1745 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001746 continue;
1747 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001748 if (job.getUid() != nextPending.getUid()) {
1749 continue;
1750 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001751 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001752 continue;
1753 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001754 if (minPriority > nextPending.lastEvaluatedPriority) {
1755 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001756 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001757 }
1758 }
1759 if (minPriorityContextId != -1) {
1760 contextIdToJobMap[minPriorityContextId] = nextPending;
1761 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001762 numActive++;
1763 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1764 numForeground++;
1765 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001766 }
1767 }
1768 if (DEBUG) {
1769 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1770 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001771 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001772 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001773 boolean preservePreferredUid = false;
1774 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001775 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001776 if (js != null) {
1777 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001778 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001779 }
1780 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001781 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001782 preservePreferredUid = true;
1783 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001784 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001785 if (DEBUG) {
1786 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001787 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001788 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001789 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001790 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001791 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001792 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1793 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001794 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001795 if (mPendingJobs.remove(pendingJob)) {
1796 mJobPackageTracker.noteNonpending(pendingJob);
1797 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001798 }
1799 }
1800 if (!preservePreferredUid) {
1801 mActiveServices.get(i).clearPreferredUid();
1802 }
1803 }
1804 }
1805
1806 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1807 for (int i=0; i<map.length; i++) {
1808 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1809 return i;
1810 }
1811 }
1812 return -1;
1813 }
1814
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001815 final class LocalService implements JobSchedulerInternal {
1816
1817 /**
1818 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1819 * jobs are always considered pending.
1820 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001821 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001822 public List<JobInfo> getSystemScheduledPendingJobs() {
1823 synchronized (mLock) {
1824 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1825 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1826 @Override
1827 public void process(JobStatus job) {
1828 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1829 pendingJobs.add(job.getJob());
1830 }
1831 }
1832 });
1833 return pendingJobs;
1834 }
1835 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001836
1837 @Override
1838 public void addBackingUpUid(int uid) {
1839 synchronized (mLock) {
1840 // No need to actually do anything here, since for a full backup the
1841 // activity manager will kill the process which will kill the job (and
1842 // cause it to restart, but now it can't run).
1843 mBackingUpUids.put(uid, uid);
1844 }
1845 }
1846
1847 @Override
1848 public void removeBackingUpUid(int uid) {
1849 synchronized (mLock) {
1850 mBackingUpUids.delete(uid);
1851 // If there are any jobs for this uid, we need to rebuild the pending list
1852 // in case they are now ready to run.
1853 if (mJobs.countJobsForUid(uid) > 0) {
1854 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1855 }
1856 }
1857 }
1858
1859 @Override
1860 public void clearAllBackingUpUids() {
1861 synchronized (mLock) {
1862 if (mBackingUpUids.size() > 0) {
1863 mBackingUpUids.clear();
1864 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1865 }
1866 }
1867 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07001868
1869 @Override
1870 public int countJobs() {
1871 synchronized (mLock) {
1872 return mJobs.size();
1873 }
1874 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001875 }
1876
Shreyas Basarge5db09082016-01-07 13:38:29 +00001877 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001878 * Binder stub trampoline implementation
1879 */
1880 final class JobSchedulerStub extends IJobScheduler.Stub {
1881 /** Cache determination of whether a given app can persist jobs
1882 * key is uid of the calling app; value is undetermined/true/false
1883 */
1884 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1885
1886 // Enforce that only the app itself (or shared uid participant) can schedule a
1887 // job that runs one of the app's services, as well as verifying that the
1888 // named service properly requires the BIND_JOB_SERVICE permission
1889 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001890 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001891 final ComponentName service = job.getService();
1892 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001893 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001894 PackageManager.MATCH_DIRECT_BOOT_AWARE
1895 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001896 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001897 if (si == null) {
1898 throw new IllegalArgumentException("No such service " + service);
1899 }
Christopher Tate7060b042014-06-09 19:50:00 -07001900 if (si.applicationInfo.uid != uid) {
1901 throw new IllegalArgumentException("uid " + uid +
1902 " cannot schedule job in " + service.getPackageName());
1903 }
1904 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1905 throw new IllegalArgumentException("Scheduled service " + service
1906 + " does not require android.permission.BIND_JOB_SERVICE permission");
1907 }
Christopher Tate5568f542014-06-18 13:53:31 -07001908 } catch (RemoteException e) {
1909 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001910 }
1911 }
1912
1913 private boolean canPersistJobs(int pid, int uid) {
1914 // If we get this far we're good to go; all we need to do now is check
1915 // whether the app is allowed to persist its scheduled work.
1916 final boolean canPersist;
1917 synchronized (mPersistCache) {
1918 Boolean cached = mPersistCache.get(uid);
1919 if (cached != null) {
1920 canPersist = cached.booleanValue();
1921 } else {
1922 // Persisting jobs is tantamount to running at boot, so we permit
1923 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1924 // permission
1925 int result = getContext().checkPermission(
1926 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1927 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1928 mPersistCache.put(uid, canPersist);
1929 }
1930 }
1931 return canPersist;
1932 }
1933
1934 // IJobScheduler implementation
1935 @Override
1936 public int schedule(JobInfo job) throws RemoteException {
1937 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001938 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001939 }
1940 final int pid = Binder.getCallingPid();
1941 final int uid = Binder.getCallingUid();
1942
1943 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001944 if (job.isPersisted()) {
1945 if (!canPersistJobs(pid, uid)) {
1946 throw new IllegalArgumentException("Error: requested job be persisted without"
1947 + " holding RECEIVE_BOOT_COMPLETED permission.");
1948 }
1949 }
Christopher Tate7060b042014-06-09 19:50:00 -07001950
Jeff Sharkey785f4942016-07-14 10:31:15 -06001951 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1952 getContext().enforceCallingOrSelfPermission(
1953 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1954 }
1955
Christopher Tate7060b042014-06-09 19:50:00 -07001956 long ident = Binder.clearCallingIdentity();
1957 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001958 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, -1, null);
1959 } finally {
1960 Binder.restoreCallingIdentity(ident);
1961 }
1962 }
1963
1964 // IJobScheduler implementation
1965 @Override
1966 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
1967 if (DEBUG) {
1968 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
1969 }
1970 final int pid = Binder.getCallingPid();
1971 final int uid = Binder.getCallingUid();
1972
1973 enforceValidJobRequest(uid, job);
1974 if (job.isPersisted()) {
1975 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
1976 }
1977 if (work == null) {
1978 throw new NullPointerException("work is null");
1979 }
1980
1981 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1982 getContext().enforceCallingOrSelfPermission(
1983 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1984 }
1985
1986 long ident = Binder.clearCallingIdentity();
1987 try {
1988 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, -1, null);
Christopher Tate7060b042014-06-09 19:50:00 -07001989 } finally {
1990 Binder.restoreCallingIdentity(ident);
1991 }
1992 }
1993
1994 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001995 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001996 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001997 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001998 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001999 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
2000 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002001 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002002
2003 if (packageName == null) {
2004 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002005 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002006
2007 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2008 android.Manifest.permission.UPDATE_DEVICE_STATS);
2009 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2010 throw new SecurityException("Caller uid " + callerUid
2011 + " not permitted to schedule jobs for other apps");
2012 }
2013
Jeff Sharkey4f100402016-05-03 17:44:23 -06002014 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2015 getContext().enforceCallingOrSelfPermission(
2016 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2017 }
2018
Shreyas Basarge968ac752016-01-11 23:09:26 +00002019 long ident = Binder.clearCallingIdentity();
2020 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002021 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002022 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002023 } finally {
2024 Binder.restoreCallingIdentity(ident);
2025 }
2026 }
2027
2028 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002029 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2030 final int uid = Binder.getCallingUid();
2031
2032 long ident = Binder.clearCallingIdentity();
2033 try {
2034 return JobSchedulerService.this.getPendingJobs(uid);
2035 } finally {
2036 Binder.restoreCallingIdentity(ident);
2037 }
2038 }
2039
2040 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002041 public JobInfo getPendingJob(int jobId) throws RemoteException {
2042 final int uid = Binder.getCallingUid();
2043
2044 long ident = Binder.clearCallingIdentity();
2045 try {
2046 return JobSchedulerService.this.getPendingJob(uid, jobId);
2047 } finally {
2048 Binder.restoreCallingIdentity(ident);
2049 }
2050 }
2051
2052 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002053 public void cancelAll() throws RemoteException {
2054 final int uid = Binder.getCallingUid();
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002055 switch (uid) {
2056 case Process.SYSTEM_UID:
2057 // This really shouldn't happen.
2058 Slog.wtf(TAG, "JobScheduler.cancelAll() called for uid=" + uid);
2059 return;
2060 }
Christopher Tate7060b042014-06-09 19:50:00 -07002061
2062 long ident = Binder.clearCallingIdentity();
2063 try {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002064 JobSchedulerService.this.cancelJobsForUid(uid, "cancelAll() called by app");
Christopher Tate7060b042014-06-09 19:50:00 -07002065 } finally {
2066 Binder.restoreCallingIdentity(ident);
2067 }
2068 }
2069
2070 @Override
2071 public void cancel(int jobId) throws RemoteException {
2072 final int uid = Binder.getCallingUid();
2073
2074 long ident = Binder.clearCallingIdentity();
2075 try {
2076 JobSchedulerService.this.cancelJob(uid, jobId);
2077 } finally {
2078 Binder.restoreCallingIdentity(ident);
2079 }
2080 }
2081
2082 /**
2083 * "dumpsys" infrastructure
2084 */
2085 @Override
2086 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002087 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002088
2089 long identityToken = Binder.clearCallingIdentity();
2090 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002091 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07002092 } finally {
2093 Binder.restoreCallingIdentity(identityToken);
2094 }
2095 }
Christopher Tate5d346052016-03-08 12:56:08 -08002096
2097 @Override
2098 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002099 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002100 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002101 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002102 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002103 };
2104
Christopher Tate5d346052016-03-08 12:56:08 -08002105 // Shell command infrastructure: run the given job immediately
2106 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2107 if (DEBUG) {
2108 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2109 + " " + jobId + " f=" + force);
2110 }
2111
2112 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002113 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2114 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002115 if (uid < 0) {
2116 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2117 }
2118
2119 synchronized (mLock) {
2120 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2121 if (js == null) {
2122 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2123 }
2124
2125 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2126 if (!js.isConstraintsSatisfied()) {
2127 js.overrideState = 0;
2128 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2129 }
2130
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002131 queueReadyJobsForExecutionLocked();
2132 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002133 }
2134 } catch (RemoteException e) {
2135 // can't happen
2136 }
2137 return 0;
2138 }
2139
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002140 // Shell command infrastructure: immediately timeout currently executing jobs
2141 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2142 boolean hasJobId, int jobId) {
2143 if (DEBUG) {
2144 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2145 }
2146
2147 synchronized (mLock) {
2148 boolean foundSome = false;
2149 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002150 final JobServiceContext jc = mActiveServices.get(i);
2151 final JobStatus js = jc.getRunningJobLocked();
2152 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId)) {
2153 foundSome = true;
2154 pw.print("Timing out: ");
2155 js.printUniqueId(pw);
2156 pw.print(" ");
2157 pw.println(js.getServiceComponent().flattenToShortString());
2158 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002159 }
2160 if (!foundSome) {
2161 pw.println("No matching executing jobs found.");
2162 }
2163 }
2164 return 0;
2165 }
2166
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002167 void setMonitorBattery(boolean enabled) {
2168 synchronized (mLock) {
2169 if (mBatteryController != null) {
2170 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2171 }
2172 }
2173 }
2174
2175 int getBatterySeq() {
2176 synchronized (mLock) {
2177 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2178 }
2179 }
2180
2181 boolean getBatteryCharging() {
2182 synchronized (mLock) {
2183 return mBatteryController != null
2184 ? mBatteryController.getTracker().isOnStablePower() : false;
2185 }
2186 }
2187
2188 boolean getBatteryNotLow() {
2189 synchronized (mLock) {
2190 return mBatteryController != null
2191 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2192 }
2193 }
2194
Dianne Hackborn532ea262017-03-17 17:50:55 -07002195 int getStorageSeq() {
2196 synchronized (mLock) {
2197 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2198 }
2199 }
2200
2201 boolean getStorageNotLow() {
2202 synchronized (mLock) {
2203 return mStorageController != null
2204 ? mStorageController.getTracker().isStorageNotLow() : false;
2205 }
2206 }
2207
Dianne Hackborn6d068262017-05-16 13:14:37 -07002208 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2209 try {
2210 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2211 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2212 if (uid < 0) {
2213 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2214 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2215 }
2216
2217 synchronized (mLock) {
2218 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2219 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2220 if (js == null) {
2221 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2222 pw.print("/jid"); pw.print(jobId); pw.println(")");
2223 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2224 }
2225
2226 boolean printed = false;
2227 if (mPendingJobs.contains(js)) {
2228 pw.print("pending");
2229 printed = true;
2230 }
2231 if (isCurrentlyActiveLocked(js)) {
2232 if (printed) {
2233 pw.print(" ");
2234 }
2235 printed = true;
2236 pw.println("active");
2237 }
2238 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2239 if (printed) {
2240 pw.print(" ");
2241 }
2242 printed = true;
2243 pw.println("user-stopped");
2244 }
2245 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2246 if (printed) {
2247 pw.print(" ");
2248 }
2249 printed = true;
2250 pw.println("backing-up");
2251 }
2252 boolean componentPresent = false;
2253 try {
2254 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2255 js.getServiceComponent(),
2256 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2257 js.getUserId()) != null);
2258 } catch (RemoteException e) {
2259 }
2260 if (!componentPresent) {
2261 if (printed) {
2262 pw.print(" ");
2263 }
2264 printed = true;
2265 pw.println("no-component");
2266 }
2267 if (js.isReady()) {
2268 if (printed) {
2269 pw.print(" ");
2270 }
2271 printed = true;
2272 pw.println("ready");
2273 }
2274 if (!printed) {
2275 pw.print("waiting");
2276 }
2277 pw.println();
2278 }
2279 } catch (RemoteException e) {
2280 // can't happen
2281 }
2282 return 0;
2283 }
2284
Shreyas Basarge5db09082016-01-07 13:38:29 +00002285 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2286 StringBuilder s = new StringBuilder(initial + ": ");
2287 for (int i=0; i<map.length; i++) {
2288 s.append("(")
2289 .append(map[i] == null? -1: map[i].getJobId())
2290 .append(map[i] == null? -1: map[i].getUid())
2291 .append(")" );
2292 }
2293 return s.toString();
2294 }
2295
2296 private String printPendingQueue() {
2297 StringBuilder s = new StringBuilder("Pending queue: ");
2298 Iterator<JobStatus> it = mPendingJobs.iterator();
2299 while (it.hasNext()) {
2300 JobStatus js = it.next();
2301 s.append("(")
2302 .append(js.getJob().getId())
2303 .append(", ")
2304 .append(js.getUid())
2305 .append(") ");
2306 }
2307 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002308 }
Christopher Tate7060b042014-06-09 19:50:00 -07002309
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002310 static void dumpHelp(PrintWriter pw) {
2311 pw.println("Job Scheduler (jobscheduler) dump options:");
2312 pw.println(" [-h] [package] ...");
2313 pw.println(" -h: print this help");
2314 pw.println(" [package] is an optional package name to limit the output to.");
2315 }
2316
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002317 void dumpInternal(final PrintWriter pw, String[] args) {
2318 int filterUid = -1;
2319 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002320 int opti = 0;
2321 while (opti < args.length) {
2322 String arg = args[opti];
2323 if ("-h".equals(arg)) {
2324 dumpHelp(pw);
2325 return;
2326 } else if ("-a".equals(arg)) {
2327 // Ignore, we always dump all.
2328 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2329 pw.println("Unknown option: " + arg);
2330 return;
2331 } else {
2332 break;
2333 }
2334 opti++;
2335 }
2336 if (opti < args.length) {
2337 String pkg = args[opti];
2338 try {
2339 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002340 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002341 } catch (NameNotFoundException ignored) {
2342 pw.println("Invalid package: " + pkg);
2343 return;
2344 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002345 }
2346 }
2347
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002348 final int filterUidFinal = UserHandle.getAppId(filterUid);
Dianne Hackborn6d068262017-05-16 13:14:37 -07002349 final long nowElapsed = SystemClock.elapsedRealtime();
2350 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002351 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002352 mConstants.dump(pw);
2353 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002354 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002355 pw.print("Registered ");
2356 pw.print(mJobs.size());
2357 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002358 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002359 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2360 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002361 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002362 public int compare(JobStatus o1, JobStatus o2) {
2363 int uid1 = o1.getUid();
2364 int uid2 = o2.getUid();
2365 int id1 = o1.getJobId();
2366 int id2 = o2.getJobId();
2367 if (uid1 != uid2) {
2368 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002369 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002370 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08002371 }
2372 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002373 for (JobStatus job : jobs) {
2374 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2375 pw.println(job.toShortStringExceptUniqueId());
2376
2377 // Skip printing details if the caller requested a filter
2378 if (!job.shouldDump(filterUidFinal)) {
2379 continue;
2380 }
2381
Dianne Hackborn6d068262017-05-16 13:14:37 -07002382 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002383 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002384 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002385 pw.print(" (job=");
2386 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002387 pw.print(" user=");
2388 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002389 pw.print(" !pending=");
2390 pw.print(!mPendingJobs.contains(job));
2391 pw.print(" !active=");
2392 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002393 pw.print(" !backingup=");
2394 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002395 pw.print(" comp=");
2396 boolean componentPresent = false;
2397 try {
2398 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2399 job.getServiceComponent(),
2400 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2401 job.getUserId()) != null);
2402 } catch (RemoteException e) {
2403 }
2404 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002405 pw.println(")");
2406 }
Christopher Tate7060b042014-06-09 19:50:00 -07002407 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002408 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002409 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002410 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002411 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002412 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002413 }
2414 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002415 pw.println("Uid priority overrides:");
2416 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002417 int uid = mUidPriorityOverride.keyAt(i);
2418 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2419 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2420 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2421 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002422 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002423 if (mBackingUpUids.size() > 0) {
2424 pw.println();
2425 pw.println("Backing up uids:");
2426 boolean first = true;
2427 for (int i = 0; i < mBackingUpUids.size(); i++) {
2428 int uid = mBackingUpUids.keyAt(i);
2429 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2430 if (first) {
2431 pw.print(" ");
2432 first = false;
2433 } else {
2434 pw.print(", ");
2435 }
2436 pw.print(UserHandle.formatUid(uid));
2437 }
2438 }
2439 pw.println();
2440 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002441 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002442 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002443 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002444 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2445 pw.println();
2446 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002447 pw.println("Pending queue:");
2448 for (int i=0; i<mPendingJobs.size(); i++) {
2449 JobStatus job = mPendingJobs.get(i);
2450 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2451 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002452 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002453 int priority = evaluateJobPriorityLocked(job);
2454 if (priority != JobInfo.PRIORITY_DEFAULT) {
2455 pw.print(" Evaluated priority: "); pw.println(priority);
2456 }
2457 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002458 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002459 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002460 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002461 }
Christopher Tate7060b042014-06-09 19:50:00 -07002462 pw.println();
2463 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002464 for (int i=0; i<mActiveServices.size(); i++) {
2465 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002466 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002467 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002468 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002469 if (jsc.mStoppedReason != null) {
2470 pw.print("inactive since ");
2471 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2472 pw.print(", stopped because: ");
2473 pw.println(jsc.mStoppedReason);
2474 } else {
2475 pw.println("inactive");
2476 }
Christopher Tate7060b042014-06-09 19:50:00 -07002477 continue;
2478 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002479 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002480 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002481 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002482 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002483 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002484 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002485 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002486 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002487 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002488 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002489 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002490 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002491 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002492 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002493 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2494 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002495 }
2496 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002497 if (filterUid == -1) {
2498 pw.println();
2499 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2500 pw.print("mReportedActive="); pw.println(mReportedActive);
2501 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2502 }
Christopher Tate7060b042014-06-09 19:50:00 -07002503 }
2504 pw.println();
2505 }
2506}