blob: 98d49d43ea8cffbf8e2b37d6368a359207a3013e [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;
79import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080080import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080081import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070082import com.android.server.job.controllers.BackgroundJobsController;
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;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700143 /** Need directly for sending uid state changes */
144 private BackgroundJobsController mBackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700145 /**
146 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
147 * when ready to execute them.
148 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700149 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700150
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700151 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700152
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700153 final JobHandler mHandler;
154 final JobSchedulerStub mJobSchedulerStub;
155
156 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700157 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800158 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700159
160 /**
161 * Set to true once we are allowed to run third party apps.
162 */
163 boolean mReadyToRock;
164
Christopher Tate7060b042014-06-09 19:50:00 -0700165 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800166 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800167 */
168 boolean mReportedActive;
169
170 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800171 * Current limit on the number of concurrent JobServiceContext entries we want to
172 * keep actively running a job.
173 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700174 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800175
176 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800177 * Which uids are currently in the foreground.
178 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800179 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
180
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700181 /**
182 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
183 */
184 final SparseIntArray mBackingUpUids = new SparseIntArray();
185
Dianne Hackborn970510b2016-02-24 16:56:42 -0800186 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
187
188 /**
189 * This array essentially stores the state of mActiveServices array.
190 * The ith index stores the job present on the ith JobServiceContext.
191 * We manipulate this array until we arrive at what jobs should be running on
192 * what JobServiceContext.
193 */
194 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
195 /**
196 * Indicates whether we need to act on this jobContext id
197 */
198 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
199 /**
200 * The uid whose jobs we would like to assign to a context.
201 */
202 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800203
204 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700205 * All times are in milliseconds. These constants are kept synchronized with the system
206 * global Settings. Any access to this class or its fields should be done while
207 * holding the JobSchedulerService.mLock lock.
208 */
209 private final class Constants extends ContentObserver {
210 // Key names stored in the settings value.
211 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
212 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800213 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700214 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700215 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
216 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
217 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
218 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
219 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
220 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
221 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
222 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
223 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
224 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700225 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
226 = "max_standard_reschedule_count";
227 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
228 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
229 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700230 private static final String KEY_BG_JOBS_RESTRICTED = "bg_jobs_restricted";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700231
232 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
233 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800234 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700235 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700236 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
237 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
238 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
239 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
240 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
241 private static final int DEFAULT_FG_JOB_COUNT = 4;
242 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
243 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700244 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700245 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700246 private static final boolean DEFAULT_BG_JOBS_RESTRICTED = false;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700247 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
248 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
249 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
250 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700251
252 /**
253 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
254 * early.
255 */
256 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
257 /**
258 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
259 * things early.
260 */
261 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
262 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800263 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
264 * schedule things early.
265 */
266 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
267 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700268 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
269 * schedule things early.
270 */
271 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
272 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700273 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
274 * things early. 1 == Run connectivity jobs as soon as ready.
275 */
276 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
277 /**
278 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
279 * schedule things early.
280 */
281 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
282 /**
283 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
284 * running some work early. This (and thus the other min counts) is now set to 1, to
285 * prevent any batching at this level. Since we now do batching through doze, that is
286 * a much better mechanism.
287 */
288 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
289 /**
290 * This is the job execution factor that is considered to be heavy use of the system.
291 */
292 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
293 /**
294 * This is the job execution factor that is considered to be moderate use of the system.
295 */
296 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
297 /**
298 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
299 */
300 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
301 /**
302 * The maximum number of background jobs we allow when the system is in a normal
303 * memory state.
304 */
305 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
306 /**
307 * The maximum number of background jobs we allow when the system is in a moderate
308 * memory state.
309 */
310 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
311 /**
312 * The maximum number of background jobs we allow when the system is in a low
313 * memory state.
314 */
315 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
316 /**
317 * The maximum number of background jobs we allow when the system is in a critical
318 * memory state.
319 */
320 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700321 /**
322 * The maximum number of times we allow a job to have itself rescheduled before
323 * giving up on it, for standard jobs.
324 */
325 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
326 /**
327 * The maximum number of times we allow a job to have itself rescheduled before
328 * giving up on it, for jobs that are executing work.
329 */
330 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
331 /**
332 * The minimum backoff time to allow for linear backoff.
333 */
334 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
335 /**
336 * The minimum backoff time to allow for exponential backoff.
337 */
338 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700339
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700340 /**
341 * Runtime switch for throttling background jobs
342 */
343 boolean BACKGROUND_JOBS_RESTRICTED = DEFAULT_BG_JOBS_RESTRICTED;
344
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700345 private ContentResolver mResolver;
346 private final KeyValueListParser mParser = new KeyValueListParser(',');
347
348 public Constants(Handler handler) {
349 super(handler);
350 }
351
352 public void start(ContentResolver resolver) {
353 mResolver = resolver;
354 mResolver.registerContentObserver(Settings.Global.getUriFor(
355 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
356 updateConstants();
357 }
358
359 @Override
360 public void onChange(boolean selfChange, Uri uri) {
361 updateConstants();
362 }
363
364 private void updateConstants() {
365 synchronized (mLock) {
366 try {
367 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000368 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700369 } catch (IllegalArgumentException e) {
370 // Failed to parse the settings string, log this and move on
371 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000372 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700373 }
374
375 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
376 DEFAULT_MIN_IDLE_COUNT);
377 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
378 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800379 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
380 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700381 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
382 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700383 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
384 DEFAULT_MIN_CONNECTIVITY_COUNT);
385 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
386 DEFAULT_MIN_CONTENT_COUNT);
387 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
388 DEFAULT_MIN_READY_JOBS_COUNT);
389 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
390 DEFAULT_HEAVY_USE_FACTOR);
391 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
392 DEFAULT_MODERATE_USE_FACTOR);
393 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
394 DEFAULT_FG_JOB_COUNT);
395 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
396 DEFAULT_BG_NORMAL_JOB_COUNT);
397 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
398 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
399 }
400 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
401 DEFAULT_BG_MODERATE_JOB_COUNT);
402 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
403 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
404 }
405 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
406 DEFAULT_BG_LOW_JOB_COUNT);
407 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
408 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
409 }
410 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
411 DEFAULT_BG_CRITICAL_JOB_COUNT);
412 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
413 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
414 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700415 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
416 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
417 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
418 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
419 MIN_LINEAR_BACKOFF_TIME = mParser.getLong(KEY_MIN_LINEAR_BACKOFF_TIME,
420 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
421 MIN_EXP_BACKOFF_TIME = mParser.getLong(KEY_MIN_EXP_BACKOFF_TIME,
422 DEFAULT_MIN_EXP_BACKOFF_TIME);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700423 final boolean bgJobsRestricted = mParser.getBoolean(KEY_BG_JOBS_RESTRICTED,
424 DEFAULT_BG_JOBS_RESTRICTED);
425 if (bgJobsRestricted != BACKGROUND_JOBS_RESTRICTED) {
426 mBackgroundJobsController.enableRestrictionsLocked(
427 BACKGROUND_JOBS_RESTRICTED = bgJobsRestricted);
428 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700429 }
430 }
431
432 void dump(PrintWriter pw) {
433 pw.println(" Settings:");
434
435 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
436 pw.print(MIN_IDLE_COUNT); pw.println();
437
438 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
439 pw.print(MIN_CHARGING_COUNT); pw.println();
440
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800441 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
442 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
443
Dianne Hackborn532ea262017-03-17 17:50:55 -0700444 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
445 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
446
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700447 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
448 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
449
450 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
451 pw.print(MIN_CONTENT_COUNT); pw.println();
452
453 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
454 pw.print(MIN_READY_JOBS_COUNT); pw.println();
455
456 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
457 pw.print(HEAVY_USE_FACTOR); pw.println();
458
459 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
460 pw.print(MODERATE_USE_FACTOR); pw.println();
461
462 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
463 pw.print(FG_JOB_COUNT); pw.println();
464
465 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
466 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
467
468 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
469 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
470
471 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
472 pw.print(BG_LOW_JOB_COUNT); pw.println();
473
474 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
475 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700476
477 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
478 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
479
480 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
481 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
482
483 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
484 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
485
486 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
487 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700488
489 pw.print(" "); pw.print(KEY_BG_JOBS_RESTRICTED); pw.print("=");
490 pw.print(BACKGROUND_JOBS_RESTRICTED); pw.println();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700491 }
492 }
493
494 final Constants mConstants;
495
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700496 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
497 if (o1.enqueueTime < o2.enqueueTime) {
498 return -1;
499 }
500 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
501 };
502
503 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
504 int where = Collections.binarySearch(array, newItem, comparator);
505 if (where < 0) {
506 where = ~where;
507 }
508 array.add(where, newItem);
509 }
510
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700511 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700512 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
513 * still clean up. On reinstall the package will have a new uid.
514 */
515 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
516 @Override
517 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700518 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700519 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700520 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700521 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700522 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700523 // Purge the app's jobs if the whole package was just disabled. When this is
524 // the case the component name will be a bare package name.
525 final String pkgName = getPackageName(intent);
526 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
527 if (pkgName != null && pkgUid != -1) {
528 final String[] changedComponents = intent.getStringArrayExtra(
529 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
530 if (changedComponents != null) {
531 for (String component : changedComponents) {
532 if (component.equals(pkgName)) {
533 if (DEBUG) {
534 Slog.d(TAG, "Package state change: " + pkgName);
535 }
536 try {
537 final int userId = UserHandle.getUserId(pkgUid);
538 IPackageManager pm = AppGlobals.getPackageManager();
539 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
540 if (state == COMPONENT_ENABLED_STATE_DISABLED
541 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
542 if (DEBUG) {
543 Slog.d(TAG, "Removing jobs for package " + pkgName
544 + " in user " + userId);
545 }
Dianne Hackborn729a3282017-06-09 16:06:01 -0700546 cancelJobsForUid(pkgUid, "app package state changed");
Christopher Tateb5c07882016-05-26 17:11:09 -0700547 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700548 } catch (RemoteException|IllegalArgumentException e) {
549 /*
550 * IllegalArgumentException means that the package doesn't exist.
551 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
552 * behind outright uninstall, so by the time we try to act it's gone.
553 * We don't need to act on this PACKAGE_CHANGED when this happens;
554 * we'll get a PACKAGE_REMOVED later and clean up then.
555 *
556 * RemoteException can't actually happen; the package manager is
557 * running in this same process.
558 */
559 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700560 break;
561 }
562 }
563 }
564 } else {
565 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
566 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700567 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700568 // If this is an outright uninstall rather than the first half of an
569 // app update sequence, cancel the jobs associated with the app.
570 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
571 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
572 if (DEBUG) {
573 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
574 }
Dianne Hackborn729a3282017-06-09 16:06:01 -0700575 cancelJobsForUid(uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700576 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700577 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700578 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
579 if (DEBUG) {
580 Slog.d(TAG, "Removing jobs for user: " + userId);
581 }
582 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700583 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
584 // Has this package scheduled any jobs, such that we will take action
585 // if it were to be force-stopped?
586 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
587 final String pkgName = intent.getData().getSchemeSpecificPart();
588 if (pkgUid != -1) {
589 List<JobStatus> jobsForUid;
590 synchronized (mLock) {
591 jobsForUid = mJobs.getJobsByUid(pkgUid);
592 }
593 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
594 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
595 if (DEBUG) {
596 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
597 + pkgUid + " has jobs");
598 }
599 setResultCode(Activity.RESULT_OK);
600 break;
601 }
602 }
603 }
604 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
605 // possible force-stop
606 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
607 final String pkgName = intent.getData().getSchemeSpecificPart();
608 if (pkgUid != -1) {
609 if (DEBUG) {
610 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
611 }
612 cancelJobsForPackageAndUid(pkgName, pkgUid);
613 }
Christopher Tate7060b042014-06-09 19:50:00 -0700614 }
615 }
616 };
617
Christopher Tateb5c07882016-05-26 17:11:09 -0700618 private String getPackageName(Intent intent) {
619 Uri uri = intent.getData();
620 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
621 return pkg;
622 }
623
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700624 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700625 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800626 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700627 }
628
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700629 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800630 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800631 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700632 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800633 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700634 synchronized (mLock) {
635 mBackgroundJobsController.setUidActiveLocked(uid, false);
636 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700637 }
638
639 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700640 synchronized (mLock) {
641 mBackgroundJobsController.setUidActiveLocked(uid, true);
642 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700643 }
644
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700645 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800646 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700647 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800648 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700649 synchronized (mLock) {
650 mBackgroundJobsController.setUidActiveLocked(uid, false);
651 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700652 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700653
654 @Override public void onUidCachedChanged(int uid, boolean cached) {
655 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700656 };
657
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800658 public Object getLock() {
659 return mLock;
660 }
661
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700662 public JobStore getJobStore() {
663 return mJobs;
664 }
665
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700666 @Override
667 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700668 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
669 // Let's kick any outstanding jobs for this user.
670 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
671 }
672
673 @Override
674 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700675 // Let's kick any outstanding jobs for this user.
676 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
677 }
678
679 @Override
680 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700681 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700682 }
683
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700684 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
685 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700686 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800687 if (ActivityManager.getService().isAppStartModeDisabled(uId,
688 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700689 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
690 + " -- package not allowed to start");
691 return JobScheduler.RESULT_FAILURE;
692 }
693 } catch (RemoteException e) {
694 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800695 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700696 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
697
698 if (work != null && toCancel != null) {
699 // Fast path: we are adding work to an existing job, and the JobInfo is not
700 // changing. We can just directly enqueue this work in to the job.
701 if (toCancel.getJob().equals(job)) {
Dianne Hackborn342e6032017-04-13 18:04:31 -0700702 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700703 return JobScheduler.RESULT_SUCCESS;
704 }
705 }
706
707 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
708 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800709 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800710 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800711 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
712 Slog.w(TAG, "Too many jobs for uid " + uId);
713 throw new IllegalStateException("Apps may not schedule more than "
714 + MAX_JOBS_PER_APP + " distinct jobs");
715 }
716 }
717
Dianne Hackborna47223f2017-03-30 13:49:13 -0700718 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700719 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700720
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700721 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700722 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700723 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700724 if (work != null) {
725 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700726 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700727 }
728 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700729
730 // If the job is immediately ready to run, then we can just immediately
731 // put it in the pending list and try to schedule it. This is especially
732 // important for jobs with a 0 deadline constraint, since they will happen a fair
733 // amount, we want to handle them as quickly as possible, and semantically we want to
734 // make sure we have started holding the wake lock for the job before returning to
735 // the caller.
736 // If the job is not yet ready to run, there is nothing more to do -- we are
737 // now just waiting for one of its controllers to change state and schedule
738 // the job appropriately.
739 if (isReadyToBeExecutedLocked(jobStatus)) {
740 // This is a new job, we can just immediately put it on the pending
741 // list and try to run it.
742 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700743 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700744 maybeRunPendingJobsLocked();
745 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800746 }
Christopher Tate7060b042014-06-09 19:50:00 -0700747 return JobScheduler.RESULT_SUCCESS;
748 }
749
750 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800751 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800752 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
753 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
754 for (int i = jobs.size() - 1; i >= 0; i--) {
755 JobStatus job = jobs.get(i);
756 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700757 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800758 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700759 }
Christopher Tate7060b042014-06-09 19:50:00 -0700760 }
761
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600762 public JobInfo getPendingJob(int uid, int jobId) {
763 synchronized (mLock) {
764 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
765 for (int i = jobs.size() - 1; i >= 0; i--) {
766 JobStatus job = jobs.get(i);
767 if (job.getJobId() == jobId) {
768 return job.getJob();
769 }
770 }
771 return null;
772 }
773 }
774
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700775 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800776 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700777 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
778 for (int i=0; i<jobsForUser.size(); i++) {
779 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700780 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700781 }
Christopher Tate7060b042014-06-09 19:50:00 -0700782 }
783 }
784
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700785 private void cancelJobsForNonExistentUsers() {
786 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
787 synchronized (mLock) {
788 mJobs.removeJobsOfNonUsers(umi.getUserIds());
789 }
790 }
791
Christopher Tateee7805b2016-07-15 16:56:56 -0700792 void cancelJobsForPackageAndUid(String pkgName, int uid) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700793 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700794 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
795 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
796 final JobStatus job = jobsForUid.get(i);
797 if (job.getSourcePackageName().equals(pkgName)) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700798 cancelJobImplLocked(job, null, "app force stopped");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700799 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700800 }
801 }
802 }
803
Christopher Tate7060b042014-06-09 19:50:00 -0700804 /**
805 * Entry point from client to cancel all jobs originating from their uid.
806 * This will remove the job from the master list, and cancel the job if it was staged for
807 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700808 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800809 *
Christopher Tate7060b042014-06-09 19:50:00 -0700810 */
Dianne Hackborn729a3282017-06-09 16:06:01 -0700811 public void cancelJobsForUid(int uid, String reason) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800812 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700813 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
814 for (int i=0; i<jobsForUid.size(); i++) {
815 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700816 cancelJobImplLocked(toRemove, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700817 }
Christopher Tate7060b042014-06-09 19:50:00 -0700818 }
819 }
820
821 /**
822 * Entry point from client to cancel the job corresponding to the jobId provided.
823 * This will remove the job from the master list, and cancel the job if it was staged for
824 * execution or being executed.
825 * @param uid Uid of the calling client.
826 * @param jobId Id of the job, provided at schedule-time.
827 */
828 public void cancelJob(int uid, int jobId) {
829 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800830 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700831 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700832 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700833 cancelJobImplLocked(toCancel, null, "cancel() called by app");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700834 }
Christopher Tate7060b042014-06-09 19:50:00 -0700835 }
836 }
837
Dianne Hackborn729a3282017-06-09 16:06:01 -0700838 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700839 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
840 cancelled.unprepareLocked(ActivityManager.getService());
841 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
842 // Remove from pending queue.
843 if (mPendingJobs.remove(cancelled)) {
844 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700845 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700846 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700847 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700848 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700849 }
850
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800851 void updateUidState(int uid, int procState) {
852 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800853 if (procState == ActivityManager.PROCESS_STATE_TOP) {
854 // Only use this if we are exactly the top app. All others can live
855 // with just the foreground priority. This means that persistent processes
856 // can never be the top app priority... that is fine.
857 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
858 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
859 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800860 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800861 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800862 }
863 }
864 }
865
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700866 @Override
867 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800868 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700869 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600870 // When becoming idle, make sure no jobs are actively running,
871 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700872 for (int i=0; i<mActiveServices.size(); i++) {
873 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700874 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600875 if (executing != null
876 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700877 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
878 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700879 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700880 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700881 } else {
882 // When coming out of idle, allow thing to start back up.
883 if (mReadyToRock) {
884 if (mLocalDeviceIdleController != null) {
885 if (!mReportedActive) {
886 mReportedActive = true;
887 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700888 }
889 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700890 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700891 }
892 }
893 }
894 }
895
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700896 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000897 // active is true if pending queue contains jobs OR some job is running.
898 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800899 if (mPendingJobs.size() <= 0) {
900 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700901 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700902 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700903 if (job != null
904 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
905 && !job.dozeWhitelisted) {
906 // We will report active if we have a job running and it is not an exception
907 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800908 active = true;
909 break;
910 }
911 }
912 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000913
914 if (mReportedActive != active) {
915 mReportedActive = active;
916 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800917 mLocalDeviceIdleController.setJobsActive(active);
918 }
919 }
920 }
921
Christopher Tate7060b042014-06-09 19:50:00 -0700922 /**
923 * Initializes the system service.
924 * <p>
925 * Subclasses must define a single argument constructor that accepts the context
926 * and passes it to super.
927 * </p>
928 *
929 * @param context The system server context.
930 */
931 public JobSchedulerService(Context context) {
932 super(context);
Dianne Hackborn970e3f42016-06-01 10:55:13 -0700933 mHandler = new JobHandler(context.getMainLooper());
934 mConstants = new Constants(mHandler);
935 mJobSchedulerStub = new JobSchedulerStub();
936 mJobs = JobStore.initAndGet(this);
937
Christopher Tate7060b042014-06-09 19:50:00 -0700938 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700939 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700940 mControllers.add(ConnectivityController.get(this));
941 mControllers.add(TimeController.get(this));
942 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800943 mBatteryController = BatteryController.get(this);
944 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700945 mStorageController = StorageController.get(this);
946 mControllers.add(mStorageController);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700947 mBackgroundJobsController = BackgroundJobsController.get(this);
948 mControllers.add(mBackgroundJobsController);
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800949 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800950 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700951 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700952 }
953
954 @Override
955 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000956 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -0700957 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
958 }
959
960 @Override
961 public void onBootPhase(int phase) {
962 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700963 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +0000964 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -0700965 final IntentFilter filter = new IntentFilter();
966 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
967 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -0700968 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
969 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -0700970 filter.addDataScheme("package");
971 getContext().registerReceiverAsUser(
972 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
973 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
974 getContext().registerReceiverAsUser(
975 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000976 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700977 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800978 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800979 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700980 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
981 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700982 } catch (RemoteException e) {
983 // ignored; both services live in system_server
984 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700985 // Remove any jobs that are not associated with any of the current users.
986 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700987 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800988 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700989 // Let's go!
990 mReadyToRock = true;
991 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
992 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800993 mLocalDeviceIdleController
994 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700995 // Create the "runners".
996 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
997 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -0700998 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700999 getContext().getMainLooper()));
1000 }
1001 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001002 mJobs.forEachJob(new JobStatusFunctor() {
1003 @Override
1004 public void process(JobStatus job) {
1005 for (int controller = 0; controller < mControllers.size(); controller++) {
1006 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001007 sc.maybeStartTrackingJobLocked(job, null);
1008 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001009 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001010 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001011 // GO GO GO!
1012 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1013 }
Christopher Tate7060b042014-06-09 19:50:00 -07001014 }
1015 }
1016
1017 /**
1018 * Called when we have a job status object that we need to insert in our
1019 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1020 * about.
1021 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001022 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1023 if (!jobStatus.isPreparedLocked()) {
1024 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1025 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001026 jobStatus.enqueueTime = SystemClock.elapsedRealtime();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001027 final boolean update = mJobs.add(jobStatus);
1028 if (mReadyToRock) {
1029 for (int i = 0; i < mControllers.size(); i++) {
1030 StateController controller = mControllers.get(i);
1031 if (update) {
1032 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001033 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001034 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001035 }
Christopher Tate7060b042014-06-09 19:50:00 -07001036 }
1037 }
1038
1039 /**
1040 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1041 * object removed.
1042 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001043 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001044 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001045 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001046 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001047
1048 // Remove from store as well as controllers.
1049 final boolean removed = mJobs.remove(jobStatus, writeBack);
1050 if (removed && mReadyToRock) {
1051 for (int i=0; i<mControllers.size(); i++) {
1052 StateController controller = mControllers.get(i);
1053 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001054 }
1055 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001056 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001057 }
1058
Dianne Hackborn729a3282017-06-09 16:06:01 -07001059 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001060 for (int i=0; i<mActiveServices.size(); i++) {
1061 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001062 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001063 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001064 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001065 return true;
1066 }
1067 }
1068 return false;
1069 }
1070
1071 /**
1072 * @param job JobStatus we are querying against.
1073 * @return Whether or not the job represented by the status object is currently being run or
1074 * is pending.
1075 */
1076 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001077 for (int i=0; i<mActiveServices.size(); i++) {
1078 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001079 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001080 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1081 return true;
1082 }
1083 }
1084 return false;
1085 }
1086
Dianne Hackborn807de782016-04-07 17:54:41 -07001087 void noteJobsPending(List<JobStatus> jobs) {
1088 for (int i = jobs.size() - 1; i >= 0; i--) {
1089 JobStatus job = jobs.get(i);
1090 mJobPackageTracker.notePending(job);
1091 }
1092 }
1093
1094 void noteJobsNonpending(List<JobStatus> jobs) {
1095 for (int i = jobs.size() - 1; i >= 0; i--) {
1096 JobStatus job = jobs.get(i);
1097 mJobPackageTracker.noteNonpending(job);
1098 }
1099 }
1100
Christopher Tate7060b042014-06-09 19:50:00 -07001101 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001102 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1103 * specify an override deadline on a failed job (the failed job will run even though it's not
1104 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1105 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1106 *
Christopher Tate7060b042014-06-09 19:50:00 -07001107 * @param failureToReschedule Provided job status that we will reschedule.
1108 * @return A newly instantiated JobStatus with the same constraints as the last job except
1109 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001110 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001111 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001112 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001113 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001114 final long elapsedNowMillis = SystemClock.elapsedRealtime();
1115 final JobInfo job = failureToReschedule.getJob();
1116
1117 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001118 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1119 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001120
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001121 if (failureToReschedule.hasWorkLocked()) {
1122 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1123 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1124 + backoffAttempts + " > work limit "
1125 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1126 return null;
1127 }
1128 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1129 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1130 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1131 return null;
1132 }
1133
Christopher Tate7060b042014-06-09 19:50:00 -07001134 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001135 case JobInfo.BACKOFF_POLICY_LINEAR: {
1136 long backoff = initialBackoffMillis;
1137 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1138 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1139 }
1140 delayMillis = backoff * backoffAttempts;
1141 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001142 default:
1143 if (DEBUG) {
1144 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1145 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001146 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1147 long backoff = initialBackoffMillis;
1148 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1149 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1150 }
1151 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1152 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001153 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001154 delayMillis =
1155 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001156 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001157 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
1158 failureToReschedule.getLastSuccessfulRunTime(), System.currentTimeMillis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001159 for (int ic=0; ic<mControllers.size(); ic++) {
1160 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001161 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001162 }
1163 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001164 }
1165
1166 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001167 * Called after a periodic has executed so we can reschedule it. We take the last execution
1168 * time of the job to be the time of completion (i.e. the time at which this function is
1169 * called).
Christopher Tate7060b042014-06-09 19:50:00 -07001170 * This could be inaccurate b/c the job can run for as long as
1171 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1172 * to underscheduling at least, rather than if we had taken the last execution time to be the
1173 * start of the execution.
1174 * @return A new job representing the execution criteria for this instantiation of the
1175 * recurring job.
1176 */
1177 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
1178 final long elapsedNow = SystemClock.elapsedRealtime();
1179 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001180 long runEarly = 0L;
1181
1182 // If this periodic was rescheduled it won't have a deadline.
1183 if (periodicToReschedule.hasDeadlineConstraint()) {
1184 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1185 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001186 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001187 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001188 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1189 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001190
1191 if (DEBUG) {
1192 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1193 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1194 }
1195 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001196 newLatestRuntimeElapsed, 0 /* backoffAttempt */,
1197 System.currentTimeMillis() /* lastSuccessfulRunTime */,
1198 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001199 }
1200
1201 // JobCompletedListener implementations.
1202
1203 /**
1204 * A job just finished executing. We fetch the
1205 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1206 * whether we want to reschedule we readd it to the controllers.
1207 * @param jobStatus Completed job.
1208 * @param needsReschedule Whether the implementing class should reschedule this job.
1209 */
1210 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001211 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001212 if (DEBUG) {
1213 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1214 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001215
1216 // If the job wants to be rescheduled, we first need to make the next upcoming
1217 // job so we can transfer any appropriate state over from the previous job when
1218 // we stop it.
1219 final JobStatus rescheduledJob = needsReschedule
1220 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1221
Shreyas Basarge73f10252016-02-11 17:06:13 +00001222 // Do not write back immediately if this is a periodic job. The job may get lost if system
1223 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001224 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001225 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001226 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001227 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001228 // We still want to check for jobs to execute, because this job may have
1229 // scheduled a new job under the same job id, and now we can run it.
1230 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001231 return;
1232 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001233
1234 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001235 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001236 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001237 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001238 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001239 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001240 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001241 } else if (jobStatus.getJob().isPeriodic()) {
1242 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001243 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001244 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001245 } catch (SecurityException e) {
1246 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1247 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001248 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001249 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001250 jobStatus.unprepareLocked(ActivityManager.getService());
1251 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001252 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001253 }
1254
1255 // StateChangedListener implementations.
1256
1257 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001258 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1259 * some controller's state has changed, so as to run through the list of jobs and start/stop
1260 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001261 */
1262 @Override
1263 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001264 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001265 }
1266
1267 @Override
1268 public void onRunJobNow(JobStatus jobStatus) {
1269 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1270 }
1271
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001272 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001273
1274 public JobHandler(Looper looper) {
1275 super(looper);
1276 }
1277
1278 @Override
1279 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001280 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001281 if (!mReadyToRock) {
1282 return;
1283 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001284 switch (message.what) {
1285 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001286 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001287 // runNow can be null, which is a controller's way of indicating that its
1288 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001289 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001290 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001291 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001292 } else {
1293 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001294 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001295 } break;
1296 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001297 if (mReportedActive) {
1298 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001299 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001300 } else {
1301 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001302 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001303 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001304 break;
1305 case MSG_CHECK_JOB_GREEDY:
1306 queueReadyJobsForExecutionLocked();
1307 break;
1308 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001309 cancelJobImplLocked((JobStatus) message.obj, null,
1310 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001311 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001312 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001313 maybeRunPendingJobsLocked();
1314 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1315 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001316 }
1317 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001318 }
Christopher Tate7060b042014-06-09 19:50:00 -07001319
Dianne Hackborn6d068262017-05-16 13:14:37 -07001320 private void stopNonReadyActiveJobsLocked() {
1321 for (int i=0; i<mActiveServices.size(); i++) {
1322 JobServiceContext serviceContext = mActiveServices.get(i);
1323 final JobStatus running = serviceContext.getRunningJobLocked();
1324 if (running != null && !running.isReady()) {
1325 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001326 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1327 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001328 }
1329 }
1330 }
1331
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001332 /**
1333 * Run through list of jobs and execute all possible - at least one is expired so we do
1334 * as many as we can.
1335 */
1336 private void queueReadyJobsForExecutionLocked() {
1337 if (DEBUG) {
1338 Slog.d(TAG, "queuing all ready jobs for execution:");
1339 }
1340 noteJobsNonpending(mPendingJobs);
1341 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001342 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001343 mJobs.forEachJob(mReadyQueueFunctor);
1344 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001345
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001346 if (DEBUG) {
1347 final int queuedJobs = mPendingJobs.size();
1348 if (queuedJobs == 0) {
1349 Slog.d(TAG, "No jobs pending.");
1350 } else {
1351 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001352 }
1353 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001354 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001355
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001356 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1357 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001358
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001359 @Override
1360 public void process(JobStatus job) {
1361 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001362 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001363 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001364 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001365 if (newReadyJobs == null) {
1366 newReadyJobs = new ArrayList<JobStatus>();
1367 }
1368 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001369 }
1370 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001371
1372 public void postProcess() {
1373 if (newReadyJobs != null) {
1374 noteJobsPending(newReadyJobs);
1375 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001376 if (mPendingJobs.size() > 1) {
1377 mPendingJobs.sort(mEnqueueTimeComparator);
1378 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001379 }
1380 newReadyJobs = null;
1381 }
1382 }
1383 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1384
1385 /**
1386 * The state of at least one job has changed. Here is where we could enforce various
1387 * policies on when we want to execute jobs.
1388 * Right now the policy is such:
1389 * If >1 of the ready jobs is idle mode we send all of them off
1390 * if more than 2 network connectivity jobs are ready we send them all off.
1391 * If more than 4 jobs total are ready we send them all off.
1392 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1393 */
1394 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1395 int chargingCount;
1396 int batteryNotLowCount;
1397 int storageNotLowCount;
1398 int idleCount;
1399 int backoffCount;
1400 int connectivityCount;
1401 int contentCount;
1402 List<JobStatus> runnableJobs;
1403
1404 public MaybeReadyJobQueueFunctor() {
1405 reset();
1406 }
1407
1408 // Functor method invoked for each job via JobStore.forEachJob()
1409 @Override
1410 public void process(JobStatus job) {
1411 if (isReadyToBeExecutedLocked(job)) {
1412 try {
1413 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1414 job.getJob().getService().getPackageName())) {
1415 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1416 + job.getJob().toString() + " -- package not allowed to start");
1417 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1418 return;
1419 }
1420 } catch (RemoteException e) {
1421 }
1422 if (job.getNumFailures() > 0) {
1423 backoffCount++;
1424 }
1425 if (job.hasIdleConstraint()) {
1426 idleCount++;
1427 }
1428 if (job.hasConnectivityConstraint()) {
1429 connectivityCount++;
1430 }
1431 if (job.hasChargingConstraint()) {
1432 chargingCount++;
1433 }
1434 if (job.hasBatteryNotLowConstraint()) {
1435 batteryNotLowCount++;
1436 }
1437 if (job.hasStorageNotLowConstraint()) {
1438 storageNotLowCount++;
1439 }
1440 if (job.hasContentTriggerConstraint()) {
1441 contentCount++;
1442 }
1443 if (runnableJobs == null) {
1444 runnableJobs = new ArrayList<>();
1445 }
1446 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001447 }
1448 }
1449
1450 public void postProcess() {
1451 if (backoffCount > 0 ||
1452 idleCount >= mConstants.MIN_IDLE_COUNT ||
1453 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1454 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1455 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1456 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1457 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1458 (runnableJobs != null
1459 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1460 if (DEBUG) {
1461 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1462 }
1463 noteJobsPending(runnableJobs);
1464 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001465 if (mPendingJobs.size() > 1) {
1466 mPendingJobs.sort(mEnqueueTimeComparator);
1467 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001468 } else {
1469 if (DEBUG) {
1470 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1471 }
1472 }
1473
1474 // Be ready for next time
1475 reset();
1476 }
1477
1478 private void reset() {
1479 chargingCount = 0;
1480 idleCount = 0;
1481 backoffCount = 0;
1482 connectivityCount = 0;
1483 batteryNotLowCount = 0;
1484 storageNotLowCount = 0;
1485 contentCount = 0;
1486 runnableJobs = null;
1487 }
1488 }
1489 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1490
1491 private void maybeQueueReadyJobsForExecutionLocked() {
1492 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1493
1494 noteJobsNonpending(mPendingJobs);
1495 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001496 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001497 mJobs.forEachJob(mMaybeQueueFunctor);
1498 mMaybeQueueFunctor.postProcess();
1499 }
1500
1501 /**
1502 * Criteria for moving a job into the pending queue:
1503 * - It's ready.
1504 * - It's not pending.
1505 * - It's not already running on a JSC.
1506 * - The user that requested the job is running.
1507 * - The component is enabled and runnable.
1508 */
1509 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001510 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001511
1512 if (DEBUG) {
1513 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1514 + " ready=" + jobReady);
1515 }
1516
1517 // This is a condition that is very likely to be false (most jobs that are
1518 // scheduled are sitting there, not ready yet) and very cheap to check (just
1519 // a few conditions on data in JobStatus).
1520 if (!jobReady) {
1521 return false;
1522 }
1523
1524 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001525
1526 final int userId = job.getUserId();
1527 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1528
1529 if (DEBUG) {
1530 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001531 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001532 }
1533
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001534 // These are also fairly cheap to check, though they typically will not
1535 // be conditions we fail.
1536 if (!jobExists || !userStarted) {
1537 return false;
1538 }
1539
1540 final boolean jobPending = mPendingJobs.contains(job);
1541 final boolean jobActive = isCurrentlyActiveLocked(job);
1542
1543 if (DEBUG) {
1544 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1545 + " pending=" + jobPending + " active=" + jobActive);
1546 }
1547
1548 // These can be a little more expensive (especially jobActive, since we need to
1549 // go through the array of all potentially active jobs), so we are doing them
1550 // later... but still before checking with the package manager!
1551 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001552 return false;
1553 }
1554
1555 final boolean componentPresent;
1556 try {
1557 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1558 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1559 userId) != null);
1560 } catch (RemoteException e) {
1561 throw e.rethrowAsRuntimeException();
1562 }
1563
1564 if (DEBUG) {
1565 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1566 + " componentPresent=" + componentPresent);
1567 }
1568
1569 // Everything else checked out so far, so this is the final yes/no check
1570 return componentPresent;
1571 }
1572
1573 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001574 * Reconcile jobs in the pending queue against available execution contexts.
1575 * A controller can force a job into the pending queue even if it's already running, but
1576 * here is where we decide whether to actually execute it.
1577 */
1578 private void maybeRunPendingJobsLocked() {
1579 if (DEBUG) {
1580 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1581 }
1582 assignJobsToContextsLocked();
1583 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001584 }
1585
Dianne Hackborn807de782016-04-07 17:54:41 -07001586 private int adjustJobPriority(int curPriority, JobStatus job) {
1587 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1588 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001589 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001590 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001591 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001592 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1593 }
1594 }
1595 return curPriority;
1596 }
1597
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001598 private int evaluateJobPriorityLocked(JobStatus job) {
1599 int priority = job.getPriority();
1600 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001601 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001602 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001603 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1604 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001605 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001606 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001607 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001608 }
1609
Christopher Tate7060b042014-06-09 19:50:00 -07001610 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001611 * Takes jobs from pending queue and runs them on available contexts.
1612 * If no contexts are available, preempts lower priority jobs to
1613 * run higher priority ones.
1614 * Lock on mJobs before calling this function.
1615 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001616 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001617 if (DEBUG) {
1618 Slog.d(TAG, printPendingQueue());
1619 }
1620
Dianne Hackborn970510b2016-02-24 16:56:42 -08001621 int memLevel;
1622 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001623 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001624 } catch (RemoteException e) {
1625 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1626 }
1627 switch (memLevel) {
1628 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001629 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001630 break;
1631 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001632 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001633 break;
1634 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001635 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001636 break;
1637 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001638 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001639 break;
1640 }
1641
1642 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1643 boolean[] act = mTmpAssignAct;
1644 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1645 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001646 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001647 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1648 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001649 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001650 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001651 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001652 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1653 numForeground++;
1654 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001655 }
1656 act[i] = false;
1657 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001658 }
1659 if (DEBUG) {
1660 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1661 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001662 for (int i=0; i<mPendingJobs.size(); i++) {
1663 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001664
1665 // If job is already running, go to next job.
1666 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1667 if (jobRunningContext != -1) {
1668 continue;
1669 }
1670
Dianne Hackborn970510b2016-02-24 16:56:42 -08001671 final int priority = evaluateJobPriorityLocked(nextPending);
1672 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001673
Shreyas Basarge5db09082016-01-07 13:38:29 +00001674 // Find a context for nextPending. The context should be available OR
1675 // it should have lowest priority among all running jobs
1676 // (sharing the same Uid as nextPending)
1677 int minPriority = Integer.MAX_VALUE;
1678 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001679 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1680 JobStatus job = contextIdToJobMap[j];
1681 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001682 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001683 if ((numActive < mMaxActiveJobs ||
1684 (priority >= JobInfo.PRIORITY_TOP_APP &&
1685 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001686 (preferredUid == nextPending.getUid() ||
1687 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1688 // This slot is free, and we haven't yet hit the limit on
1689 // concurrent jobs... we can just throw the job in to here.
1690 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001691 break;
1692 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001693 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001694 // the context has a preferred Uid or we have reached the limit on
1695 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001696 continue;
1697 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001698 if (job.getUid() != nextPending.getUid()) {
1699 continue;
1700 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001701 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001702 continue;
1703 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001704 if (minPriority > nextPending.lastEvaluatedPriority) {
1705 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001706 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001707 }
1708 }
1709 if (minPriorityContextId != -1) {
1710 contextIdToJobMap[minPriorityContextId] = nextPending;
1711 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001712 numActive++;
1713 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1714 numForeground++;
1715 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001716 }
1717 }
1718 if (DEBUG) {
1719 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1720 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001721 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001722 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001723 boolean preservePreferredUid = false;
1724 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001725 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001726 if (js != null) {
1727 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001728 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001729 }
1730 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001731 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001732 preservePreferredUid = true;
1733 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001734 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001735 if (DEBUG) {
1736 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001737 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001738 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001739 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001740 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001741 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001742 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1743 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001744 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001745 if (mPendingJobs.remove(pendingJob)) {
1746 mJobPackageTracker.noteNonpending(pendingJob);
1747 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001748 }
1749 }
1750 if (!preservePreferredUid) {
1751 mActiveServices.get(i).clearPreferredUid();
1752 }
1753 }
1754 }
1755
1756 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1757 for (int i=0; i<map.length; i++) {
1758 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1759 return i;
1760 }
1761 }
1762 return -1;
1763 }
1764
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001765 final class LocalService implements JobSchedulerInternal {
1766
1767 /**
1768 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1769 * jobs are always considered pending.
1770 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001771 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001772 public List<JobInfo> getSystemScheduledPendingJobs() {
1773 synchronized (mLock) {
1774 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1775 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1776 @Override
1777 public void process(JobStatus job) {
1778 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1779 pendingJobs.add(job.getJob());
1780 }
1781 }
1782 });
1783 return pendingJobs;
1784 }
1785 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001786
1787 @Override
1788 public void addBackingUpUid(int uid) {
1789 synchronized (mLock) {
1790 // No need to actually do anything here, since for a full backup the
1791 // activity manager will kill the process which will kill the job (and
1792 // cause it to restart, but now it can't run).
1793 mBackingUpUids.put(uid, uid);
1794 }
1795 }
1796
1797 @Override
1798 public void removeBackingUpUid(int uid) {
1799 synchronized (mLock) {
1800 mBackingUpUids.delete(uid);
1801 // If there are any jobs for this uid, we need to rebuild the pending list
1802 // in case they are now ready to run.
1803 if (mJobs.countJobsForUid(uid) > 0) {
1804 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1805 }
1806 }
1807 }
1808
1809 @Override
1810 public void clearAllBackingUpUids() {
1811 synchronized (mLock) {
1812 if (mBackingUpUids.size() > 0) {
1813 mBackingUpUids.clear();
1814 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1815 }
1816 }
1817 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001818 }
1819
Shreyas Basarge5db09082016-01-07 13:38:29 +00001820 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001821 * Binder stub trampoline implementation
1822 */
1823 final class JobSchedulerStub extends IJobScheduler.Stub {
1824 /** Cache determination of whether a given app can persist jobs
1825 * key is uid of the calling app; value is undetermined/true/false
1826 */
1827 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1828
1829 // Enforce that only the app itself (or shared uid participant) can schedule a
1830 // job that runs one of the app's services, as well as verifying that the
1831 // named service properly requires the BIND_JOB_SERVICE permission
1832 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001833 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001834 final ComponentName service = job.getService();
1835 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001836 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001837 PackageManager.MATCH_DIRECT_BOOT_AWARE
1838 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001839 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001840 if (si == null) {
1841 throw new IllegalArgumentException("No such service " + service);
1842 }
Christopher Tate7060b042014-06-09 19:50:00 -07001843 if (si.applicationInfo.uid != uid) {
1844 throw new IllegalArgumentException("uid " + uid +
1845 " cannot schedule job in " + service.getPackageName());
1846 }
1847 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1848 throw new IllegalArgumentException("Scheduled service " + service
1849 + " does not require android.permission.BIND_JOB_SERVICE permission");
1850 }
Christopher Tate5568f542014-06-18 13:53:31 -07001851 } catch (RemoteException e) {
1852 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001853 }
1854 }
1855
1856 private boolean canPersistJobs(int pid, int uid) {
1857 // If we get this far we're good to go; all we need to do now is check
1858 // whether the app is allowed to persist its scheduled work.
1859 final boolean canPersist;
1860 synchronized (mPersistCache) {
1861 Boolean cached = mPersistCache.get(uid);
1862 if (cached != null) {
1863 canPersist = cached.booleanValue();
1864 } else {
1865 // Persisting jobs is tantamount to running at boot, so we permit
1866 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1867 // permission
1868 int result = getContext().checkPermission(
1869 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1870 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1871 mPersistCache.put(uid, canPersist);
1872 }
1873 }
1874 return canPersist;
1875 }
1876
1877 // IJobScheduler implementation
1878 @Override
1879 public int schedule(JobInfo job) throws RemoteException {
1880 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001881 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001882 }
1883 final int pid = Binder.getCallingPid();
1884 final int uid = Binder.getCallingUid();
1885
1886 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001887 if (job.isPersisted()) {
1888 if (!canPersistJobs(pid, uid)) {
1889 throw new IllegalArgumentException("Error: requested job be persisted without"
1890 + " holding RECEIVE_BOOT_COMPLETED permission.");
1891 }
1892 }
Christopher Tate7060b042014-06-09 19:50:00 -07001893
Jeff Sharkey785f4942016-07-14 10:31:15 -06001894 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1895 getContext().enforceCallingOrSelfPermission(
1896 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1897 }
1898
Christopher Tate7060b042014-06-09 19:50:00 -07001899 long ident = Binder.clearCallingIdentity();
1900 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001901 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, -1, null);
1902 } finally {
1903 Binder.restoreCallingIdentity(ident);
1904 }
1905 }
1906
1907 // IJobScheduler implementation
1908 @Override
1909 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
1910 if (DEBUG) {
1911 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
1912 }
1913 final int pid = Binder.getCallingPid();
1914 final int uid = Binder.getCallingUid();
1915
1916 enforceValidJobRequest(uid, job);
1917 if (job.isPersisted()) {
1918 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
1919 }
1920 if (work == null) {
1921 throw new NullPointerException("work is null");
1922 }
1923
1924 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1925 getContext().enforceCallingOrSelfPermission(
1926 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1927 }
1928
1929 long ident = Binder.clearCallingIdentity();
1930 try {
1931 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, -1, null);
Christopher Tate7060b042014-06-09 19:50:00 -07001932 } finally {
1933 Binder.restoreCallingIdentity(ident);
1934 }
1935 }
1936
1937 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001938 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001939 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001940 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001941 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001942 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1943 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001944 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001945
1946 if (packageName == null) {
1947 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001948 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001949
1950 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1951 android.Manifest.permission.UPDATE_DEVICE_STATS);
1952 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1953 throw new SecurityException("Caller uid " + callerUid
1954 + " not permitted to schedule jobs for other apps");
1955 }
1956
Jeff Sharkey4f100402016-05-03 17:44:23 -06001957 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1958 getContext().enforceCallingOrSelfPermission(
1959 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1960 }
1961
Shreyas Basarge968ac752016-01-11 23:09:26 +00001962 long ident = Binder.clearCallingIdentity();
1963 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001964 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001965 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001966 } finally {
1967 Binder.restoreCallingIdentity(ident);
1968 }
1969 }
1970
1971 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001972 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1973 final int uid = Binder.getCallingUid();
1974
1975 long ident = Binder.clearCallingIdentity();
1976 try {
1977 return JobSchedulerService.this.getPendingJobs(uid);
1978 } finally {
1979 Binder.restoreCallingIdentity(ident);
1980 }
1981 }
1982
1983 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001984 public JobInfo getPendingJob(int jobId) throws RemoteException {
1985 final int uid = Binder.getCallingUid();
1986
1987 long ident = Binder.clearCallingIdentity();
1988 try {
1989 return JobSchedulerService.this.getPendingJob(uid, jobId);
1990 } finally {
1991 Binder.restoreCallingIdentity(ident);
1992 }
1993 }
1994
1995 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001996 public void cancelAll() throws RemoteException {
1997 final int uid = Binder.getCallingUid();
1998
1999 long ident = Binder.clearCallingIdentity();
2000 try {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002001 JobSchedulerService.this.cancelJobsForUid(uid, "cancelAll() called by app");
Christopher Tate7060b042014-06-09 19:50:00 -07002002 } finally {
2003 Binder.restoreCallingIdentity(ident);
2004 }
2005 }
2006
2007 @Override
2008 public void cancel(int jobId) throws RemoteException {
2009 final int uid = Binder.getCallingUid();
2010
2011 long ident = Binder.clearCallingIdentity();
2012 try {
2013 JobSchedulerService.this.cancelJob(uid, jobId);
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
2017 }
2018
2019 /**
2020 * "dumpsys" infrastructure
2021 */
2022 @Override
2023 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002024 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002025
2026 long identityToken = Binder.clearCallingIdentity();
2027 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002028 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07002029 } finally {
2030 Binder.restoreCallingIdentity(identityToken);
2031 }
2032 }
Christopher Tate5d346052016-03-08 12:56:08 -08002033
2034 @Override
2035 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002036 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002037 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002038 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002039 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002040 };
2041
Christopher Tate5d346052016-03-08 12:56:08 -08002042 // Shell command infrastructure: run the given job immediately
2043 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2044 if (DEBUG) {
2045 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2046 + " " + jobId + " f=" + force);
2047 }
2048
2049 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002050 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2051 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002052 if (uid < 0) {
2053 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2054 }
2055
2056 synchronized (mLock) {
2057 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2058 if (js == null) {
2059 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2060 }
2061
2062 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2063 if (!js.isConstraintsSatisfied()) {
2064 js.overrideState = 0;
2065 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2066 }
2067
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002068 queueReadyJobsForExecutionLocked();
2069 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002070 }
2071 } catch (RemoteException e) {
2072 // can't happen
2073 }
2074 return 0;
2075 }
2076
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002077 // Shell command infrastructure: immediately timeout currently executing jobs
2078 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2079 boolean hasJobId, int jobId) {
2080 if (DEBUG) {
2081 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2082 }
2083
2084 synchronized (mLock) {
2085 boolean foundSome = false;
2086 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002087 final JobServiceContext jc = mActiveServices.get(i);
2088 final JobStatus js = jc.getRunningJobLocked();
2089 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId)) {
2090 foundSome = true;
2091 pw.print("Timing out: ");
2092 js.printUniqueId(pw);
2093 pw.print(" ");
2094 pw.println(js.getServiceComponent().flattenToShortString());
2095 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002096 }
2097 if (!foundSome) {
2098 pw.println("No matching executing jobs found.");
2099 }
2100 }
2101 return 0;
2102 }
2103
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002104 void setMonitorBattery(boolean enabled) {
2105 synchronized (mLock) {
2106 if (mBatteryController != null) {
2107 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2108 }
2109 }
2110 }
2111
2112 int getBatterySeq() {
2113 synchronized (mLock) {
2114 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2115 }
2116 }
2117
2118 boolean getBatteryCharging() {
2119 synchronized (mLock) {
2120 return mBatteryController != null
2121 ? mBatteryController.getTracker().isOnStablePower() : false;
2122 }
2123 }
2124
2125 boolean getBatteryNotLow() {
2126 synchronized (mLock) {
2127 return mBatteryController != null
2128 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2129 }
2130 }
2131
Dianne Hackborn532ea262017-03-17 17:50:55 -07002132 int getStorageSeq() {
2133 synchronized (mLock) {
2134 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2135 }
2136 }
2137
2138 boolean getStorageNotLow() {
2139 synchronized (mLock) {
2140 return mStorageController != null
2141 ? mStorageController.getTracker().isStorageNotLow() : false;
2142 }
2143 }
2144
Dianne Hackborn6d068262017-05-16 13:14:37 -07002145 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2146 try {
2147 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2148 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2149 if (uid < 0) {
2150 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2151 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2152 }
2153
2154 synchronized (mLock) {
2155 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2156 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2157 if (js == null) {
2158 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2159 pw.print("/jid"); pw.print(jobId); pw.println(")");
2160 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2161 }
2162
2163 boolean printed = false;
2164 if (mPendingJobs.contains(js)) {
2165 pw.print("pending");
2166 printed = true;
2167 }
2168 if (isCurrentlyActiveLocked(js)) {
2169 if (printed) {
2170 pw.print(" ");
2171 }
2172 printed = true;
2173 pw.println("active");
2174 }
2175 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2176 if (printed) {
2177 pw.print(" ");
2178 }
2179 printed = true;
2180 pw.println("user-stopped");
2181 }
2182 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2183 if (printed) {
2184 pw.print(" ");
2185 }
2186 printed = true;
2187 pw.println("backing-up");
2188 }
2189 boolean componentPresent = false;
2190 try {
2191 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2192 js.getServiceComponent(),
2193 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2194 js.getUserId()) != null);
2195 } catch (RemoteException e) {
2196 }
2197 if (!componentPresent) {
2198 if (printed) {
2199 pw.print(" ");
2200 }
2201 printed = true;
2202 pw.println("no-component");
2203 }
2204 if (js.isReady()) {
2205 if (printed) {
2206 pw.print(" ");
2207 }
2208 printed = true;
2209 pw.println("ready");
2210 }
2211 if (!printed) {
2212 pw.print("waiting");
2213 }
2214 pw.println();
2215 }
2216 } catch (RemoteException e) {
2217 // can't happen
2218 }
2219 return 0;
2220 }
2221
Shreyas Basarge5db09082016-01-07 13:38:29 +00002222 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2223 StringBuilder s = new StringBuilder(initial + ": ");
2224 for (int i=0; i<map.length; i++) {
2225 s.append("(")
2226 .append(map[i] == null? -1: map[i].getJobId())
2227 .append(map[i] == null? -1: map[i].getUid())
2228 .append(")" );
2229 }
2230 return s.toString();
2231 }
2232
2233 private String printPendingQueue() {
2234 StringBuilder s = new StringBuilder("Pending queue: ");
2235 Iterator<JobStatus> it = mPendingJobs.iterator();
2236 while (it.hasNext()) {
2237 JobStatus js = it.next();
2238 s.append("(")
2239 .append(js.getJob().getId())
2240 .append(", ")
2241 .append(js.getUid())
2242 .append(") ");
2243 }
2244 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002245 }
Christopher Tate7060b042014-06-09 19:50:00 -07002246
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002247 static void dumpHelp(PrintWriter pw) {
2248 pw.println("Job Scheduler (jobscheduler) dump options:");
2249 pw.println(" [-h] [package] ...");
2250 pw.println(" -h: print this help");
2251 pw.println(" [package] is an optional package name to limit the output to.");
2252 }
2253
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002254 void dumpInternal(final PrintWriter pw, String[] args) {
2255 int filterUid = -1;
2256 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002257 int opti = 0;
2258 while (opti < args.length) {
2259 String arg = args[opti];
2260 if ("-h".equals(arg)) {
2261 dumpHelp(pw);
2262 return;
2263 } else if ("-a".equals(arg)) {
2264 // Ignore, we always dump all.
2265 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2266 pw.println("Unknown option: " + arg);
2267 return;
2268 } else {
2269 break;
2270 }
2271 opti++;
2272 }
2273 if (opti < args.length) {
2274 String pkg = args[opti];
2275 try {
2276 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002277 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002278 } catch (NameNotFoundException ignored) {
2279 pw.println("Invalid package: " + pkg);
2280 return;
2281 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002282 }
2283 }
2284
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002285 final int filterUidFinal = UserHandle.getAppId(filterUid);
Dianne Hackborn6d068262017-05-16 13:14:37 -07002286 final long nowElapsed = SystemClock.elapsedRealtime();
2287 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002288 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002289 mConstants.dump(pw);
2290 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002291 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002292 pw.print("Registered ");
2293 pw.print(mJobs.size());
2294 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002295 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002296 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2297 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002298 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002299 public int compare(JobStatus o1, JobStatus o2) {
2300 int uid1 = o1.getUid();
2301 int uid2 = o2.getUid();
2302 int id1 = o1.getJobId();
2303 int id2 = o2.getJobId();
2304 if (uid1 != uid2) {
2305 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002306 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002307 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08002308 }
2309 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002310 for (JobStatus job : jobs) {
2311 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2312 pw.println(job.toShortStringExceptUniqueId());
2313
2314 // Skip printing details if the caller requested a filter
2315 if (!job.shouldDump(filterUidFinal)) {
2316 continue;
2317 }
2318
Dianne Hackborn6d068262017-05-16 13:14:37 -07002319 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002320 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002321 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002322 pw.print(" (job=");
2323 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002324 pw.print(" user=");
2325 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002326 pw.print(" !pending=");
2327 pw.print(!mPendingJobs.contains(job));
2328 pw.print(" !active=");
2329 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002330 pw.print(" !backingup=");
2331 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002332 pw.print(" comp=");
2333 boolean componentPresent = false;
2334 try {
2335 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2336 job.getServiceComponent(),
2337 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2338 job.getUserId()) != null);
2339 } catch (RemoteException e) {
2340 }
2341 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002342 pw.println(")");
2343 }
Christopher Tate7060b042014-06-09 19:50:00 -07002344 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002345 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002346 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002347 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002348 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002349 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002350 }
2351 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002352 pw.println("Uid priority overrides:");
2353 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002354 int uid = mUidPriorityOverride.keyAt(i);
2355 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2356 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2357 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2358 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002359 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002360 if (mBackingUpUids.size() > 0) {
2361 pw.println();
2362 pw.println("Backing up uids:");
2363 boolean first = true;
2364 for (int i = 0; i < mBackingUpUids.size(); i++) {
2365 int uid = mBackingUpUids.keyAt(i);
2366 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2367 if (first) {
2368 pw.print(" ");
2369 first = false;
2370 } else {
2371 pw.print(", ");
2372 }
2373 pw.print(UserHandle.formatUid(uid));
2374 }
2375 }
2376 pw.println();
2377 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002378 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002379 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002380 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002381 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2382 pw.println();
2383 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002384 pw.println("Pending queue:");
2385 for (int i=0; i<mPendingJobs.size(); i++) {
2386 JobStatus job = mPendingJobs.get(i);
2387 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2388 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002389 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002390 int priority = evaluateJobPriorityLocked(job);
2391 if (priority != JobInfo.PRIORITY_DEFAULT) {
2392 pw.print(" Evaluated priority: "); pw.println(priority);
2393 }
2394 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002395 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002396 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002397 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002398 }
Christopher Tate7060b042014-06-09 19:50:00 -07002399 pw.println();
2400 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002401 for (int i=0; i<mActiveServices.size(); i++) {
2402 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002403 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002404 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002405 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002406 if (jsc.mStoppedReason != null) {
2407 pw.print("inactive since ");
2408 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2409 pw.print(", stopped because: ");
2410 pw.println(jsc.mStoppedReason);
2411 } else {
2412 pw.println("inactive");
2413 }
Christopher Tate7060b042014-06-09 19:50:00 -07002414 continue;
2415 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002416 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002417 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002418 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002419 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002420 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002421 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002422 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002423 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002424 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002425 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002426 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002427 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002428 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002429 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002430 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2431 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002432 }
2433 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002434 if (filterUid == -1) {
2435 pw.println();
2436 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2437 pw.print("mReportedActive="); pw.println(mReportedActive);
2438 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2439 }
Christopher Tate7060b042014-06-09 19:50:00 -07002440 }
2441 pw.println();
2442 }
2443}