blob: b30afb5e4777e40e40719279d89532e349604b7c [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
Shreyas Basarge5db09082016-01-07 13:38:29 +000019import java.io.FileDescriptor;
20import java.io.PrintWriter;
21import java.util.ArrayList;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070022import java.util.Arrays;
Shreyas Basarge5db09082016-01-07 13:38:29 +000023import java.util.Iterator;
24import java.util.List;
25
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070026import android.app.ActivityManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070027import android.app.ActivityManagerNative;
Christopher Tate5568f542014-06-18 13:53:31 -070028import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070029import android.app.IUidObserver;
Christopher Tate7060b042014-06-09 19:50:00 -070030import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000031import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070032import android.app.job.JobScheduler;
33import android.app.job.JobService;
Shreyas Basarge5db09082016-01-07 13:38:29 +000034import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070035import android.content.BroadcastReceiver;
36import android.content.ComponentName;
37import android.content.Context;
38import android.content.Intent;
39import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070040import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070042import android.content.pm.ServiceInfo;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070043import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070044import android.os.Binder;
45import android.os.Handler;
46import android.os.Looper;
47import android.os.Message;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070048import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070049import android.os.RemoteException;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070050import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070051import android.os.SystemClock;
52import android.os.UserHandle;
53import android.util.Slog;
54import android.util.SparseArray;
55
Dianne Hackbornfdb19562014-07-11 16:03:36 -070056import com.android.internal.app.IBatteryStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070057import com.android.internal.util.ArrayUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080058import com.android.server.DeviceIdleController;
59import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080060import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080061import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070062import com.android.server.job.controllers.BatteryController;
63import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080064import com.android.server.job.controllers.ContentObserverController;
Christopher Tate7060b042014-06-09 19:50:00 -070065import com.android.server.job.controllers.IdleController;
66import com.android.server.job.controllers.JobStatus;
67import com.android.server.job.controllers.StateController;
68import com.android.server.job.controllers.TimeController;
69
Jeff Sharkey822cbd12016-02-25 11:09:55 -070070import libcore.util.EmptyArray;
71
Christopher Tate7060b042014-06-09 19:50:00 -070072/**
73 * Responsible for taking jobs representing work to be performed by a client app, and determining
74 * based on the criteria specified when that job should be run against the client application's
75 * endpoint.
76 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
77 * about constraints, or the state of active jobs. It receives callbacks from the various
78 * controllers and completed jobs and operates accordingly.
79 *
80 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
81 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
82 * @hide
83 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -080084public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070085 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -080086 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -070087 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -080088
Christopher Tate7060b042014-06-09 19:50:00 -070089 /** The number of concurrent jobs we run at one time. */
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070090 private static final int MAX_JOB_CONTEXTS_COUNT
Shreyas Basarge8c834c02016-01-07 13:53:16 +000091 = ActivityManager.isLowRamDeviceStatic() ? 3 : 6;
Christopher Tate2f36fd62016-02-18 18:36:08 -080092 /** The maximum number of jobs that we allow an unprivileged app to schedule */
93 private static final int MAX_JOBS_PER_APP = 100;
94
Dianne Hackborn33d31c52016-02-16 10:30:33 -080095 /** Global local for all job scheduler state. */
96 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -070097 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070098 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -070099
100 static final int MSG_JOB_EXPIRED = 0;
101 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700102 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000103 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700104
105 // Policy constants
106 /**
107 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
108 * early.
109 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700110 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -0700111 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700112 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
113 * early.
114 */
115 static final int MIN_CHARGING_COUNT = 1;
116 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700117 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
118 * things early.
119 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700120 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700121 /**
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800122 * Minimum # of content trigger jobs that must be ready in order to force the JMS to schedule
123 * things early.
124 */
125 static final int MIN_CONTENT_COUNT = 1;
126 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700127 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
128 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700129 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700130 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700131 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700132
133 /**
134 * Track Services that have currently active or pending jobs. The index is provided by
135 * {@link JobStatus#getServiceToken()}
136 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700137 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700138 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700139 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700140 /**
141 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
142 * when ready to execute them.
143 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700144 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700145
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700146 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700147
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700148 final JobHandler mHandler;
149 final JobSchedulerStub mJobSchedulerStub;
150
151 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700152 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800153 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700154
155 /**
156 * Set to true once we are allowed to run third party apps.
157 */
158 boolean mReadyToRock;
159
Christopher Tate7060b042014-06-09 19:50:00 -0700160 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700161 * True when in device idle mode, so we don't want to schedule any jobs.
162 */
163 boolean mDeviceIdleMode;
164
165 /**
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800166 * What we last reported to DeviceIdleController about wheter we are active.
167 */
168 boolean mReportedActive;
169
170 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700171 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
172 * still clean up. On reinstall the package will have a new uid.
173 */
174 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
175 @Override
176 public void onReceive(Context context, Intent intent) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000177 Slog.d(TAG, "Receieved: " + intent.getAction());
178 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700179 // If this is an outright uninstall rather than the first half of an
180 // app update sequence, cancel the jobs associated with the app.
181 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
182 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
183 if (DEBUG) {
184 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
185 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700186 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700187 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000188 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700189 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
190 if (DEBUG) {
191 Slog.d(TAG, "Removing jobs for user: " + userId);
192 }
193 cancelJobsForUser(userId);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000194 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())
195 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700196 updateIdleMode(mPowerManager != null
197 ? (mPowerManager.isDeviceIdleMode()
Shreyas Basarge5db09082016-01-07 13:38:29 +0000198 || mPowerManager.isLightDeviceIdleMode())
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700199 : false);
Christopher Tate7060b042014-06-09 19:50:00 -0700200 }
201 }
202 };
203
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700204 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
205 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
206 }
207
208 @Override public void onUidGone(int uid) throws RemoteException {
209 }
210
211 @Override public void onUidActive(int uid) throws RemoteException {
212 }
213
214 @Override public void onUidIdle(int uid) throws RemoteException {
215 cancelJobsForUid(uid, false);
216 }
217 };
218
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800219 public Object getLock() {
220 return mLock;
221 }
222
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700223 @Override
224 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700225 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
226 // Let's kick any outstanding jobs for this user.
227 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
228 }
229
230 @Override
231 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700232 // Let's kick any outstanding jobs for this user.
233 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
234 }
235
236 @Override
237 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700238 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700239 }
240
Christopher Tate7060b042014-06-09 19:50:00 -0700241 /**
242 * Entry point from client to schedule the provided job.
243 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
244 * @param job JobInfo object containing execution parameters
245 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700246 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
247 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700248 public int schedule(JobInfo job, int uId) {
Shreyas Basarge968ac752016-01-11 23:09:26 +0000249 return scheduleAsPackage(job, uId, null, -1);
250 }
251
252 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId) {
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800253 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700254 try {
255 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
256 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
257 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
258 + " -- package not allowed to start");
259 return JobScheduler.RESULT_FAILURE;
260 }
261 } catch (RemoteException e) {
262 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800263 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
264 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800265 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800266 // Jobs on behalf of others don't apply to the per-app job cap
267 if (packageName == null) {
268 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
269 Slog.w(TAG, "Too many jobs for uid " + uId);
270 throw new IllegalStateException("Apps may not schedule more than "
271 + MAX_JOBS_PER_APP + " distinct jobs");
272 }
273 }
274
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800275 toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
276 }
277 startTrackingJob(jobStatus, toCancel);
278 if (toCancel != null) {
279 cancelJobImpl(toCancel);
280 }
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700281 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700282 return JobScheduler.RESULT_SUCCESS;
283 }
284
285 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800286 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800287 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
288 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
289 for (int i = jobs.size() - 1; i >= 0; i--) {
290 JobStatus job = jobs.get(i);
291 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700292 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800293 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700294 }
Christopher Tate7060b042014-06-09 19:50:00 -0700295 }
296
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700297 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700298 List<JobStatus> jobsForUser;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800299 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700300 jobsForUser = mJobs.getJobsByUser(userHandle);
301 }
302 for (int i=0; i<jobsForUser.size(); i++) {
303 JobStatus toRemove = jobsForUser.get(i);
304 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700305 }
306 }
307
308 /**
309 * Entry point from client to cancel all jobs originating from their uid.
310 * This will remove the job from the master list, and cancel the job if it was staged for
311 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700312 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700313 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
314 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700315 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700316 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700317 List<JobStatus> jobsForUid;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800318 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700319 jobsForUid = mJobs.getJobsByUid(uid);
320 }
321 for (int i=0; i<jobsForUid.size(); i++) {
322 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700323 if (!forceAll) {
324 String packageName = toRemove.getServiceComponent().getPackageName();
325 try {
326 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
327 != ActivityManager.APP_START_MODE_DISABLED) {
328 continue;
329 }
330 } catch (RemoteException e) {
331 }
332 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700333 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700334 }
335 }
336
337 /**
338 * Entry point from client to cancel the job corresponding to the jobId provided.
339 * This will remove the job from the master list, and cancel the job if it was staged for
340 * execution or being executed.
341 * @param uid Uid of the calling client.
342 * @param jobId Id of the job, provided at schedule-time.
343 */
344 public void cancelJob(int uid, int jobId) {
345 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800346 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700347 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700348 }
349 if (toCancel != null) {
350 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700351 }
352 }
353
Matthew Williams48a30db2014-09-23 13:39:36 -0700354 private void cancelJobImpl(JobStatus cancelled) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800355 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Shreyas Basarge73f10252016-02-11 17:06:13 +0000356 stopTrackingJob(cancelled, true /* writeBack */);
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800357 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700358 // Remove from pending queue.
359 mPendingJobs.remove(cancelled);
360 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000361 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800362 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700363 }
Christopher Tate7060b042014-06-09 19:50:00 -0700364 }
365
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700366 void updateIdleMode(boolean enabled) {
367 boolean changed = false;
368 boolean rocking;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800369 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700370 if (mDeviceIdleMode != enabled) {
371 changed = true;
372 }
373 rocking = mReadyToRock;
374 }
375 if (changed) {
376 if (rocking) {
377 for (int i=0; i<mControllers.size(); i++) {
378 mControllers.get(i).deviceIdleModeChanged(enabled);
379 }
380 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800381 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700382 mDeviceIdleMode = enabled;
383 if (enabled) {
384 // When becoming idle, make sure no jobs are actively running.
385 for (int i=0; i<mActiveServices.size(); i++) {
386 JobServiceContext jsc = mActiveServices.get(i);
387 final JobStatus executing = jsc.getRunningJob();
388 if (executing != null) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000389 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700390 }
391 }
392 } else {
393 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800394 if (rocking) {
395 if (mLocalDeviceIdleController != null) {
396 if (!mReportedActive) {
397 mReportedActive = true;
398 mLocalDeviceIdleController.setJobsActive(true);
399 }
400 }
401 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700402 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
403 }
404 }
405 }
406 }
407
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800408 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000409 // active is true if pending queue contains jobs OR some job is running.
410 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800411 if (mPendingJobs.size() <= 0) {
412 for (int i=0; i<mActiveServices.size(); i++) {
413 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000414 if (jsc.getRunningJob() != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800415 active = true;
416 break;
417 }
418 }
419 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000420
421 if (mReportedActive != active) {
422 mReportedActive = active;
423 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800424 mLocalDeviceIdleController.setJobsActive(active);
425 }
426 }
427 }
428
Christopher Tate7060b042014-06-09 19:50:00 -0700429 /**
430 * Initializes the system service.
431 * <p>
432 * Subclasses must define a single argument constructor that accepts the context
433 * and passes it to super.
434 * </p>
435 *
436 * @param context The system server context.
437 */
438 public JobSchedulerService(Context context) {
439 super(context);
440 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700441 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700442 mControllers.add(ConnectivityController.get(this));
443 mControllers.add(TimeController.get(this));
444 mControllers.add(IdleController.get(this));
445 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800446 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800447 mControllers.add(ContentObserverController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700448
449 mHandler = new JobHandler(context.getMainLooper());
450 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700451 mJobs = JobStore.initAndGet(this);
452 }
453
454 @Override
455 public void onStart() {
456 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
457 }
458
459 @Override
460 public void onBootPhase(int phase) {
461 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000462 // Register br for package removals and user removals.
Christopher Tate7060b042014-06-09 19:50:00 -0700463 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
464 filter.addDataScheme("package");
465 getContext().registerReceiverAsUser(
466 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
467 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700468 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700469 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700470 getContext().registerReceiverAsUser(
471 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000472 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700473 try {
474 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
475 ActivityManager.UID_OBSERVER_IDLE);
476 } catch (RemoteException e) {
477 // ignored; both services live in system_server
478 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700479 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800480 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700481 // Let's go!
482 mReadyToRock = true;
483 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
484 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800485 mLocalDeviceIdleController
486 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700487 // Create the "runners".
488 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
489 mActiveServices.add(
490 new JobServiceContext(this, mBatteryStats,
491 getContext().getMainLooper()));
492 }
493 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -0800494 mJobs.forEachJob(new JobStatusFunctor() {
495 @Override
496 public void process(JobStatus job) {
497 for (int controller = 0; controller < mControllers.size(); controller++) {
498 final StateController sc = mControllers.get(controller);
499 sc.deviceIdleModeChanged(mDeviceIdleMode);
500 sc.maybeStartTrackingJobLocked(job, null);
501 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700502 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800503 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700504 // GO GO GO!
505 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
506 }
Christopher Tate7060b042014-06-09 19:50:00 -0700507 }
508 }
509
510 /**
511 * Called when we have a job status object that we need to insert in our
512 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
513 * about.
514 */
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800515 private void startTrackingJob(JobStatus jobStatus, JobStatus lastJob) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800516 synchronized (mLock) {
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800517 final boolean update = mJobs.add(jobStatus);
518 if (mReadyToRock) {
519 for (int i = 0; i < mControllers.size(); i++) {
520 StateController controller = mControllers.get(i);
521 if (update) {
522 controller.maybeStopTrackingJobLocked(jobStatus, true);
523 }
524 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700525 }
Christopher Tate7060b042014-06-09 19:50:00 -0700526 }
Christopher Tate7060b042014-06-09 19:50:00 -0700527 }
528 }
529
530 /**
531 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
532 * object removed.
533 */
Shreyas Basarge73f10252016-02-11 17:06:13 +0000534 private boolean stopTrackingJob(JobStatus jobStatus, boolean writeBack) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800535 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700536 // Remove from store as well as controllers.
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800537 final boolean removed = mJobs.remove(jobStatus, writeBack);
538 if (removed && mReadyToRock) {
539 for (int i=0; i<mControllers.size(); i++) {
540 StateController controller = mControllers.get(i);
541 controller.maybeStopTrackingJobLocked(jobStatus, false);
542 }
Christopher Tate7060b042014-06-09 19:50:00 -0700543 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800544 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -0700545 }
Christopher Tate7060b042014-06-09 19:50:00 -0700546 }
547
Shreyas Basarge5db09082016-01-07 13:38:29 +0000548 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700549 for (int i=0; i<mActiveServices.size(); i++) {
550 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700551 final JobStatus executing = jsc.getRunningJob();
552 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000553 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700554 return true;
555 }
556 }
557 return false;
558 }
559
560 /**
561 * @param job JobStatus we are querying against.
562 * @return Whether or not the job represented by the status object is currently being run or
563 * is pending.
564 */
565 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700566 for (int i=0; i<mActiveServices.size(); i++) {
567 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700568 final JobStatus running = serviceContext.getRunningJob();
569 if (running != null && running.matches(job.getUid(), job.getJobId())) {
570 return true;
571 }
572 }
573 return false;
574 }
575
576 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700577 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
578 * specify an override deadline on a failed job (the failed job will run even though it's not
579 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
580 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
581 *
Christopher Tate7060b042014-06-09 19:50:00 -0700582 * @param failureToReschedule Provided job status that we will reschedule.
583 * @return A newly instantiated JobStatus with the same constraints as the last job except
584 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700585 *
586 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700587 */
588 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
589 final long elapsedNowMillis = SystemClock.elapsedRealtime();
590 final JobInfo job = failureToReschedule.getJob();
591
592 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700593 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
594 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700595
596 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700597 case JobInfo.BACKOFF_POLICY_LINEAR:
598 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700599 break;
600 default:
601 if (DEBUG) {
602 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
603 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700604 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
605 delayMillis =
606 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700607 break;
608 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700609 delayMillis =
610 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800611 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -0700612 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800613 for (int ic=0; ic<mControllers.size(); ic++) {
614 StateController controller = mControllers.get(ic);
615 controller.rescheduleForFailure(newJob, failureToReschedule);
616 }
617 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -0700618 }
619
620 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700621 * Called after a periodic has executed so we can reschedule it. We take the last execution
622 * time of the job to be the time of completion (i.e. the time at which this function is
623 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700624 * This could be inaccurate b/c the job can run for as long as
625 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
626 * to underscheduling at least, rather than if we had taken the last execution time to be the
627 * start of the execution.
628 * @return A new job representing the execution criteria for this instantiation of the
629 * recurring job.
630 */
631 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
632 final long elapsedNow = SystemClock.elapsedRealtime();
633 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700634 long runEarly = 0L;
635
636 // If this periodic was rescheduled it won't have a deadline.
637 if (periodicToReschedule.hasDeadlineConstraint()) {
638 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
639 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000640 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700641 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000642 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
643 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -0700644
645 if (DEBUG) {
646 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
647 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
648 }
649 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
650 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
651 }
652
653 // JobCompletedListener implementations.
654
655 /**
656 * A job just finished executing. We fetch the
657 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
658 * whether we want to reschedule we readd it to the controllers.
659 * @param jobStatus Completed job.
660 * @param needsReschedule Whether the implementing class should reschedule this job.
661 */
662 @Override
663 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
664 if (DEBUG) {
665 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
666 }
Shreyas Basarge73f10252016-02-11 17:06:13 +0000667 // Do not write back immediately if this is a periodic job. The job may get lost if system
668 // shuts down before it is added back.
669 if (!stopTrackingJob(jobStatus, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700670 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700671 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700672 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800673 // We still want to check for jobs to execute, because this job may have
674 // scheduled a new job under the same job id, and now we can run it.
675 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700676 return;
677 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800678 // Note: there is a small window of time in here where, when rescheduling a job,
679 // we will stop monitoring its content providers. This should be fixed by stopping
680 // the old job after scheduling the new one, but since we have no lock held here
681 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -0700682 if (needsReschedule) {
683 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800684 startTrackingJob(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700685 } else if (jobStatus.getJob().isPeriodic()) {
686 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800687 startTrackingJob(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700688 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000689 reportActive();
690 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700691 }
692
693 // StateChangedListener implementations.
694
695 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700696 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
697 * some controller's state has changed, so as to run through the list of jobs and start/stop
698 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700699 */
700 @Override
701 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700702 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700703 }
704
705 @Override
706 public void onRunJobNow(JobStatus jobStatus) {
707 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
708 }
709
Christopher Tate7060b042014-06-09 19:50:00 -0700710 private class JobHandler extends Handler {
711
712 public JobHandler(Looper looper) {
713 super(looper);
714 }
715
716 @Override
717 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800718 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700719 if (!mReadyToRock) {
720 return;
721 }
722 }
Christopher Tate7060b042014-06-09 19:50:00 -0700723 switch (message.what) {
724 case MSG_JOB_EXPIRED:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800725 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700726 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700727 // runNow can be null, which is a controller's way of indicating that its
728 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700729 if (runNow != null && !mPendingJobs.contains(runNow)
730 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700731 mPendingJobs.add(runNow);
732 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700733 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700734 }
Christopher Tate7060b042014-06-09 19:50:00 -0700735 break;
736 case MSG_CHECK_JOB:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800737 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000738 if (mReportedActive) {
739 // if jobs are currently being run, queue all ready jobs for execution.
740 queueReadyJobsForExecutionLockedH();
741 } else {
742 // Check the list of jobs and run some of them if we feel inclined.
743 maybeQueueReadyJobsForExecutionLockedH();
744 }
745 }
746 break;
747 case MSG_CHECK_JOB_GREEDY:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800748 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000749 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700750 }
Christopher Tate7060b042014-06-09 19:50:00 -0700751 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700752 case MSG_STOP_JOB:
753 cancelJobImpl((JobStatus)message.obj);
754 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700755 }
756 maybeRunPendingJobsH();
757 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
758 removeMessages(MSG_CHECK_JOB);
759 }
760
761 /**
762 * Run through list of jobs and execute all possible - at least one is expired so we do
763 * as many as we can.
764 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700765 private void queueReadyJobsForExecutionLockedH() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700766 if (DEBUG) {
767 Slog.d(TAG, "queuing all ready jobs for execution:");
768 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800769 mPendingJobs.clear();
770 mJobs.forEachJob(mReadyQueueFunctor);
771 mReadyQueueFunctor.postProcess();
772
Matthew Williams48a30db2014-09-23 13:39:36 -0700773 if (DEBUG) {
774 final int queuedJobs = mPendingJobs.size();
775 if (queuedJobs == 0) {
776 Slog.d(TAG, "No jobs pending.");
777 } else {
778 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700779 }
Christopher Tate7060b042014-06-09 19:50:00 -0700780 }
781 }
782
Christopher Tate2f36fd62016-02-18 18:36:08 -0800783 class ReadyJobQueueFunctor implements JobStatusFunctor {
784 ArrayList<JobStatus> newReadyJobs;
785
786 @Override
787 public void process(JobStatus job) {
788 if (isReadyToBeExecutedLocked(job)) {
789 if (DEBUG) {
790 Slog.d(TAG, " queued " + job.toShortString());
791 }
792 if (newReadyJobs == null) {
793 newReadyJobs = new ArrayList<JobStatus>();
794 }
795 newReadyJobs.add(job);
796 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
797 stopJobOnServiceContextLocked(job,
798 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
799 }
800 }
801
802 public void postProcess() {
803 if (newReadyJobs != null) {
804 mPendingJobs.addAll(newReadyJobs);
805 }
806 newReadyJobs = null;
807 }
808 }
809 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
810
Christopher Tate7060b042014-06-09 19:50:00 -0700811 /**
812 * The state of at least one job has changed. Here is where we could enforce various
813 * policies on when we want to execute jobs.
814 * Right now the policy is such:
815 * If >1 of the ready jobs is idle mode we send all of them off
816 * if more than 2 network connectivity jobs are ready we send them all off.
817 * If more than 4 jobs total are ready we send them all off.
818 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
819 */
Christopher Tate2f36fd62016-02-18 18:36:08 -0800820 class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
821 int chargingCount;
822 int idleCount;
823 int backoffCount;
824 int connectivityCount;
825 int contentCount;
826 List<JobStatus> runnableJobs;
827
828 public MaybeReadyJobQueueFunctor() {
829 reset();
830 }
831
832 // Functor method invoked for each job via JobStore.forEachJob()
833 @Override
834 public void process(JobStatus job) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700835 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700836 try {
837 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
838 job.getJob().getService().getPackageName())
839 == ActivityManager.APP_START_MODE_DISABLED) {
840 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
841 + job.getJob().toString() + " -- package not allowed to start");
842 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800843 return;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700844 }
845 } catch (RemoteException e) {
846 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700847 if (job.getNumFailures() > 0) {
848 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700849 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700850 if (job.hasIdleConstraint()) {
851 idleCount++;
852 }
853 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
854 connectivityCount++;
855 }
856 if (job.hasChargingConstraint()) {
857 chargingCount++;
858 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800859 if (job.hasContentTriggerConstraint()) {
860 contentCount++;
861 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700862 if (runnableJobs == null) {
863 runnableJobs = new ArrayList<>();
864 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700865 runnableJobs.add(job);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800866 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000867 stopJobOnServiceContextLocked(job,
868 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700869 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700870 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800871
872 public void postProcess() {
873 if (backoffCount > 0 ||
874 idleCount >= MIN_IDLE_COUNT ||
875 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
876 chargingCount >= MIN_CHARGING_COUNT ||
877 contentCount >= MIN_CONTENT_COUNT ||
878 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
879 if (DEBUG) {
880 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
881 }
882 mPendingJobs.addAll(runnableJobs);
883 } else {
884 if (DEBUG) {
885 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
886 }
Christopher Tate7060b042014-06-09 19:50:00 -0700887 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800888
889 // Be ready for next time
890 reset();
Matthew Williams48a30db2014-09-23 13:39:36 -0700891 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800892
893 private void reset() {
894 chargingCount = 0;
895 idleCount = 0;
896 backoffCount = 0;
897 connectivityCount = 0;
898 contentCount = 0;
899 runnableJobs = null;
900 }
901 }
902 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
903
904 private void maybeQueueReadyJobsForExecutionLockedH() {
905 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
906
907 mPendingJobs.clear();
908 mJobs.forEachJob(mMaybeQueueFunctor);
909 mMaybeQueueFunctor.postProcess();
Christopher Tate7060b042014-06-09 19:50:00 -0700910 }
911
912 /**
913 * Criteria for moving a job into the pending queue:
914 * - It's ready.
915 * - It's not pending.
916 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700917 * - The user that requested the job is running.
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700918 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -0700919 */
920 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700921 final boolean jobReady = job.isReady();
922 final boolean jobPending = mPendingJobs.contains(job);
923 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700924
925 final int userId = job.getUserId();
926 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
927 final boolean componentPresent;
928 try {
929 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
930 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
931 userId) != null);
932 } catch (RemoteException e) {
933 throw e.rethrowAsRuntimeException();
934 }
935
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700936 if (DEBUG) {
937 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
938 + " ready=" + jobReady + " pending=" + jobPending
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700939 + " active=" + jobActive + " userStarted=" + userStarted
940 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700941 }
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700942 return userStarted && componentPresent && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700943 }
944
945 /**
946 * Criteria for cancelling an active job:
947 * - It's not ready
948 * - It's running on a JSC.
949 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800950 private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -0700951 return !job.isReady() && isCurrentlyActiveLocked(job);
952 }
953
954 /**
955 * Reconcile jobs in the pending queue against available execution contexts.
956 * A controller can force a job into the pending queue even if it's already running, but
957 * here is where we decide whether to actually execute it.
958 */
959 private void maybeRunPendingJobsH() {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800960 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700961 if (mDeviceIdleMode) {
962 // If device is idle, we will not schedule jobs to run.
963 return;
964 }
Matthew Williams75fc5252014-09-02 16:17:53 -0700965 if (DEBUG) {
966 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
967 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800968 assignJobsToContextsLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800969 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700970 }
971 }
972 }
973
974 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +0000975 * Takes jobs from pending queue and runs them on available contexts.
976 * If no contexts are available, preempts lower priority jobs to
977 * run higher priority ones.
978 * Lock on mJobs before calling this function.
979 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800980 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000981 if (DEBUG) {
982 Slog.d(TAG, printPendingQueue());
983 }
984
985 // This array essentially stores the state of mActiveServices array.
986 // ith index stores the job present on the ith JobServiceContext.
987 // We manipulate this array until we arrive at what jobs should be running on
988 // what JobServiceContext.
989 JobStatus[] contextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
990 // Indicates whether we need to act on this jobContext id
991 boolean[] act = new boolean[MAX_JOB_CONTEXTS_COUNT];
992 int[] preferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
993 for (int i=0; i<mActiveServices.size(); i++) {
994 contextIdToJobMap[i] = mActiveServices.get(i).getRunningJob();
995 preferredUidForContext[i] = mActiveServices.get(i).getPreferredUid();
996 }
997 if (DEBUG) {
998 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
999 }
1000 Iterator<JobStatus> it = mPendingJobs.iterator();
1001 while (it.hasNext()) {
1002 JobStatus nextPending = it.next();
1003
1004 // If job is already running, go to next job.
1005 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1006 if (jobRunningContext != -1) {
1007 continue;
1008 }
1009
1010 // Find a context for nextPending. The context should be available OR
1011 // it should have lowest priority among all running jobs
1012 // (sharing the same Uid as nextPending)
1013 int minPriority = Integer.MAX_VALUE;
1014 int minPriorityContextId = -1;
1015 for (int i=0; i<mActiveServices.size(); i++) {
1016 JobStatus job = contextIdToJobMap[i];
1017 int preferredUid = preferredUidForContext[i];
1018 if (job == null && (preferredUid == nextPending.getUid() ||
1019 preferredUid == JobServiceContext.NO_PREFERRED_UID) ) {
1020 minPriorityContextId = i;
1021 break;
1022 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001023 if (job == null) {
1024 // No job on this context, but nextPending can't run here because
1025 // the context has a preferred Uid.
1026 continue;
1027 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001028 if (job.getUid() != nextPending.getUid()) {
1029 continue;
1030 }
1031 if (job.getPriority() >= nextPending.getPriority()) {
1032 continue;
1033 }
1034 if (minPriority > nextPending.getPriority()) {
1035 minPriority = nextPending.getPriority();
1036 minPriorityContextId = i;
1037 }
1038 }
1039 if (minPriorityContextId != -1) {
1040 contextIdToJobMap[minPriorityContextId] = nextPending;
1041 act[minPriorityContextId] = true;
1042 }
1043 }
1044 if (DEBUG) {
1045 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1046 }
1047 for (int i=0; i<mActiveServices.size(); i++) {
1048 boolean preservePreferredUid = false;
1049 if (act[i]) {
1050 JobStatus js = mActiveServices.get(i).getRunningJob();
1051 if (js != null) {
1052 if (DEBUG) {
1053 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
1054 }
1055 // preferredUid will be set to uid of currently running job.
1056 mActiveServices.get(i).preemptExecutingJob();
1057 preservePreferredUid = true;
1058 } else {
1059 if (DEBUG) {
1060 Slog.d(TAG, "About to run job on context "
1061 + String.valueOf(i) + ", job: " + contextIdToJobMap[i]);
1062 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001063 for (int ic=0; ic<mControllers.size(); ic++) {
1064 StateController controller = mControllers.get(ic);
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001065 controller.prepareForExecutionLocked(contextIdToJobMap[i]);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001066 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001067 if (!mActiveServices.get(i).executeRunnableJob(contextIdToJobMap[i])) {
1068 Slog.d(TAG, "Error executing " + contextIdToJobMap[i]);
1069 }
1070 mPendingJobs.remove(contextIdToJobMap[i]);
1071 }
1072 }
1073 if (!preservePreferredUid) {
1074 mActiveServices.get(i).clearPreferredUid();
1075 }
1076 }
1077 }
1078
1079 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1080 for (int i=0; i<map.length; i++) {
1081 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1082 return i;
1083 }
1084 }
1085 return -1;
1086 }
1087
1088 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001089 * Binder stub trampoline implementation
1090 */
1091 final class JobSchedulerStub extends IJobScheduler.Stub {
1092 /** Cache determination of whether a given app can persist jobs
1093 * key is uid of the calling app; value is undetermined/true/false
1094 */
1095 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1096
1097 // Enforce that only the app itself (or shared uid participant) can schedule a
1098 // job that runs one of the app's services, as well as verifying that the
1099 // named service properly requires the BIND_JOB_SERVICE permission
1100 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001101 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001102 final ComponentName service = job.getService();
1103 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001104 ServiceInfo si = pm.getServiceInfo(service,
1105 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001106 if (si == null) {
1107 throw new IllegalArgumentException("No such service " + service);
1108 }
Christopher Tate7060b042014-06-09 19:50:00 -07001109 if (si.applicationInfo.uid != uid) {
1110 throw new IllegalArgumentException("uid " + uid +
1111 " cannot schedule job in " + service.getPackageName());
1112 }
1113 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1114 throw new IllegalArgumentException("Scheduled service " + service
1115 + " does not require android.permission.BIND_JOB_SERVICE permission");
1116 }
Christopher Tate5568f542014-06-18 13:53:31 -07001117 } catch (RemoteException e) {
1118 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001119 }
1120 }
1121
1122 private boolean canPersistJobs(int pid, int uid) {
1123 // If we get this far we're good to go; all we need to do now is check
1124 // whether the app is allowed to persist its scheduled work.
1125 final boolean canPersist;
1126 synchronized (mPersistCache) {
1127 Boolean cached = mPersistCache.get(uid);
1128 if (cached != null) {
1129 canPersist = cached.booleanValue();
1130 } else {
1131 // Persisting jobs is tantamount to running at boot, so we permit
1132 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1133 // permission
1134 int result = getContext().checkPermission(
1135 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1136 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1137 mPersistCache.put(uid, canPersist);
1138 }
1139 }
1140 return canPersist;
1141 }
1142
1143 // IJobScheduler implementation
1144 @Override
1145 public int schedule(JobInfo job) throws RemoteException {
1146 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001147 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001148 }
1149 final int pid = Binder.getCallingPid();
1150 final int uid = Binder.getCallingUid();
1151
1152 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001153 if (job.isPersisted()) {
1154 if (!canPersistJobs(pid, uid)) {
1155 throw new IllegalArgumentException("Error: requested job be persisted without"
1156 + " holding RECEIVE_BOOT_COMPLETED permission.");
1157 }
1158 }
Christopher Tate7060b042014-06-09 19:50:00 -07001159
1160 long ident = Binder.clearCallingIdentity();
1161 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001162 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001163 } finally {
1164 Binder.restoreCallingIdentity(ident);
1165 }
1166 }
1167
1168 @Override
Shreyas Basarge968ac752016-01-11 23:09:26 +00001169 public int scheduleAsPackage(JobInfo job, String packageName, int userId)
1170 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001171 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001172 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001173 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1174 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001175 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001176
1177 if (packageName == null) {
1178 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001179 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001180
1181 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1182 android.Manifest.permission.UPDATE_DEVICE_STATS);
1183 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1184 throw new SecurityException("Caller uid " + callerUid
1185 + " not permitted to schedule jobs for other apps");
1186 }
1187
Shreyas Basarge968ac752016-01-11 23:09:26 +00001188 long ident = Binder.clearCallingIdentity();
1189 try {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001190 return JobSchedulerService.this.scheduleAsPackage(job, callerUid,
1191 packageName, userId);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001192 } finally {
1193 Binder.restoreCallingIdentity(ident);
1194 }
1195 }
1196
1197 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001198 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1199 final int uid = Binder.getCallingUid();
1200
1201 long ident = Binder.clearCallingIdentity();
1202 try {
1203 return JobSchedulerService.this.getPendingJobs(uid);
1204 } finally {
1205 Binder.restoreCallingIdentity(ident);
1206 }
1207 }
1208
1209 @Override
1210 public void cancelAll() throws RemoteException {
1211 final int uid = Binder.getCallingUid();
1212
1213 long ident = Binder.clearCallingIdentity();
1214 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001215 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001216 } finally {
1217 Binder.restoreCallingIdentity(ident);
1218 }
1219 }
1220
1221 @Override
1222 public void cancel(int jobId) throws RemoteException {
1223 final int uid = Binder.getCallingUid();
1224
1225 long ident = Binder.clearCallingIdentity();
1226 try {
1227 JobSchedulerService.this.cancelJob(uid, jobId);
1228 } finally {
1229 Binder.restoreCallingIdentity(ident);
1230 }
1231 }
1232
1233 /**
1234 * "dumpsys" infrastructure
1235 */
1236 @Override
1237 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1238 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1239
1240 long identityToken = Binder.clearCallingIdentity();
1241 try {
1242 JobSchedulerService.this.dumpInternal(pw);
1243 } finally {
1244 Binder.restoreCallingIdentity(identityToken);
1245 }
1246 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001247 };
1248
1249 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1250 StringBuilder s = new StringBuilder(initial + ": ");
1251 for (int i=0; i<map.length; i++) {
1252 s.append("(")
1253 .append(map[i] == null? -1: map[i].getJobId())
1254 .append(map[i] == null? -1: map[i].getUid())
1255 .append(")" );
1256 }
1257 return s.toString();
1258 }
1259
1260 private String printPendingQueue() {
1261 StringBuilder s = new StringBuilder("Pending queue: ");
1262 Iterator<JobStatus> it = mPendingJobs.iterator();
1263 while (it.hasNext()) {
1264 JobStatus js = it.next();
1265 s.append("(")
1266 .append(js.getJob().getId())
1267 .append(", ")
1268 .append(js.getUid())
1269 .append(") ");
1270 }
1271 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001272 }
Christopher Tate7060b042014-06-09 19:50:00 -07001273
Christopher Tate2f36fd62016-02-18 18:36:08 -08001274 void dumpInternal(final PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001275 final long now = SystemClock.elapsedRealtime();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001276 synchronized (mLock) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001277 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Christopher Tate7060b042014-06-09 19:50:00 -07001278 pw.println("Registered jobs:");
1279 if (mJobs.size() > 0) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001280 mJobs.forEachJob(new JobStatusFunctor() {
1281 private int index = 0;
1282
1283 @Override
1284 public void process(JobStatus job) {
1285 pw.print(" Job #"); pw.print(index++); pw.print(": ");
1286 pw.println(job.toShortString());
1287 job.dump(pw, " ");
1288 pw.print(" Ready: ");
1289 pw.print(mHandler.isReadyToBeExecutedLocked(job));
1290 pw.print(" (job=");
1291 pw.print(job.isReady());
1292 pw.print(" pending=");
1293 pw.print(mPendingJobs.contains(job));
1294 pw.print(" active=");
1295 pw.print(isCurrentlyActiveLocked(job));
1296 pw.print(" user=");
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001297 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Christopher Tate2f36fd62016-02-18 18:36:08 -08001298 pw.println(")");
1299 }
1300 });
Christopher Tate7060b042014-06-09 19:50:00 -07001301 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001302 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001303 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001304 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001305 pw.println();
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001306 mControllers.get(i).dumpControllerStateLocked(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001307 }
1308 pw.println();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001309 pw.println(printPendingQueue());
Christopher Tate7060b042014-06-09 19:50:00 -07001310 pw.println();
1311 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001312 for (int i=0; i<mActiveServices.size(); i++) {
1313 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001314 if (jsc.getRunningJob() == null) {
Christopher Tate7060b042014-06-09 19:50:00 -07001315 continue;
1316 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001317 final long timeout = jsc.getTimeoutElapsed();
1318 pw.print("Running for: ");
1319 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1320 pw.print("s timeout=");
1321 pw.print(timeout);
1322 pw.print(" fromnow=");
1323 pw.println(timeout-now);
1324 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -07001325 }
1326 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001327 pw.println();
1328 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001329 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001330 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001331 }
1332 pw.println();
1333 }
1334}