blob: 3fc76c055529fcad27a1e64e0d34904ca54ca99e [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;
Christopher Tate7060b042014-06-09 19:50:00 -070083import com.android.server.job.controllers.BatteryController;
84import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080085import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070086import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070087import com.android.server.job.controllers.IdleController;
88import com.android.server.job.controllers.JobStatus;
89import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070090import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070091import com.android.server.job.controllers.TimeController;
92
Jeff Sharkey822cbd12016-02-25 11:09:55 -070093import libcore.util.EmptyArray;
94
Christopher Tate7060b042014-06-09 19:50:00 -070095/**
96 * Responsible for taking jobs representing work to be performed by a client app, and determining
97 * based on the criteria specified when that job should be run against the client application's
98 * endpoint.
99 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
100 * about constraints, or the state of active jobs. It receives callbacks from the various
101 * controllers and completed jobs and operates accordingly.
102 *
103 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
104 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
105 * @hide
106 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800107public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700108 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800109 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700110 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800111
Dianne Hackborn970510b2016-02-24 16:56:42 -0800112 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700113 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800114 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800115 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800116 /** The maximum number of jobs that we allow an unprivileged app to schedule */
117 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700118
Christopher Tate2f36fd62016-02-18 18:36:08 -0800119
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800120 /** Global local for all job scheduler state. */
121 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700122 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700123 final JobStore mJobs;
Dianne Hackborn807de782016-04-07 17:54:41 -0700124 /** Tracking amount of time each package runs for. */
125 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700126
127 static final int MSG_JOB_EXPIRED = 0;
128 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700129 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000130 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700131
Christopher Tate7060b042014-06-09 19:50:00 -0700132 /**
133 * Track Services that have currently active or pending jobs. The index is provided by
134 * {@link JobStatus#getServiceToken()}
135 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700136 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700137 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700138 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800139 /** Need direct access to this for testing. */
140 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700141 /** Need direct access to this for testing. */
142 StorageController mStorageController;
Christopher Tate7060b042014-06-09 19:50:00 -0700143 /**
144 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
145 * when ready to execute them.
146 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700147 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700148
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700149 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700150
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700151 final JobHandler mHandler;
152 final JobSchedulerStub mJobSchedulerStub;
153
154 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700155 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800156 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700157
158 /**
159 * Set to true once we are allowed to run third party apps.
160 */
161 boolean mReadyToRock;
162
Christopher Tate7060b042014-06-09 19:50:00 -0700163 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800164 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800165 */
166 boolean mReportedActive;
167
168 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800169 * Current limit on the number of concurrent JobServiceContext entries we want to
170 * keep actively running a job.
171 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700172 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800173
174 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800175 * Which uids are currently in the foreground.
176 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800177 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
178
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700179 /**
180 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
181 */
182 final SparseIntArray mBackingUpUids = new SparseIntArray();
183
Dianne Hackborn970510b2016-02-24 16:56:42 -0800184 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
185
186 /**
187 * This array essentially stores the state of mActiveServices array.
188 * The ith index stores the job present on the ith JobServiceContext.
189 * We manipulate this array until we arrive at what jobs should be running on
190 * what JobServiceContext.
191 */
192 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
193 /**
194 * Indicates whether we need to act on this jobContext id
195 */
196 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
197 /**
198 * The uid whose jobs we would like to assign to a context.
199 */
200 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800201
202 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700203 * All times are in milliseconds. These constants are kept synchronized with the system
204 * global Settings. Any access to this class or its fields should be done while
205 * holding the JobSchedulerService.mLock lock.
206 */
207 private final class Constants extends ContentObserver {
208 // Key names stored in the settings value.
209 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
210 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800211 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700212 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700213 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
214 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
215 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
216 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
217 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
218 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
219 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
220 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
221 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
222 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700223 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
224 = "max_standard_reschedule_count";
225 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
226 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
227 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700228
229 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
230 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800231 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700232 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700233 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
234 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
235 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
236 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
237 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
238 private static final int DEFAULT_FG_JOB_COUNT = 4;
239 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
240 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700241 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700242 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700243 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
244 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
245 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
246 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700247
248 /**
249 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
250 * early.
251 */
252 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
253 /**
254 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
255 * things early.
256 */
257 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
258 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800259 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
260 * schedule things early.
261 */
262 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
263 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700264 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
265 * schedule things early.
266 */
267 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
268 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700269 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
270 * things early. 1 == Run connectivity jobs as soon as ready.
271 */
272 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
273 /**
274 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
275 * schedule things early.
276 */
277 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
278 /**
279 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
280 * running some work early. This (and thus the other min counts) is now set to 1, to
281 * prevent any batching at this level. Since we now do batching through doze, that is
282 * a much better mechanism.
283 */
284 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
285 /**
286 * This is the job execution factor that is considered to be heavy use of the system.
287 */
288 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
289 /**
290 * This is the job execution factor that is considered to be moderate use of the system.
291 */
292 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
293 /**
294 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
295 */
296 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
297 /**
298 * The maximum number of background jobs we allow when the system is in a normal
299 * memory state.
300 */
301 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
302 /**
303 * The maximum number of background jobs we allow when the system is in a moderate
304 * memory state.
305 */
306 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
307 /**
308 * The maximum number of background jobs we allow when the system is in a low
309 * memory state.
310 */
311 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
312 /**
313 * The maximum number of background jobs we allow when the system is in a critical
314 * memory state.
315 */
316 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700317 /**
318 * The maximum number of times we allow a job to have itself rescheduled before
319 * giving up on it, for standard jobs.
320 */
321 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
322 /**
323 * The maximum number of times we allow a job to have itself rescheduled before
324 * giving up on it, for jobs that are executing work.
325 */
326 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
327 /**
328 * The minimum backoff time to allow for linear backoff.
329 */
330 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
331 /**
332 * The minimum backoff time to allow for exponential backoff.
333 */
334 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700335
336 private ContentResolver mResolver;
337 private final KeyValueListParser mParser = new KeyValueListParser(',');
338
339 public Constants(Handler handler) {
340 super(handler);
341 }
342
343 public void start(ContentResolver resolver) {
344 mResolver = resolver;
345 mResolver.registerContentObserver(Settings.Global.getUriFor(
346 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
347 updateConstants();
348 }
349
350 @Override
351 public void onChange(boolean selfChange, Uri uri) {
352 updateConstants();
353 }
354
355 private void updateConstants() {
356 synchronized (mLock) {
357 try {
358 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000359 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700360 } catch (IllegalArgumentException e) {
361 // Failed to parse the settings string, log this and move on
362 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000363 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700364 }
365
366 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
367 DEFAULT_MIN_IDLE_COUNT);
368 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
369 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800370 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
371 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700372 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
373 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700374 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
375 DEFAULT_MIN_CONNECTIVITY_COUNT);
376 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
377 DEFAULT_MIN_CONTENT_COUNT);
378 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
379 DEFAULT_MIN_READY_JOBS_COUNT);
380 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
381 DEFAULT_HEAVY_USE_FACTOR);
382 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
383 DEFAULT_MODERATE_USE_FACTOR);
384 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
385 DEFAULT_FG_JOB_COUNT);
386 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
387 DEFAULT_BG_NORMAL_JOB_COUNT);
388 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
389 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
390 }
391 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
392 DEFAULT_BG_MODERATE_JOB_COUNT);
393 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
394 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
395 }
396 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
397 DEFAULT_BG_LOW_JOB_COUNT);
398 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
399 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
400 }
401 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
402 DEFAULT_BG_CRITICAL_JOB_COUNT);
403 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
404 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
405 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700406 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
407 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
408 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
409 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
410 MIN_LINEAR_BACKOFF_TIME = mParser.getLong(KEY_MIN_LINEAR_BACKOFF_TIME,
411 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
412 MIN_EXP_BACKOFF_TIME = mParser.getLong(KEY_MIN_EXP_BACKOFF_TIME,
413 DEFAULT_MIN_EXP_BACKOFF_TIME);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700414 }
415 }
416
417 void dump(PrintWriter pw) {
418 pw.println(" Settings:");
419
420 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
421 pw.print(MIN_IDLE_COUNT); pw.println();
422
423 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
424 pw.print(MIN_CHARGING_COUNT); pw.println();
425
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800426 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
427 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
428
Dianne Hackborn532ea262017-03-17 17:50:55 -0700429 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
430 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
431
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700432 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
433 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
434
435 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
436 pw.print(MIN_CONTENT_COUNT); pw.println();
437
438 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
439 pw.print(MIN_READY_JOBS_COUNT); pw.println();
440
441 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
442 pw.print(HEAVY_USE_FACTOR); pw.println();
443
444 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
445 pw.print(MODERATE_USE_FACTOR); pw.println();
446
447 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
448 pw.print(FG_JOB_COUNT); pw.println();
449
450 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
451 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
452
453 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
454 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
455
456 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
457 pw.print(BG_LOW_JOB_COUNT); pw.println();
458
459 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
460 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700461
462 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
463 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
464
465 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
466 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
467
468 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
469 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
470
471 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
472 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700473 }
474 }
475
476 final Constants mConstants;
477
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700478 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
479 if (o1.enqueueTime < o2.enqueueTime) {
480 return -1;
481 }
482 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
483 };
484
485 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
486 int where = Collections.binarySearch(array, newItem, comparator);
487 if (where < 0) {
488 where = ~where;
489 }
490 array.add(where, newItem);
491 }
492
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700493 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700494 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
495 * still clean up. On reinstall the package will have a new uid.
496 */
497 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
498 @Override
499 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700500 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700501 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700502 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700503 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700504 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700505 // Purge the app's jobs if the whole package was just disabled. When this is
506 // the case the component name will be a bare package name.
507 final String pkgName = getPackageName(intent);
508 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
509 if (pkgName != null && pkgUid != -1) {
510 final String[] changedComponents = intent.getStringArrayExtra(
511 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
512 if (changedComponents != null) {
513 for (String component : changedComponents) {
514 if (component.equals(pkgName)) {
515 if (DEBUG) {
516 Slog.d(TAG, "Package state change: " + pkgName);
517 }
518 try {
519 final int userId = UserHandle.getUserId(pkgUid);
520 IPackageManager pm = AppGlobals.getPackageManager();
521 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
522 if (state == COMPONENT_ENABLED_STATE_DISABLED
523 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
524 if (DEBUG) {
525 Slog.d(TAG, "Removing jobs for package " + pkgName
526 + " in user " + userId);
527 }
Dianne Hackborn729a3282017-06-09 16:06:01 -0700528 cancelJobsForUid(pkgUid, "app package state changed");
Christopher Tateb5c07882016-05-26 17:11:09 -0700529 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700530 } catch (RemoteException|IllegalArgumentException e) {
531 /*
532 * IllegalArgumentException means that the package doesn't exist.
533 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
534 * behind outright uninstall, so by the time we try to act it's gone.
535 * We don't need to act on this PACKAGE_CHANGED when this happens;
536 * we'll get a PACKAGE_REMOVED later and clean up then.
537 *
538 * RemoteException can't actually happen; the package manager is
539 * running in this same process.
540 */
541 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700542 break;
543 }
544 }
545 }
546 } else {
547 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
548 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700549 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700550 // If this is an outright uninstall rather than the first half of an
551 // app update sequence, cancel the jobs associated with the app.
552 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
553 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
554 if (DEBUG) {
555 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
556 }
Dianne Hackborn729a3282017-06-09 16:06:01 -0700557 cancelJobsForUid(uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700558 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700559 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700560 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
561 if (DEBUG) {
562 Slog.d(TAG, "Removing jobs for user: " + userId);
563 }
564 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700565 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
566 // Has this package scheduled any jobs, such that we will take action
567 // if it were to be force-stopped?
568 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
569 final String pkgName = intent.getData().getSchemeSpecificPart();
570 if (pkgUid != -1) {
571 List<JobStatus> jobsForUid;
572 synchronized (mLock) {
573 jobsForUid = mJobs.getJobsByUid(pkgUid);
574 }
575 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
576 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
577 if (DEBUG) {
578 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
579 + pkgUid + " has jobs");
580 }
581 setResultCode(Activity.RESULT_OK);
582 break;
583 }
584 }
585 }
586 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
587 // possible force-stop
588 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
589 final String pkgName = intent.getData().getSchemeSpecificPart();
590 if (pkgUid != -1) {
591 if (DEBUG) {
592 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
593 }
594 cancelJobsForPackageAndUid(pkgName, pkgUid);
595 }
Christopher Tate7060b042014-06-09 19:50:00 -0700596 }
597 }
598 };
599
Christopher Tateb5c07882016-05-26 17:11:09 -0700600 private String getPackageName(Intent intent) {
601 Uri uri = intent.getData();
602 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
603 return pkg;
604 }
605
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700606 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700607 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800608 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700609 }
610
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700611 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800612 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800613 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700614 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800615 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700616 }
617
618 @Override public void onUidActive(int uid) throws RemoteException {
619 }
620
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700621 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800622 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700623 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800624 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700625 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700626
627 @Override public void onUidCachedChanged(int uid, boolean cached) {
628 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700629 };
630
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800631 public Object getLock() {
632 return mLock;
633 }
634
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700635 public JobStore getJobStore() {
636 return mJobs;
637 }
638
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700639 @Override
640 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700641 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
642 // Let's kick any outstanding jobs for this user.
643 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
644 }
645
646 @Override
647 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700648 // Let's kick any outstanding jobs for this user.
649 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
650 }
651
652 @Override
653 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700654 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700655 }
656
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700657 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
658 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700659 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800660 if (ActivityManager.getService().isAppStartModeDisabled(uId,
661 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700662 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
663 + " -- package not allowed to start");
664 return JobScheduler.RESULT_FAILURE;
665 }
666 } catch (RemoteException e) {
667 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800668 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700669 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
670
671 if (work != null && toCancel != null) {
672 // Fast path: we are adding work to an existing job, and the JobInfo is not
673 // changing. We can just directly enqueue this work in to the job.
674 if (toCancel.getJob().equals(job)) {
Dianne Hackborn342e6032017-04-13 18:04:31 -0700675 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700676 return JobScheduler.RESULT_SUCCESS;
677 }
678 }
679
680 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
681 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800682 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800683 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800684 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
685 Slog.w(TAG, "Too many jobs for uid " + uId);
686 throw new IllegalStateException("Apps may not schedule more than "
687 + MAX_JOBS_PER_APP + " distinct jobs");
688 }
689 }
690
Dianne Hackborna47223f2017-03-30 13:49:13 -0700691 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700692 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700693
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700694 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700695 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700696 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700697 if (work != null) {
698 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700699 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700700 }
701 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700702
703 // If the job is immediately ready to run, then we can just immediately
704 // put it in the pending list and try to schedule it. This is especially
705 // important for jobs with a 0 deadline constraint, since they will happen a fair
706 // amount, we want to handle them as quickly as possible, and semantically we want to
707 // make sure we have started holding the wake lock for the job before returning to
708 // the caller.
709 // If the job is not yet ready to run, there is nothing more to do -- we are
710 // now just waiting for one of its controllers to change state and schedule
711 // the job appropriately.
712 if (isReadyToBeExecutedLocked(jobStatus)) {
713 // This is a new job, we can just immediately put it on the pending
714 // list and try to run it.
715 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700716 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700717 maybeRunPendingJobsLocked();
718 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800719 }
Christopher Tate7060b042014-06-09 19:50:00 -0700720 return JobScheduler.RESULT_SUCCESS;
721 }
722
723 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800724 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800725 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
726 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
727 for (int i = jobs.size() - 1; i >= 0; i--) {
728 JobStatus job = jobs.get(i);
729 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700730 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800731 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700732 }
Christopher Tate7060b042014-06-09 19:50:00 -0700733 }
734
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600735 public JobInfo getPendingJob(int uid, int jobId) {
736 synchronized (mLock) {
737 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
738 for (int i = jobs.size() - 1; i >= 0; i--) {
739 JobStatus job = jobs.get(i);
740 if (job.getJobId() == jobId) {
741 return job.getJob();
742 }
743 }
744 return null;
745 }
746 }
747
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700748 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800749 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700750 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
751 for (int i=0; i<jobsForUser.size(); i++) {
752 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700753 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700754 }
Christopher Tate7060b042014-06-09 19:50:00 -0700755 }
756 }
757
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700758 private void cancelJobsForNonExistentUsers() {
759 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
760 synchronized (mLock) {
761 mJobs.removeJobsOfNonUsers(umi.getUserIds());
762 }
763 }
764
Christopher Tateee7805b2016-07-15 16:56:56 -0700765 void cancelJobsForPackageAndUid(String pkgName, int uid) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700766 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700767 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
768 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
769 final JobStatus job = jobsForUid.get(i);
770 if (job.getSourcePackageName().equals(pkgName)) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700771 cancelJobImplLocked(job, null, "app force stopped");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700772 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700773 }
774 }
775 }
776
Christopher Tate7060b042014-06-09 19:50:00 -0700777 /**
778 * Entry point from client to cancel all jobs originating from their uid.
779 * This will remove the job from the master list, and cancel the job if it was staged for
780 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700781 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800782 *
Christopher Tate7060b042014-06-09 19:50:00 -0700783 */
Dianne Hackborn729a3282017-06-09 16:06:01 -0700784 public void cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700785 if (uid == Process.SYSTEM_UID) {
786 // This really shouldn't happen.
787 Slog.wtfStack(TAG, "cancelJobsForUid() called for system uid");
788 return;
789 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800790 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700791 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
792 for (int i=0; i<jobsForUid.size(); i++) {
793 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700794 cancelJobImplLocked(toRemove, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700795 }
Christopher Tate7060b042014-06-09 19:50:00 -0700796 }
797 }
798
799 /**
800 * Entry point from client to cancel the job corresponding to the jobId provided.
801 * This will remove the job from the master list, and cancel the job if it was staged for
802 * execution or being executed.
803 * @param uid Uid of the calling client.
804 * @param jobId Id of the job, provided at schedule-time.
805 */
806 public void cancelJob(int uid, int jobId) {
807 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800808 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700809 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700810 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700811 cancelJobImplLocked(toCancel, null, "cancel() called by app");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700812 }
Christopher Tate7060b042014-06-09 19:50:00 -0700813 }
814 }
815
Dianne Hackborn729a3282017-06-09 16:06:01 -0700816 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700817 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
818 cancelled.unprepareLocked(ActivityManager.getService());
819 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
820 // Remove from pending queue.
821 if (mPendingJobs.remove(cancelled)) {
822 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700823 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700824 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700825 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700826 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700827 }
828
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800829 void updateUidState(int uid, int procState) {
830 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800831 if (procState == ActivityManager.PROCESS_STATE_TOP) {
832 // Only use this if we are exactly the top app. All others can live
833 // with just the foreground priority. This means that persistent processes
834 // can never be the top app priority... that is fine.
835 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
836 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
837 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800838 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800839 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800840 }
841 }
842 }
843
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700844 @Override
845 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800846 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700847 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600848 // When becoming idle, make sure no jobs are actively running,
849 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700850 for (int i=0; i<mActiveServices.size(); i++) {
851 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700852 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600853 if (executing != null
854 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700855 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
856 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700857 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700858 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700859 } else {
860 // When coming out of idle, allow thing to start back up.
861 if (mReadyToRock) {
862 if (mLocalDeviceIdleController != null) {
863 if (!mReportedActive) {
864 mReportedActive = true;
865 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700866 }
867 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700868 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700869 }
870 }
871 }
872 }
873
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700874 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000875 // active is true if pending queue contains jobs OR some job is running.
876 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800877 if (mPendingJobs.size() <= 0) {
878 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700879 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700880 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700881 if (job != null
882 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
883 && !job.dozeWhitelisted) {
884 // We will report active if we have a job running and it is not an exception
885 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800886 active = true;
887 break;
888 }
889 }
890 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000891
892 if (mReportedActive != active) {
893 mReportedActive = active;
894 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800895 mLocalDeviceIdleController.setJobsActive(active);
896 }
897 }
898 }
899
Christopher Tate7060b042014-06-09 19:50:00 -0700900 /**
901 * Initializes the system service.
902 * <p>
903 * Subclasses must define a single argument constructor that accepts the context
904 * and passes it to super.
905 * </p>
906 *
907 * @param context The system server context.
908 */
909 public JobSchedulerService(Context context) {
910 super(context);
Dianne Hackborn970e3f42016-06-01 10:55:13 -0700911 mHandler = new JobHandler(context.getMainLooper());
912 mConstants = new Constants(mHandler);
913 mJobSchedulerStub = new JobSchedulerStub();
914 mJobs = JobStore.initAndGet(this);
915
Christopher Tate7060b042014-06-09 19:50:00 -0700916 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700917 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700918 mControllers.add(ConnectivityController.get(this));
919 mControllers.add(TimeController.get(this));
920 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800921 mBatteryController = BatteryController.get(this);
922 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700923 mStorageController = StorageController.get(this);
924 mControllers.add(mStorageController);
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800925 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800926 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700927 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate616541d2017-07-26 14:27:38 -0700928
929 // If the job store determined that it can't yet reschedule persisted jobs,
930 // we need to start watching the clock.
931 if (!mJobs.jobTimesInflatedValid()) {
932 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
933 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
934 }
Christopher Tate7060b042014-06-09 19:50:00 -0700935 }
936
Christopher Tate616541d2017-07-26 14:27:38 -0700937 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
938 @Override
939 public void onReceive(Context context, Intent intent) {
940 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
941 // When we reach clock sanity, recalculate the temporal windows
942 // of all affected jobs.
943 if (mJobs.clockNowValidToInflate(System.currentTimeMillis())) {
944 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
945
946 // We've done our job now, so stop watching the time.
947 context.unregisterReceiver(this);
948
949 // And kick off the work to update the affected jobs, using a secondary
950 // thread instead of chugging away here on the main looper thread.
951 FgThread.getHandler().post(mJobTimeUpdater);
952 }
953 }
954 }
955 };
956
957 private final Runnable mJobTimeUpdater = () -> {
958 final ArrayList<JobStatus> toRemove = new ArrayList<>();
959 final ArrayList<JobStatus> toAdd = new ArrayList<>();
960 synchronized (mLock) {
961 // Note: we intentionally both look up the existing affected jobs and replace them
962 // with recalculated ones inside the same lock lifetime.
963 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
964
965 // Now, at each position [i], we have both the existing JobStatus
966 // and the one that replaces it.
967 final int N = toAdd.size();
968 for (int i = 0; i < N; i++) {
969 final JobStatus oldJob = toRemove.get(i);
970 final JobStatus newJob = toAdd.get(i);
971 if (DEBUG) {
972 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
973 }
974 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
975 }
976 }
977 };
978
Christopher Tate7060b042014-06-09 19:50:00 -0700979 @Override
980 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000981 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -0700982 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
983 }
984
985 @Override
986 public void onBootPhase(int phase) {
987 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700988 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +0000989 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -0700990 final IntentFilter filter = new IntentFilter();
991 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
992 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -0700993 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
994 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -0700995 filter.addDataScheme("package");
996 getContext().registerReceiverAsUser(
997 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
998 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
999 getContext().registerReceiverAsUser(
1000 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001001 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001002 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001003 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001004 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Dianne Hackborn5614bf52016-11-07 17:26:41 -08001005 | ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN,
1006 null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001007 } catch (RemoteException e) {
1008 // ignored; both services live in system_server
1009 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001010 // Remove any jobs that are not associated with any of the current users.
1011 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001012 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001013 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001014 // Let's go!
1015 mReadyToRock = true;
1016 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1017 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001018 mLocalDeviceIdleController
1019 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001020 // Create the "runners".
1021 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1022 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001023 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001024 getContext().getMainLooper()));
1025 }
1026 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001027 mJobs.forEachJob(new JobStatusFunctor() {
1028 @Override
1029 public void process(JobStatus job) {
1030 for (int controller = 0; controller < mControllers.size(); controller++) {
1031 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001032 sc.maybeStartTrackingJobLocked(job, null);
1033 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001034 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001035 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001036 // GO GO GO!
1037 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1038 }
Christopher Tate7060b042014-06-09 19:50:00 -07001039 }
1040 }
1041
1042 /**
1043 * Called when we have a job status object that we need to insert in our
1044 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1045 * about.
1046 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001047 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1048 if (!jobStatus.isPreparedLocked()) {
1049 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1050 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001051 jobStatus.enqueueTime = SystemClock.elapsedRealtime();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001052 final boolean update = mJobs.add(jobStatus);
1053 if (mReadyToRock) {
1054 for (int i = 0; i < mControllers.size(); i++) {
1055 StateController controller = mControllers.get(i);
1056 if (update) {
1057 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001058 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001059 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001060 }
Christopher Tate7060b042014-06-09 19:50:00 -07001061 }
1062 }
1063
1064 /**
1065 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1066 * object removed.
1067 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001068 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001069 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001070 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001071 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001072
1073 // Remove from store as well as controllers.
1074 final boolean removed = mJobs.remove(jobStatus, writeBack);
1075 if (removed && mReadyToRock) {
1076 for (int i=0; i<mControllers.size(); i++) {
1077 StateController controller = mControllers.get(i);
1078 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001079 }
1080 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001081 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001082 }
1083
Dianne Hackborn729a3282017-06-09 16:06:01 -07001084 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001085 for (int i=0; i<mActiveServices.size(); i++) {
1086 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001087 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001088 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001089 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001090 return true;
1091 }
1092 }
1093 return false;
1094 }
1095
1096 /**
1097 * @param job JobStatus we are querying against.
1098 * @return Whether or not the job represented by the status object is currently being run or
1099 * is pending.
1100 */
1101 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001102 for (int i=0; i<mActiveServices.size(); i++) {
1103 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001104 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001105 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1106 return true;
1107 }
1108 }
1109 return false;
1110 }
1111
Dianne Hackborn807de782016-04-07 17:54:41 -07001112 void noteJobsPending(List<JobStatus> jobs) {
1113 for (int i = jobs.size() - 1; i >= 0; i--) {
1114 JobStatus job = jobs.get(i);
1115 mJobPackageTracker.notePending(job);
1116 }
1117 }
1118
1119 void noteJobsNonpending(List<JobStatus> jobs) {
1120 for (int i = jobs.size() - 1; i >= 0; i--) {
1121 JobStatus job = jobs.get(i);
1122 mJobPackageTracker.noteNonpending(job);
1123 }
1124 }
1125
Christopher Tate7060b042014-06-09 19:50:00 -07001126 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001127 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1128 * specify an override deadline on a failed job (the failed job will run even though it's not
1129 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1130 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1131 *
Christopher Tate7060b042014-06-09 19:50:00 -07001132 * @param failureToReschedule Provided job status that we will reschedule.
1133 * @return A newly instantiated JobStatus with the same constraints as the last job except
1134 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001135 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001136 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001137 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001138 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001139 final long elapsedNowMillis = SystemClock.elapsedRealtime();
1140 final JobInfo job = failureToReschedule.getJob();
1141
1142 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001143 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1144 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001145
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001146 if (failureToReschedule.hasWorkLocked()) {
1147 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1148 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1149 + backoffAttempts + " > work limit "
1150 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1151 return null;
1152 }
1153 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1154 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1155 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1156 return null;
1157 }
1158
Christopher Tate7060b042014-06-09 19:50:00 -07001159 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001160 case JobInfo.BACKOFF_POLICY_LINEAR: {
1161 long backoff = initialBackoffMillis;
1162 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1163 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1164 }
1165 delayMillis = backoff * backoffAttempts;
1166 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001167 default:
1168 if (DEBUG) {
1169 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1170 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001171 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1172 long backoff = initialBackoffMillis;
1173 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1174 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1175 }
1176 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1177 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001178 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001179 delayMillis =
1180 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001181 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001182 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
1183 failureToReschedule.getLastSuccessfulRunTime(), System.currentTimeMillis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001184 for (int ic=0; ic<mControllers.size(); ic++) {
1185 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001186 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001187 }
1188 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001189 }
1190
1191 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001192 * Called after a periodic has executed so we can reschedule it. We take the last execution
1193 * time of the job to be the time of completion (i.e. the time at which this function is
1194 * called).
Christopher Tate7060b042014-06-09 19:50:00 -07001195 * This could be inaccurate b/c the job can run for as long as
1196 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1197 * to underscheduling at least, rather than if we had taken the last execution time to be the
1198 * start of the execution.
1199 * @return A new job representing the execution criteria for this instantiation of the
1200 * recurring job.
1201 */
1202 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
1203 final long elapsedNow = SystemClock.elapsedRealtime();
1204 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001205 long runEarly = 0L;
1206
1207 // If this periodic was rescheduled it won't have a deadline.
1208 if (periodicToReschedule.hasDeadlineConstraint()) {
1209 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1210 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001211 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001212 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001213 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1214 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001215
1216 if (DEBUG) {
1217 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1218 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1219 }
1220 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001221 newLatestRuntimeElapsed, 0 /* backoffAttempt */,
1222 System.currentTimeMillis() /* lastSuccessfulRunTime */,
1223 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001224 }
1225
1226 // JobCompletedListener implementations.
1227
1228 /**
1229 * A job just finished executing. We fetch the
1230 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1231 * whether we want to reschedule we readd it to the controllers.
1232 * @param jobStatus Completed job.
1233 * @param needsReschedule Whether the implementing class should reschedule this job.
1234 */
1235 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001236 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001237 if (DEBUG) {
1238 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1239 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001240
1241 // If the job wants to be rescheduled, we first need to make the next upcoming
1242 // job so we can transfer any appropriate state over from the previous job when
1243 // we stop it.
1244 final JobStatus rescheduledJob = needsReschedule
1245 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1246
Shreyas Basarge73f10252016-02-11 17:06:13 +00001247 // Do not write back immediately if this is a periodic job. The job may get lost if system
1248 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001249 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001250 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001251 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001252 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001253 // We still want to check for jobs to execute, because this job may have
1254 // scheduled a new job under the same job id, and now we can run it.
1255 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001256 return;
1257 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001258
1259 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001260 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001261 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001262 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001263 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001264 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001265 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001266 } else if (jobStatus.getJob().isPeriodic()) {
1267 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001268 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001269 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001270 } catch (SecurityException e) {
1271 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1272 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001273 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001274 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001275 jobStatus.unprepareLocked(ActivityManager.getService());
1276 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001277 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001278 }
1279
1280 // StateChangedListener implementations.
1281
1282 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001283 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1284 * some controller's state has changed, so as to run through the list of jobs and start/stop
1285 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001286 */
1287 @Override
1288 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001289 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001290 }
1291
1292 @Override
1293 public void onRunJobNow(JobStatus jobStatus) {
1294 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1295 }
1296
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001297 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001298
1299 public JobHandler(Looper looper) {
1300 super(looper);
1301 }
1302
1303 @Override
1304 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001305 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001306 if (!mReadyToRock) {
1307 return;
1308 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001309 switch (message.what) {
1310 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001311 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001312 // runNow can be null, which is a controller's way of indicating that its
1313 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001314 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001315 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001316 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001317 } else {
1318 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001319 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001320 } break;
1321 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001322 if (mReportedActive) {
1323 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001324 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001325 } else {
1326 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001327 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001328 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001329 break;
1330 case MSG_CHECK_JOB_GREEDY:
1331 queueReadyJobsForExecutionLocked();
1332 break;
1333 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001334 cancelJobImplLocked((JobStatus) message.obj, null,
1335 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001336 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001337 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001338 maybeRunPendingJobsLocked();
1339 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1340 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001341 }
1342 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001343 }
Christopher Tate7060b042014-06-09 19:50:00 -07001344
Dianne Hackborn6d068262017-05-16 13:14:37 -07001345 private void stopNonReadyActiveJobsLocked() {
1346 for (int i=0; i<mActiveServices.size(); i++) {
1347 JobServiceContext serviceContext = mActiveServices.get(i);
1348 final JobStatus running = serviceContext.getRunningJobLocked();
1349 if (running != null && !running.isReady()) {
1350 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001351 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1352 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001353 }
1354 }
1355 }
1356
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001357 /**
1358 * Run through list of jobs and execute all possible - at least one is expired so we do
1359 * as many as we can.
1360 */
1361 private void queueReadyJobsForExecutionLocked() {
1362 if (DEBUG) {
1363 Slog.d(TAG, "queuing all ready jobs for execution:");
1364 }
1365 noteJobsNonpending(mPendingJobs);
1366 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001367 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001368 mJobs.forEachJob(mReadyQueueFunctor);
1369 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001370
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001371 if (DEBUG) {
1372 final int queuedJobs = mPendingJobs.size();
1373 if (queuedJobs == 0) {
1374 Slog.d(TAG, "No jobs pending.");
1375 } else {
1376 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001377 }
1378 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001379 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001380
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001381 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1382 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001383
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001384 @Override
1385 public void process(JobStatus job) {
1386 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001387 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001388 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001389 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001390 if (newReadyJobs == null) {
1391 newReadyJobs = new ArrayList<JobStatus>();
1392 }
1393 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001394 }
1395 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001396
1397 public void postProcess() {
1398 if (newReadyJobs != null) {
1399 noteJobsPending(newReadyJobs);
1400 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001401 if (mPendingJobs.size() > 1) {
1402 mPendingJobs.sort(mEnqueueTimeComparator);
1403 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001404 }
1405 newReadyJobs = null;
1406 }
1407 }
1408 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1409
1410 /**
1411 * The state of at least one job has changed. Here is where we could enforce various
1412 * policies on when we want to execute jobs.
1413 * Right now the policy is such:
1414 * If >1 of the ready jobs is idle mode we send all of them off
1415 * if more than 2 network connectivity jobs are ready we send them all off.
1416 * If more than 4 jobs total are ready we send them all off.
1417 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1418 */
1419 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1420 int chargingCount;
1421 int batteryNotLowCount;
1422 int storageNotLowCount;
1423 int idleCount;
1424 int backoffCount;
1425 int connectivityCount;
1426 int contentCount;
1427 List<JobStatus> runnableJobs;
1428
1429 public MaybeReadyJobQueueFunctor() {
1430 reset();
1431 }
1432
1433 // Functor method invoked for each job via JobStore.forEachJob()
1434 @Override
1435 public void process(JobStatus job) {
1436 if (isReadyToBeExecutedLocked(job)) {
1437 try {
1438 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1439 job.getJob().getService().getPackageName())) {
1440 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1441 + job.getJob().toString() + " -- package not allowed to start");
1442 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1443 return;
1444 }
1445 } catch (RemoteException e) {
1446 }
1447 if (job.getNumFailures() > 0) {
1448 backoffCount++;
1449 }
1450 if (job.hasIdleConstraint()) {
1451 idleCount++;
1452 }
1453 if (job.hasConnectivityConstraint()) {
1454 connectivityCount++;
1455 }
1456 if (job.hasChargingConstraint()) {
1457 chargingCount++;
1458 }
1459 if (job.hasBatteryNotLowConstraint()) {
1460 batteryNotLowCount++;
1461 }
1462 if (job.hasStorageNotLowConstraint()) {
1463 storageNotLowCount++;
1464 }
1465 if (job.hasContentTriggerConstraint()) {
1466 contentCount++;
1467 }
1468 if (runnableJobs == null) {
1469 runnableJobs = new ArrayList<>();
1470 }
1471 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001472 }
1473 }
1474
1475 public void postProcess() {
1476 if (backoffCount > 0 ||
1477 idleCount >= mConstants.MIN_IDLE_COUNT ||
1478 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1479 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1480 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1481 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1482 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1483 (runnableJobs != null
1484 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1485 if (DEBUG) {
1486 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1487 }
1488 noteJobsPending(runnableJobs);
1489 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001490 if (mPendingJobs.size() > 1) {
1491 mPendingJobs.sort(mEnqueueTimeComparator);
1492 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001493 } else {
1494 if (DEBUG) {
1495 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1496 }
1497 }
1498
1499 // Be ready for next time
1500 reset();
1501 }
1502
1503 private void reset() {
1504 chargingCount = 0;
1505 idleCount = 0;
1506 backoffCount = 0;
1507 connectivityCount = 0;
1508 batteryNotLowCount = 0;
1509 storageNotLowCount = 0;
1510 contentCount = 0;
1511 runnableJobs = null;
1512 }
1513 }
1514 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1515
1516 private void maybeQueueReadyJobsForExecutionLocked() {
1517 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1518
1519 noteJobsNonpending(mPendingJobs);
1520 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001521 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001522 mJobs.forEachJob(mMaybeQueueFunctor);
1523 mMaybeQueueFunctor.postProcess();
1524 }
1525
1526 /**
1527 * Criteria for moving a job into the pending queue:
1528 * - It's ready.
1529 * - It's not pending.
1530 * - It's not already running on a JSC.
1531 * - The user that requested the job is running.
1532 * - The component is enabled and runnable.
1533 */
1534 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001535 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001536
1537 if (DEBUG) {
1538 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1539 + " ready=" + jobReady);
1540 }
1541
1542 // This is a condition that is very likely to be false (most jobs that are
1543 // scheduled are sitting there, not ready yet) and very cheap to check (just
1544 // a few conditions on data in JobStatus).
1545 if (!jobReady) {
1546 return false;
1547 }
1548
1549 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001550
1551 final int userId = job.getUserId();
1552 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1553
1554 if (DEBUG) {
1555 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001556 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001557 }
1558
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001559 // These are also fairly cheap to check, though they typically will not
1560 // be conditions we fail.
1561 if (!jobExists || !userStarted) {
1562 return false;
1563 }
1564
1565 final boolean jobPending = mPendingJobs.contains(job);
1566 final boolean jobActive = isCurrentlyActiveLocked(job);
1567
1568 if (DEBUG) {
1569 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1570 + " pending=" + jobPending + " active=" + jobActive);
1571 }
1572
1573 // These can be a little more expensive (especially jobActive, since we need to
1574 // go through the array of all potentially active jobs), so we are doing them
1575 // later... but still before checking with the package manager!
1576 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001577 return false;
1578 }
1579
1580 final boolean componentPresent;
1581 try {
1582 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1583 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1584 userId) != null);
1585 } catch (RemoteException e) {
1586 throw e.rethrowAsRuntimeException();
1587 }
1588
1589 if (DEBUG) {
1590 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1591 + " componentPresent=" + componentPresent);
1592 }
1593
1594 // Everything else checked out so far, so this is the final yes/no check
1595 return componentPresent;
1596 }
1597
1598 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001599 * Reconcile jobs in the pending queue against available execution contexts.
1600 * A controller can force a job into the pending queue even if it's already running, but
1601 * here is where we decide whether to actually execute it.
1602 */
1603 private void maybeRunPendingJobsLocked() {
1604 if (DEBUG) {
1605 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1606 }
1607 assignJobsToContextsLocked();
1608 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001609 }
1610
Dianne Hackborn807de782016-04-07 17:54:41 -07001611 private int adjustJobPriority(int curPriority, JobStatus job) {
1612 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1613 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001614 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001615 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001616 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001617 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1618 }
1619 }
1620 return curPriority;
1621 }
1622
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001623 private int evaluateJobPriorityLocked(JobStatus job) {
1624 int priority = job.getPriority();
1625 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001626 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001627 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001628 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1629 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001630 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001631 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001632 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001633 }
1634
Christopher Tate7060b042014-06-09 19:50:00 -07001635 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001636 * Takes jobs from pending queue and runs them on available contexts.
1637 * If no contexts are available, preempts lower priority jobs to
1638 * run higher priority ones.
1639 * Lock on mJobs before calling this function.
1640 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001641 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001642 if (DEBUG) {
1643 Slog.d(TAG, printPendingQueue());
1644 }
1645
Dianne Hackborn970510b2016-02-24 16:56:42 -08001646 int memLevel;
1647 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001648 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001649 } catch (RemoteException e) {
1650 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1651 }
1652 switch (memLevel) {
1653 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001654 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001655 break;
1656 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001657 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001658 break;
1659 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001660 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001661 break;
1662 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001663 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001664 break;
1665 }
1666
1667 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1668 boolean[] act = mTmpAssignAct;
1669 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1670 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001671 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001672 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1673 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001674 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001675 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001676 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001677 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1678 numForeground++;
1679 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001680 }
1681 act[i] = false;
1682 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001683 }
1684 if (DEBUG) {
1685 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1686 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001687 for (int i=0; i<mPendingJobs.size(); i++) {
1688 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001689
1690 // If job is already running, go to next job.
1691 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1692 if (jobRunningContext != -1) {
1693 continue;
1694 }
1695
Dianne Hackborn970510b2016-02-24 16:56:42 -08001696 final int priority = evaluateJobPriorityLocked(nextPending);
1697 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001698
Shreyas Basarge5db09082016-01-07 13:38:29 +00001699 // Find a context for nextPending. The context should be available OR
1700 // it should have lowest priority among all running jobs
1701 // (sharing the same Uid as nextPending)
1702 int minPriority = Integer.MAX_VALUE;
1703 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001704 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1705 JobStatus job = contextIdToJobMap[j];
1706 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001707 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001708 if ((numActive < mMaxActiveJobs ||
1709 (priority >= JobInfo.PRIORITY_TOP_APP &&
1710 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001711 (preferredUid == nextPending.getUid() ||
1712 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1713 // This slot is free, and we haven't yet hit the limit on
1714 // concurrent jobs... we can just throw the job in to here.
1715 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001716 break;
1717 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001718 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001719 // the context has a preferred Uid or we have reached the limit on
1720 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001721 continue;
1722 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001723 if (job.getUid() != nextPending.getUid()) {
1724 continue;
1725 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001726 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001727 continue;
1728 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001729 if (minPriority > nextPending.lastEvaluatedPriority) {
1730 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001731 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001732 }
1733 }
1734 if (minPriorityContextId != -1) {
1735 contextIdToJobMap[minPriorityContextId] = nextPending;
1736 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001737 numActive++;
1738 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1739 numForeground++;
1740 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001741 }
1742 }
1743 if (DEBUG) {
1744 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1745 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001746 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001747 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001748 boolean preservePreferredUid = false;
1749 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001750 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001751 if (js != null) {
1752 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001753 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001754 }
1755 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001756 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001757 preservePreferredUid = true;
1758 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001759 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001760 if (DEBUG) {
1761 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001762 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001763 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001764 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001765 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001766 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001767 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1768 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001769 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001770 if (mPendingJobs.remove(pendingJob)) {
1771 mJobPackageTracker.noteNonpending(pendingJob);
1772 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001773 }
1774 }
1775 if (!preservePreferredUid) {
1776 mActiveServices.get(i).clearPreferredUid();
1777 }
1778 }
1779 }
1780
1781 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1782 for (int i=0; i<map.length; i++) {
1783 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1784 return i;
1785 }
1786 }
1787 return -1;
1788 }
1789
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001790 final class LocalService implements JobSchedulerInternal {
1791
1792 /**
1793 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1794 * jobs are always considered pending.
1795 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001796 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001797 public List<JobInfo> getSystemScheduledPendingJobs() {
1798 synchronized (mLock) {
1799 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1800 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1801 @Override
1802 public void process(JobStatus job) {
1803 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1804 pendingJobs.add(job.getJob());
1805 }
1806 }
1807 });
1808 return pendingJobs;
1809 }
1810 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001811
1812 @Override
1813 public void addBackingUpUid(int uid) {
1814 synchronized (mLock) {
1815 // No need to actually do anything here, since for a full backup the
1816 // activity manager will kill the process which will kill the job (and
1817 // cause it to restart, but now it can't run).
1818 mBackingUpUids.put(uid, uid);
1819 }
1820 }
1821
1822 @Override
1823 public void removeBackingUpUid(int uid) {
1824 synchronized (mLock) {
1825 mBackingUpUids.delete(uid);
1826 // If there are any jobs for this uid, we need to rebuild the pending list
1827 // in case they are now ready to run.
1828 if (mJobs.countJobsForUid(uid) > 0) {
1829 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1830 }
1831 }
1832 }
1833
1834 @Override
1835 public void clearAllBackingUpUids() {
1836 synchronized (mLock) {
1837 if (mBackingUpUids.size() > 0) {
1838 mBackingUpUids.clear();
1839 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1840 }
1841 }
1842 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07001843
1844 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07001845 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07001846 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07001847 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07001848 }
1849 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001850 }
1851
Shreyas Basarge5db09082016-01-07 13:38:29 +00001852 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001853 * Binder stub trampoline implementation
1854 */
1855 final class JobSchedulerStub extends IJobScheduler.Stub {
1856 /** Cache determination of whether a given app can persist jobs
1857 * key is uid of the calling app; value is undetermined/true/false
1858 */
1859 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1860
1861 // Enforce that only the app itself (or shared uid participant) can schedule a
1862 // job that runs one of the app's services, as well as verifying that the
1863 // named service properly requires the BIND_JOB_SERVICE permission
1864 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001865 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001866 final ComponentName service = job.getService();
1867 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001868 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001869 PackageManager.MATCH_DIRECT_BOOT_AWARE
1870 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001871 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001872 if (si == null) {
1873 throw new IllegalArgumentException("No such service " + service);
1874 }
Christopher Tate7060b042014-06-09 19:50:00 -07001875 if (si.applicationInfo.uid != uid) {
1876 throw new IllegalArgumentException("uid " + uid +
1877 " cannot schedule job in " + service.getPackageName());
1878 }
1879 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1880 throw new IllegalArgumentException("Scheduled service " + service
1881 + " does not require android.permission.BIND_JOB_SERVICE permission");
1882 }
Christopher Tate5568f542014-06-18 13:53:31 -07001883 } catch (RemoteException e) {
1884 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001885 }
1886 }
1887
1888 private boolean canPersistJobs(int pid, int uid) {
1889 // If we get this far we're good to go; all we need to do now is check
1890 // whether the app is allowed to persist its scheduled work.
1891 final boolean canPersist;
1892 synchronized (mPersistCache) {
1893 Boolean cached = mPersistCache.get(uid);
1894 if (cached != null) {
1895 canPersist = cached.booleanValue();
1896 } else {
1897 // Persisting jobs is tantamount to running at boot, so we permit
1898 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1899 // permission
1900 int result = getContext().checkPermission(
1901 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1902 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1903 mPersistCache.put(uid, canPersist);
1904 }
1905 }
1906 return canPersist;
1907 }
1908
1909 // IJobScheduler implementation
1910 @Override
1911 public int schedule(JobInfo job) throws RemoteException {
1912 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001913 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001914 }
1915 final int pid = Binder.getCallingPid();
1916 final int uid = Binder.getCallingUid();
1917
1918 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001919 if (job.isPersisted()) {
1920 if (!canPersistJobs(pid, uid)) {
1921 throw new IllegalArgumentException("Error: requested job be persisted without"
1922 + " holding RECEIVE_BOOT_COMPLETED permission.");
1923 }
1924 }
Christopher Tate7060b042014-06-09 19:50:00 -07001925
Jeff Sharkey785f4942016-07-14 10:31:15 -06001926 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1927 getContext().enforceCallingOrSelfPermission(
1928 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1929 }
1930
Christopher Tate7060b042014-06-09 19:50:00 -07001931 long ident = Binder.clearCallingIdentity();
1932 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001933 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, -1, null);
1934 } finally {
1935 Binder.restoreCallingIdentity(ident);
1936 }
1937 }
1938
1939 // IJobScheduler implementation
1940 @Override
1941 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
1942 if (DEBUG) {
1943 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
1944 }
1945 final int pid = Binder.getCallingPid();
1946 final int uid = Binder.getCallingUid();
1947
1948 enforceValidJobRequest(uid, job);
1949 if (job.isPersisted()) {
1950 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
1951 }
1952 if (work == null) {
1953 throw new NullPointerException("work is null");
1954 }
1955
1956 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1957 getContext().enforceCallingOrSelfPermission(
1958 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1959 }
1960
1961 long ident = Binder.clearCallingIdentity();
1962 try {
1963 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, -1, null);
Christopher Tate7060b042014-06-09 19:50:00 -07001964 } finally {
1965 Binder.restoreCallingIdentity(ident);
1966 }
1967 }
1968
1969 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001970 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001971 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001972 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001973 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001974 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1975 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001976 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001977
1978 if (packageName == null) {
1979 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001980 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001981
1982 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1983 android.Manifest.permission.UPDATE_DEVICE_STATS);
1984 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1985 throw new SecurityException("Caller uid " + callerUid
1986 + " not permitted to schedule jobs for other apps");
1987 }
1988
Jeff Sharkey4f100402016-05-03 17:44:23 -06001989 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1990 getContext().enforceCallingOrSelfPermission(
1991 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1992 }
1993
Shreyas Basarge968ac752016-01-11 23:09:26 +00001994 long ident = Binder.clearCallingIdentity();
1995 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001996 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001997 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001998 } finally {
1999 Binder.restoreCallingIdentity(ident);
2000 }
2001 }
2002
2003 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002004 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2005 final int uid = Binder.getCallingUid();
2006
2007 long ident = Binder.clearCallingIdentity();
2008 try {
2009 return JobSchedulerService.this.getPendingJobs(uid);
2010 } finally {
2011 Binder.restoreCallingIdentity(ident);
2012 }
2013 }
2014
2015 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002016 public JobInfo getPendingJob(int jobId) throws RemoteException {
2017 final int uid = Binder.getCallingUid();
2018
2019 long ident = Binder.clearCallingIdentity();
2020 try {
2021 return JobSchedulerService.this.getPendingJob(uid, jobId);
2022 } finally {
2023 Binder.restoreCallingIdentity(ident);
2024 }
2025 }
2026
2027 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002028 public void cancelAll() throws RemoteException {
2029 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002030 long ident = Binder.clearCallingIdentity();
2031 try {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002032 JobSchedulerService.this.cancelJobsForUid(uid, "cancelAll() called by app");
Christopher Tate7060b042014-06-09 19:50:00 -07002033 } finally {
2034 Binder.restoreCallingIdentity(ident);
2035 }
2036 }
2037
2038 @Override
2039 public void cancel(int jobId) throws RemoteException {
2040 final int uid = Binder.getCallingUid();
2041
2042 long ident = Binder.clearCallingIdentity();
2043 try {
2044 JobSchedulerService.this.cancelJob(uid, jobId);
2045 } finally {
2046 Binder.restoreCallingIdentity(ident);
2047 }
2048 }
2049
2050 /**
2051 * "dumpsys" infrastructure
2052 */
2053 @Override
2054 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002055 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002056
2057 long identityToken = Binder.clearCallingIdentity();
2058 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002059 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07002060 } finally {
2061 Binder.restoreCallingIdentity(identityToken);
2062 }
2063 }
Christopher Tate5d346052016-03-08 12:56:08 -08002064
2065 @Override
2066 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002067 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002068 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002069 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002070 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002071 };
2072
Christopher Tate5d346052016-03-08 12:56:08 -08002073 // Shell command infrastructure: run the given job immediately
2074 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2075 if (DEBUG) {
2076 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2077 + " " + jobId + " f=" + force);
2078 }
2079
2080 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002081 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2082 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002083 if (uid < 0) {
2084 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2085 }
2086
2087 synchronized (mLock) {
2088 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2089 if (js == null) {
2090 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2091 }
2092
2093 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2094 if (!js.isConstraintsSatisfied()) {
2095 js.overrideState = 0;
2096 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2097 }
2098
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002099 queueReadyJobsForExecutionLocked();
2100 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002101 }
2102 } catch (RemoteException e) {
2103 // can't happen
2104 }
2105 return 0;
2106 }
2107
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002108 // Shell command infrastructure: immediately timeout currently executing jobs
2109 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2110 boolean hasJobId, int jobId) {
2111 if (DEBUG) {
2112 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2113 }
2114
2115 synchronized (mLock) {
2116 boolean foundSome = false;
2117 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002118 final JobServiceContext jc = mActiveServices.get(i);
2119 final JobStatus js = jc.getRunningJobLocked();
2120 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId)) {
2121 foundSome = true;
2122 pw.print("Timing out: ");
2123 js.printUniqueId(pw);
2124 pw.print(" ");
2125 pw.println(js.getServiceComponent().flattenToShortString());
2126 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002127 }
2128 if (!foundSome) {
2129 pw.println("No matching executing jobs found.");
2130 }
2131 }
2132 return 0;
2133 }
2134
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002135 void setMonitorBattery(boolean enabled) {
2136 synchronized (mLock) {
2137 if (mBatteryController != null) {
2138 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2139 }
2140 }
2141 }
2142
2143 int getBatterySeq() {
2144 synchronized (mLock) {
2145 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2146 }
2147 }
2148
2149 boolean getBatteryCharging() {
2150 synchronized (mLock) {
2151 return mBatteryController != null
2152 ? mBatteryController.getTracker().isOnStablePower() : false;
2153 }
2154 }
2155
2156 boolean getBatteryNotLow() {
2157 synchronized (mLock) {
2158 return mBatteryController != null
2159 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2160 }
2161 }
2162
Dianne Hackborn532ea262017-03-17 17:50:55 -07002163 int getStorageSeq() {
2164 synchronized (mLock) {
2165 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2166 }
2167 }
2168
2169 boolean getStorageNotLow() {
2170 synchronized (mLock) {
2171 return mStorageController != null
2172 ? mStorageController.getTracker().isStorageNotLow() : false;
2173 }
2174 }
2175
Dianne Hackborn6d068262017-05-16 13:14:37 -07002176 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2177 try {
2178 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2179 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2180 if (uid < 0) {
2181 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2182 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2183 }
2184
2185 synchronized (mLock) {
2186 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2187 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2188 if (js == null) {
2189 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2190 pw.print("/jid"); pw.print(jobId); pw.println(")");
2191 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2192 }
2193
2194 boolean printed = false;
2195 if (mPendingJobs.contains(js)) {
2196 pw.print("pending");
2197 printed = true;
2198 }
2199 if (isCurrentlyActiveLocked(js)) {
2200 if (printed) {
2201 pw.print(" ");
2202 }
2203 printed = true;
2204 pw.println("active");
2205 }
2206 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2207 if (printed) {
2208 pw.print(" ");
2209 }
2210 printed = true;
2211 pw.println("user-stopped");
2212 }
2213 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2214 if (printed) {
2215 pw.print(" ");
2216 }
2217 printed = true;
2218 pw.println("backing-up");
2219 }
2220 boolean componentPresent = false;
2221 try {
2222 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2223 js.getServiceComponent(),
2224 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2225 js.getUserId()) != null);
2226 } catch (RemoteException e) {
2227 }
2228 if (!componentPresent) {
2229 if (printed) {
2230 pw.print(" ");
2231 }
2232 printed = true;
2233 pw.println("no-component");
2234 }
2235 if (js.isReady()) {
2236 if (printed) {
2237 pw.print(" ");
2238 }
2239 printed = true;
2240 pw.println("ready");
2241 }
2242 if (!printed) {
2243 pw.print("waiting");
2244 }
2245 pw.println();
2246 }
2247 } catch (RemoteException e) {
2248 // can't happen
2249 }
2250 return 0;
2251 }
2252
Shreyas Basarge5db09082016-01-07 13:38:29 +00002253 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2254 StringBuilder s = new StringBuilder(initial + ": ");
2255 for (int i=0; i<map.length; i++) {
2256 s.append("(")
2257 .append(map[i] == null? -1: map[i].getJobId())
2258 .append(map[i] == null? -1: map[i].getUid())
2259 .append(")" );
2260 }
2261 return s.toString();
2262 }
2263
2264 private String printPendingQueue() {
2265 StringBuilder s = new StringBuilder("Pending queue: ");
2266 Iterator<JobStatus> it = mPendingJobs.iterator();
2267 while (it.hasNext()) {
2268 JobStatus js = it.next();
2269 s.append("(")
2270 .append(js.getJob().getId())
2271 .append(", ")
2272 .append(js.getUid())
2273 .append(") ");
2274 }
2275 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002276 }
Christopher Tate7060b042014-06-09 19:50:00 -07002277
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002278 static void dumpHelp(PrintWriter pw) {
2279 pw.println("Job Scheduler (jobscheduler) dump options:");
2280 pw.println(" [-h] [package] ...");
2281 pw.println(" -h: print this help");
2282 pw.println(" [package] is an optional package name to limit the output to.");
2283 }
2284
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002285 void dumpInternal(final PrintWriter pw, String[] args) {
2286 int filterUid = -1;
2287 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002288 int opti = 0;
2289 while (opti < args.length) {
2290 String arg = args[opti];
2291 if ("-h".equals(arg)) {
2292 dumpHelp(pw);
2293 return;
2294 } else if ("-a".equals(arg)) {
2295 // Ignore, we always dump all.
2296 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2297 pw.println("Unknown option: " + arg);
2298 return;
2299 } else {
2300 break;
2301 }
2302 opti++;
2303 }
2304 if (opti < args.length) {
2305 String pkg = args[opti];
2306 try {
2307 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002308 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002309 } catch (NameNotFoundException ignored) {
2310 pw.println("Invalid package: " + pkg);
2311 return;
2312 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002313 }
2314 }
2315
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002316 final int filterUidFinal = UserHandle.getAppId(filterUid);
Dianne Hackborn6d068262017-05-16 13:14:37 -07002317 final long nowElapsed = SystemClock.elapsedRealtime();
2318 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002319 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002320 mConstants.dump(pw);
2321 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002322 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002323 pw.print("Registered ");
2324 pw.print(mJobs.size());
2325 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002326 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002327 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2328 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002329 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002330 public int compare(JobStatus o1, JobStatus o2) {
2331 int uid1 = o1.getUid();
2332 int uid2 = o2.getUid();
2333 int id1 = o1.getJobId();
2334 int id2 = o2.getJobId();
2335 if (uid1 != uid2) {
2336 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002337 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002338 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08002339 }
2340 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002341 for (JobStatus job : jobs) {
2342 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2343 pw.println(job.toShortStringExceptUniqueId());
2344
2345 // Skip printing details if the caller requested a filter
2346 if (!job.shouldDump(filterUidFinal)) {
2347 continue;
2348 }
2349
Dianne Hackborn6d068262017-05-16 13:14:37 -07002350 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002351 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002352 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002353 pw.print(" (job=");
2354 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002355 pw.print(" user=");
2356 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002357 pw.print(" !pending=");
2358 pw.print(!mPendingJobs.contains(job));
2359 pw.print(" !active=");
2360 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002361 pw.print(" !backingup=");
2362 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002363 pw.print(" comp=");
2364 boolean componentPresent = false;
2365 try {
2366 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2367 job.getServiceComponent(),
2368 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2369 job.getUserId()) != null);
2370 } catch (RemoteException e) {
2371 }
2372 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002373 pw.println(")");
2374 }
Christopher Tate7060b042014-06-09 19:50:00 -07002375 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002376 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002377 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002378 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002379 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002380 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002381 }
2382 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002383 pw.println("Uid priority overrides:");
2384 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002385 int uid = mUidPriorityOverride.keyAt(i);
2386 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2387 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2388 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2389 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002390 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002391 if (mBackingUpUids.size() > 0) {
2392 pw.println();
2393 pw.println("Backing up uids:");
2394 boolean first = true;
2395 for (int i = 0; i < mBackingUpUids.size(); i++) {
2396 int uid = mBackingUpUids.keyAt(i);
2397 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2398 if (first) {
2399 pw.print(" ");
2400 first = false;
2401 } else {
2402 pw.print(", ");
2403 }
2404 pw.print(UserHandle.formatUid(uid));
2405 }
2406 }
2407 pw.println();
2408 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002409 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002410 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002411 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002412 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2413 pw.println();
2414 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002415 pw.println("Pending queue:");
2416 for (int i=0; i<mPendingJobs.size(); i++) {
2417 JobStatus job = mPendingJobs.get(i);
2418 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2419 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002420 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002421 int priority = evaluateJobPriorityLocked(job);
2422 if (priority != JobInfo.PRIORITY_DEFAULT) {
2423 pw.print(" Evaluated priority: "); pw.println(priority);
2424 }
2425 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002426 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002427 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002428 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002429 }
Christopher Tate7060b042014-06-09 19:50:00 -07002430 pw.println();
2431 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002432 for (int i=0; i<mActiveServices.size(); i++) {
2433 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002434 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002435 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002436 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002437 if (jsc.mStoppedReason != null) {
2438 pw.print("inactive since ");
2439 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2440 pw.print(", stopped because: ");
2441 pw.println(jsc.mStoppedReason);
2442 } else {
2443 pw.println("inactive");
2444 }
Christopher Tate7060b042014-06-09 19:50:00 -07002445 continue;
2446 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002447 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002448 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002449 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002450 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002451 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002452 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002453 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002454 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002455 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002456 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002457 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002458 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002459 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002460 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002461 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2462 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002463 }
2464 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002465 if (filterUid == -1) {
2466 pw.println();
2467 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2468 pw.print("mReportedActive="); pw.println(mReportedActive);
2469 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2470 }
Makoto Onukie7b02982017-08-24 14:23:36 -07002471 pw.println();
2472 pw.print("PersistStats: ");
2473 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07002474 }
2475 pw.println();
2476 }
2477}