blob: f1d7b36a98b65ab06acf5328e4a77b5195588d48 [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;
22import java.util.Iterator;
23import java.util.List;
24
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070025import android.app.ActivityManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070026import android.app.ActivityManagerNative;
Christopher Tate5568f542014-06-18 13:53:31 -070027import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000030import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070031import android.app.job.JobScheduler;
32import android.app.job.JobService;
Shreyas Basarge5db09082016-01-07 13:38:29 +000033import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070034import android.content.BroadcastReceiver;
35import android.content.ComponentName;
36import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070039import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070040import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.content.pm.ServiceInfo;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070042import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070043import android.os.Binder;
44import android.os.Handler;
45import android.os.Looper;
46import android.os.Message;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070047import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070048import android.os.RemoteException;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070049import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070050import android.os.SystemClock;
51import android.os.UserHandle;
52import android.util.Slog;
53import android.util.SparseArray;
54
Dianne Hackborn1085ff62016-02-23 17:04:58 -080055import android.util.SparseBooleanArray;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070056import com.android.internal.app.IBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080057import com.android.server.DeviceIdleController;
58import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080059import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080060import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070061import com.android.server.job.controllers.BatteryController;
62import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080063import com.android.server.job.controllers.ContentObserverController;
Christopher Tate7060b042014-06-09 19:50:00 -070064import com.android.server.job.controllers.IdleController;
65import com.android.server.job.controllers.JobStatus;
66import com.android.server.job.controllers.StateController;
67import com.android.server.job.controllers.TimeController;
68
Christopher Tate7060b042014-06-09 19:50:00 -070069/**
70 * Responsible for taking jobs representing work to be performed by a client app, and determining
71 * based on the criteria specified when that job should be run against the client application's
72 * endpoint.
73 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
74 * about constraints, or the state of active jobs. It receives callbacks from the various
75 * controllers and completed jobs and operates accordingly.
76 *
77 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
78 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
79 * @hide
80 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -080081public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070082 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -080083 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -070084 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -080085
Christopher Tate7060b042014-06-09 19:50:00 -070086 /** The number of concurrent jobs we run at one time. */
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070087 private static final int MAX_JOB_CONTEXTS_COUNT
Shreyas Basarge8c834c02016-01-07 13:53:16 +000088 = ActivityManager.isLowRamDeviceStatic() ? 3 : 6;
Christopher Tatedabdf6f2016-02-24 12:30:22 -080089 /** Enforce a per-app limit on scheduled jobs? */
90 private static final boolean ENFORCE_MAX_JOBS = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -080091 /** The maximum number of jobs that we allow an unprivileged app to schedule */
92 private static final int MAX_JOBS_PER_APP = 100;
93
Dianne Hackborn33d31c52016-02-16 10:30:33 -080094 /** Global local for all job scheduler state. */
95 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -070096 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070097 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -070098
99 static final int MSG_JOB_EXPIRED = 0;
100 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700101 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000102 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700103
104 // Policy constants
105 /**
106 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
107 * early.
108 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700109 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -0700110 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700111 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
112 * early.
113 */
114 static final int MIN_CHARGING_COUNT = 1;
115 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700116 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
117 * things early.
118 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700119 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700120 /**
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800121 * Minimum # of content trigger jobs that must be ready in order to force the JMS to schedule
122 * things early.
123 */
124 static final int MIN_CONTENT_COUNT = 1;
125 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700126 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
127 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700128 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700129 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700130 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700131
132 /**
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;
Christopher Tate7060b042014-06-09 19:50:00 -0700139 /**
140 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
141 * when ready to execute them.
142 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700143 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700144
Shreyas Basarge5db09082016-01-07 13:38:29 +0000145 final ArrayList<Integer> mStartedUsers = new ArrayList<>();
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700146
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700147 final JobHandler mHandler;
148 final JobSchedulerStub mJobSchedulerStub;
149
150 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700151 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800152 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700153
154 /**
155 * Set to true once we are allowed to run third party apps.
156 */
157 boolean mReadyToRock;
158
Christopher Tate7060b042014-06-09 19:50:00 -0700159 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700160 * True when in device idle mode, so we don't want to schedule any jobs.
161 */
162 boolean mDeviceIdleMode;
163
164 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800165 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800166 */
167 boolean mReportedActive;
168
169 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800170 * Which uids are currently in the foreground.
171 */
172 final SparseBooleanArray mForegroundUids = new SparseBooleanArray();
173
174 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700175 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
176 * still clean up. On reinstall the package will have a new uid.
177 */
178 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
179 @Override
180 public void onReceive(Context context, Intent intent) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000181 Slog.d(TAG, "Receieved: " + intent.getAction());
182 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700183 // If this is an outright uninstall rather than the first half of an
184 // app update sequence, cancel the jobs associated with the app.
185 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
186 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
187 if (DEBUG) {
188 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
189 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700190 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700191 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000192 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700193 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
194 if (DEBUG) {
195 Slog.d(TAG, "Removing jobs for user: " + userId);
196 }
197 cancelJobsForUser(userId);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000198 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())
199 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700200 updateIdleMode(mPowerManager != null
201 ? (mPowerManager.isDeviceIdleMode()
Shreyas Basarge5db09082016-01-07 13:38:29 +0000202 || mPowerManager.isLightDeviceIdleMode())
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700203 : false);
Christopher Tate7060b042014-06-09 19:50:00 -0700204 }
205 }
206 };
207
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700208 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
209 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800210 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700211 }
212
213 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800214 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700215 }
216
217 @Override public void onUidActive(int uid) throws RemoteException {
218 }
219
220 @Override public void onUidIdle(int uid) throws RemoteException {
221 cancelJobsForUid(uid, false);
222 }
223 };
224
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800225 public Object getLock() {
226 return mLock;
227 }
228
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700229 @Override
230 public void onStartUser(int userHandle) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000231 mStartedUsers.add(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) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000238 mStartedUsers.remove(Integer.valueOf(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) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800249 return scheduleAsPackage(job, uId, null, -1, null);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000250 }
251
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800252 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId,
253 String tag) {
254 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700255 try {
256 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
257 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
258 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
259 + " -- package not allowed to start");
260 return JobScheduler.RESULT_FAILURE;
261 }
262 } catch (RemoteException e) {
263 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800264 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
265 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800266 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800267 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800268 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800269 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
270 Slog.w(TAG, "Too many jobs for uid " + uId);
271 throw new IllegalStateException("Apps may not schedule more than "
272 + MAX_JOBS_PER_APP + " distinct jobs");
273 }
274 }
275
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800276 toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
277 }
278 startTrackingJob(jobStatus, toCancel);
279 if (toCancel != null) {
280 cancelJobImpl(toCancel);
281 }
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700282 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700283 return JobScheduler.RESULT_SUCCESS;
284 }
285
286 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800287 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800288 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
289 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
290 for (int i = jobs.size() - 1; i >= 0; i--) {
291 JobStatus job = jobs.get(i);
292 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700293 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800294 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700295 }
Christopher Tate7060b042014-06-09 19:50:00 -0700296 }
297
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700298 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700299 List<JobStatus> jobsForUser;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800300 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700301 jobsForUser = mJobs.getJobsByUser(userHandle);
302 }
303 for (int i=0; i<jobsForUser.size(); i++) {
304 JobStatus toRemove = jobsForUser.get(i);
305 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700306 }
307 }
308
309 /**
310 * Entry point from client to cancel all jobs originating from their uid.
311 * This will remove the job from the master list, and cancel the job if it was staged for
312 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700313 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700314 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
315 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700316 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700317 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700318 List<JobStatus> jobsForUid;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800319 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700320 jobsForUid = mJobs.getJobsByUid(uid);
321 }
322 for (int i=0; i<jobsForUid.size(); i++) {
323 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700324 if (!forceAll) {
325 String packageName = toRemove.getServiceComponent().getPackageName();
326 try {
327 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
328 != ActivityManager.APP_START_MODE_DISABLED) {
329 continue;
330 }
331 } catch (RemoteException e) {
332 }
333 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700334 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700335 }
336 }
337
338 /**
339 * Entry point from client to cancel the job corresponding to the jobId provided.
340 * This will remove the job from the master list, and cancel the job if it was staged for
341 * execution or being executed.
342 * @param uid Uid of the calling client.
343 * @param jobId Id of the job, provided at schedule-time.
344 */
345 public void cancelJob(int uid, int jobId) {
346 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800347 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700348 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700349 }
350 if (toCancel != null) {
351 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700352 }
353 }
354
Matthew Williams48a30db2014-09-23 13:39:36 -0700355 private void cancelJobImpl(JobStatus cancelled) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800356 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Shreyas Basarge73f10252016-02-11 17:06:13 +0000357 stopTrackingJob(cancelled, true /* writeBack */);
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800358 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700359 // Remove from pending queue.
360 mPendingJobs.remove(cancelled);
361 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000362 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800363 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700364 }
Christopher Tate7060b042014-06-09 19:50:00 -0700365 }
366
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800367 void updateUidState(int uid, int procState) {
368 synchronized (mLock) {
369 boolean foreground = procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
370 boolean changed = false;
371 if (foreground) {
372 if (!mForegroundUids.get(uid)) {
373 changed = true;
374 mForegroundUids.put(uid, true);
375 }
376 } else {
377 int index = mForegroundUids.indexOfKey(uid);
378 if (index >= 0) {
379 mForegroundUids.removeAt(index);
380 changed = true;
381 }
382 }
383 }
384 }
385
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700386 void updateIdleMode(boolean enabled) {
387 boolean changed = false;
388 boolean rocking;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800389 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700390 if (mDeviceIdleMode != enabled) {
391 changed = true;
392 }
393 rocking = mReadyToRock;
394 }
395 if (changed) {
396 if (rocking) {
397 for (int i=0; i<mControllers.size(); i++) {
398 mControllers.get(i).deviceIdleModeChanged(enabled);
399 }
400 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800401 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700402 mDeviceIdleMode = enabled;
403 if (enabled) {
404 // When becoming idle, make sure no jobs are actively running.
405 for (int i=0; i<mActiveServices.size(); i++) {
406 JobServiceContext jsc = mActiveServices.get(i);
407 final JobStatus executing = jsc.getRunningJob();
408 if (executing != null) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000409 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700410 }
411 }
412 } else {
413 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800414 if (rocking) {
415 if (mLocalDeviceIdleController != null) {
416 if (!mReportedActive) {
417 mReportedActive = true;
418 mLocalDeviceIdleController.setJobsActive(true);
419 }
420 }
421 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700422 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
423 }
424 }
425 }
426 }
427
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800428 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000429 // active is true if pending queue contains jobs OR some job is running.
430 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800431 if (mPendingJobs.size() <= 0) {
432 for (int i=0; i<mActiveServices.size(); i++) {
433 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000434 if (jsc.getRunningJob() != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800435 active = true;
436 break;
437 }
438 }
439 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000440
441 if (mReportedActive != active) {
442 mReportedActive = active;
443 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800444 mLocalDeviceIdleController.setJobsActive(active);
445 }
446 }
447 }
448
Christopher Tate7060b042014-06-09 19:50:00 -0700449 /**
450 * Initializes the system service.
451 * <p>
452 * Subclasses must define a single argument constructor that accepts the context
453 * and passes it to super.
454 * </p>
455 *
456 * @param context The system server context.
457 */
458 public JobSchedulerService(Context context) {
459 super(context);
460 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700461 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700462 mControllers.add(ConnectivityController.get(this));
463 mControllers.add(TimeController.get(this));
464 mControllers.add(IdleController.get(this));
465 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800466 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800467 mControllers.add(ContentObserverController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700468
469 mHandler = new JobHandler(context.getMainLooper());
470 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700471 mJobs = JobStore.initAndGet(this);
472 }
473
474 @Override
475 public void onStart() {
476 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
477 }
478
479 @Override
480 public void onBootPhase(int phase) {
481 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000482 // Register br for package removals and user removals.
Christopher Tate7060b042014-06-09 19:50:00 -0700483 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
484 filter.addDataScheme("package");
485 getContext().registerReceiverAsUser(
486 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
487 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700488 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700489 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700490 getContext().registerReceiverAsUser(
491 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000492 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700493 try {
494 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800495 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
496 | ActivityManager.UID_OBSERVER_IDLE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700497 } catch (RemoteException e) {
498 // ignored; both services live in system_server
499 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700500 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800501 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700502 // Let's go!
503 mReadyToRock = true;
504 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
505 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800506 mLocalDeviceIdleController
507 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700508 // Create the "runners".
509 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
510 mActiveServices.add(
511 new JobServiceContext(this, mBatteryStats,
512 getContext().getMainLooper()));
513 }
514 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -0800515 mJobs.forEachJob(new JobStatusFunctor() {
516 @Override
517 public void process(JobStatus job) {
518 for (int controller = 0; controller < mControllers.size(); controller++) {
519 final StateController sc = mControllers.get(controller);
520 sc.deviceIdleModeChanged(mDeviceIdleMode);
521 sc.maybeStartTrackingJobLocked(job, null);
522 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700523 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800524 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700525 // GO GO GO!
526 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
527 }
Christopher Tate7060b042014-06-09 19:50:00 -0700528 }
529 }
530
531 /**
532 * Called when we have a job status object that we need to insert in our
533 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
534 * about.
535 */
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800536 private void startTrackingJob(JobStatus jobStatus, JobStatus lastJob) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800537 synchronized (mLock) {
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800538 final boolean update = mJobs.add(jobStatus);
539 if (mReadyToRock) {
540 for (int i = 0; i < mControllers.size(); i++) {
541 StateController controller = mControllers.get(i);
542 if (update) {
543 controller.maybeStopTrackingJobLocked(jobStatus, true);
544 }
545 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700546 }
Christopher Tate7060b042014-06-09 19:50:00 -0700547 }
Christopher Tate7060b042014-06-09 19:50:00 -0700548 }
549 }
550
551 /**
552 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
553 * object removed.
554 */
Shreyas Basarge73f10252016-02-11 17:06:13 +0000555 private boolean stopTrackingJob(JobStatus jobStatus, boolean writeBack) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800556 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700557 // Remove from store as well as controllers.
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800558 final boolean removed = mJobs.remove(jobStatus, writeBack);
559 if (removed && mReadyToRock) {
560 for (int i=0; i<mControllers.size(); i++) {
561 StateController controller = mControllers.get(i);
562 controller.maybeStopTrackingJobLocked(jobStatus, false);
563 }
Christopher Tate7060b042014-06-09 19:50:00 -0700564 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800565 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -0700566 }
Christopher Tate7060b042014-06-09 19:50:00 -0700567 }
568
Shreyas Basarge5db09082016-01-07 13:38:29 +0000569 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700570 for (int i=0; i<mActiveServices.size(); i++) {
571 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700572 final JobStatus executing = jsc.getRunningJob();
573 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000574 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700575 return true;
576 }
577 }
578 return false;
579 }
580
581 /**
582 * @param job JobStatus we are querying against.
583 * @return Whether or not the job represented by the status object is currently being run or
584 * is pending.
585 */
586 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700587 for (int i=0; i<mActiveServices.size(); i++) {
588 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700589 final JobStatus running = serviceContext.getRunningJob();
590 if (running != null && running.matches(job.getUid(), job.getJobId())) {
591 return true;
592 }
593 }
594 return false;
595 }
596
597 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700598 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
599 * specify an override deadline on a failed job (the failed job will run even though it's not
600 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
601 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
602 *
Christopher Tate7060b042014-06-09 19:50:00 -0700603 * @param failureToReschedule Provided job status that we will reschedule.
604 * @return A newly instantiated JobStatus with the same constraints as the last job except
605 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700606 *
607 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700608 */
609 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
610 final long elapsedNowMillis = SystemClock.elapsedRealtime();
611 final JobInfo job = failureToReschedule.getJob();
612
613 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700614 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
615 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700616
617 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700618 case JobInfo.BACKOFF_POLICY_LINEAR:
619 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700620 break;
621 default:
622 if (DEBUG) {
623 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
624 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700625 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
626 delayMillis =
627 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700628 break;
629 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700630 delayMillis =
631 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800632 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -0700633 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800634 for (int ic=0; ic<mControllers.size(); ic++) {
635 StateController controller = mControllers.get(ic);
636 controller.rescheduleForFailure(newJob, failureToReschedule);
637 }
638 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -0700639 }
640
641 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700642 * Called after a periodic has executed so we can reschedule it. We take the last execution
643 * time of the job to be the time of completion (i.e. the time at which this function is
644 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700645 * This could be inaccurate b/c the job can run for as long as
646 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
647 * to underscheduling at least, rather than if we had taken the last execution time to be the
648 * start of the execution.
649 * @return A new job representing the execution criteria for this instantiation of the
650 * recurring job.
651 */
652 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
653 final long elapsedNow = SystemClock.elapsedRealtime();
654 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700655 long runEarly = 0L;
656
657 // If this periodic was rescheduled it won't have a deadline.
658 if (periodicToReschedule.hasDeadlineConstraint()) {
659 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
660 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000661 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700662 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000663 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
664 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -0700665
666 if (DEBUG) {
667 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
668 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
669 }
670 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
671 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
672 }
673
674 // JobCompletedListener implementations.
675
676 /**
677 * A job just finished executing. We fetch the
678 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
679 * whether we want to reschedule we readd it to the controllers.
680 * @param jobStatus Completed job.
681 * @param needsReschedule Whether the implementing class should reschedule this job.
682 */
683 @Override
684 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
685 if (DEBUG) {
686 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
687 }
Shreyas Basarge73f10252016-02-11 17:06:13 +0000688 // Do not write back immediately if this is a periodic job. The job may get lost if system
689 // shuts down before it is added back.
690 if (!stopTrackingJob(jobStatus, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700691 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700692 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700693 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800694 // We still want to check for jobs to execute, because this job may have
695 // scheduled a new job under the same job id, and now we can run it.
696 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700697 return;
698 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800699 // Note: there is a small window of time in here where, when rescheduling a job,
700 // we will stop monitoring its content providers. This should be fixed by stopping
701 // the old job after scheduling the new one, but since we have no lock held here
702 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -0700703 if (needsReschedule) {
704 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800705 startTrackingJob(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700706 } else if (jobStatus.getJob().isPeriodic()) {
707 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800708 startTrackingJob(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700709 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000710 reportActive();
711 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700712 }
713
714 // StateChangedListener implementations.
715
716 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700717 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
718 * some controller's state has changed, so as to run through the list of jobs and start/stop
719 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700720 */
721 @Override
722 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700723 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700724 }
725
726 @Override
727 public void onRunJobNow(JobStatus jobStatus) {
728 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
729 }
730
Christopher Tate7060b042014-06-09 19:50:00 -0700731 private class JobHandler extends Handler {
732
733 public JobHandler(Looper looper) {
734 super(looper);
735 }
736
737 @Override
738 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800739 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700740 if (!mReadyToRock) {
741 return;
742 }
743 }
Christopher Tate7060b042014-06-09 19:50:00 -0700744 switch (message.what) {
745 case MSG_JOB_EXPIRED:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800746 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700747 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700748 // runNow can be null, which is a controller's way of indicating that its
749 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700750 if (runNow != null && !mPendingJobs.contains(runNow)
751 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700752 mPendingJobs.add(runNow);
753 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700754 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700755 }
Christopher Tate7060b042014-06-09 19:50:00 -0700756 break;
757 case MSG_CHECK_JOB:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800758 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000759 if (mReportedActive) {
760 // if jobs are currently being run, queue all ready jobs for execution.
761 queueReadyJobsForExecutionLockedH();
762 } else {
763 // Check the list of jobs and run some of them if we feel inclined.
764 maybeQueueReadyJobsForExecutionLockedH();
765 }
766 }
767 break;
768 case MSG_CHECK_JOB_GREEDY:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800769 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000770 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700771 }
Christopher Tate7060b042014-06-09 19:50:00 -0700772 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700773 case MSG_STOP_JOB:
774 cancelJobImpl((JobStatus)message.obj);
775 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700776 }
777 maybeRunPendingJobsH();
778 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
779 removeMessages(MSG_CHECK_JOB);
780 }
781
782 /**
783 * Run through list of jobs and execute all possible - at least one is expired so we do
784 * as many as we can.
785 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700786 private void queueReadyJobsForExecutionLockedH() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700787 if (DEBUG) {
788 Slog.d(TAG, "queuing all ready jobs for execution:");
789 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800790 mPendingJobs.clear();
791 mJobs.forEachJob(mReadyQueueFunctor);
792 mReadyQueueFunctor.postProcess();
793
Matthew Williams48a30db2014-09-23 13:39:36 -0700794 if (DEBUG) {
795 final int queuedJobs = mPendingJobs.size();
796 if (queuedJobs == 0) {
797 Slog.d(TAG, "No jobs pending.");
798 } else {
799 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700800 }
Christopher Tate7060b042014-06-09 19:50:00 -0700801 }
802 }
803
Christopher Tate2f36fd62016-02-18 18:36:08 -0800804 class ReadyJobQueueFunctor implements JobStatusFunctor {
805 ArrayList<JobStatus> newReadyJobs;
806
807 @Override
808 public void process(JobStatus job) {
809 if (isReadyToBeExecutedLocked(job)) {
810 if (DEBUG) {
811 Slog.d(TAG, " queued " + job.toShortString());
812 }
813 if (newReadyJobs == null) {
814 newReadyJobs = new ArrayList<JobStatus>();
815 }
816 newReadyJobs.add(job);
817 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
818 stopJobOnServiceContextLocked(job,
819 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
820 }
821 }
822
823 public void postProcess() {
824 if (newReadyJobs != null) {
825 mPendingJobs.addAll(newReadyJobs);
826 }
827 newReadyJobs = null;
828 }
829 }
830 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
831
Christopher Tate7060b042014-06-09 19:50:00 -0700832 /**
833 * The state of at least one job has changed. Here is where we could enforce various
834 * policies on when we want to execute jobs.
835 * Right now the policy is such:
836 * If >1 of the ready jobs is idle mode we send all of them off
837 * if more than 2 network connectivity jobs are ready we send them all off.
838 * If more than 4 jobs total are ready we send them all off.
839 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
840 */
Christopher Tate2f36fd62016-02-18 18:36:08 -0800841 class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
842 int chargingCount;
843 int idleCount;
844 int backoffCount;
845 int connectivityCount;
846 int contentCount;
847 List<JobStatus> runnableJobs;
848
849 public MaybeReadyJobQueueFunctor() {
850 reset();
851 }
852
853 // Functor method invoked for each job via JobStore.forEachJob()
854 @Override
855 public void process(JobStatus job) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700856 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700857 try {
858 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
859 job.getJob().getService().getPackageName())
860 == ActivityManager.APP_START_MODE_DISABLED) {
861 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
862 + job.getJob().toString() + " -- package not allowed to start");
863 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800864 return;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700865 }
866 } catch (RemoteException e) {
867 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700868 if (job.getNumFailures() > 0) {
869 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700870 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700871 if (job.hasIdleConstraint()) {
872 idleCount++;
873 }
874 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
875 connectivityCount++;
876 }
877 if (job.hasChargingConstraint()) {
878 chargingCount++;
879 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800880 if (job.hasContentTriggerConstraint()) {
881 contentCount++;
882 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700883 if (runnableJobs == null) {
884 runnableJobs = new ArrayList<>();
885 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700886 runnableJobs.add(job);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800887 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000888 stopJobOnServiceContextLocked(job,
889 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700890 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700891 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800892
893 public void postProcess() {
894 if (backoffCount > 0 ||
895 idleCount >= MIN_IDLE_COUNT ||
896 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
897 chargingCount >= MIN_CHARGING_COUNT ||
898 contentCount >= MIN_CONTENT_COUNT ||
899 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
900 if (DEBUG) {
901 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
902 }
903 mPendingJobs.addAll(runnableJobs);
904 } else {
905 if (DEBUG) {
906 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
907 }
Christopher Tate7060b042014-06-09 19:50:00 -0700908 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800909
910 // Be ready for next time
911 reset();
Matthew Williams48a30db2014-09-23 13:39:36 -0700912 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800913
914 private void reset() {
915 chargingCount = 0;
916 idleCount = 0;
917 backoffCount = 0;
918 connectivityCount = 0;
919 contentCount = 0;
920 runnableJobs = null;
921 }
922 }
923 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
924
925 private void maybeQueueReadyJobsForExecutionLockedH() {
926 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
927
928 mPendingJobs.clear();
929 mJobs.forEachJob(mMaybeQueueFunctor);
930 mMaybeQueueFunctor.postProcess();
Christopher Tate7060b042014-06-09 19:50:00 -0700931 }
932
933 /**
934 * Criteria for moving a job into the pending queue:
935 * - It's ready.
936 * - It's not pending.
937 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700938 * - The user that requested the job is running.
Christopher Tate7060b042014-06-09 19:50:00 -0700939 */
940 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700941 final boolean jobReady = job.isReady();
942 final boolean jobPending = mPendingJobs.contains(job);
943 final boolean jobActive = isCurrentlyActiveLocked(job);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000944 final boolean userRunning = mStartedUsers.contains(job.getUserId());
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700945 if (DEBUG) {
946 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
947 + " ready=" + jobReady + " pending=" + jobPending
Shreyas Basarge5db09082016-01-07 13:38:29 +0000948 + " active=" + jobActive + " userRunning=" + userRunning);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700949 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000950 return userRunning && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700951 }
952
953 /**
954 * Criteria for cancelling an active job:
955 * - It's not ready
956 * - It's running on a JSC.
957 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800958 private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -0700959 return !job.isReady() && isCurrentlyActiveLocked(job);
960 }
961
962 /**
963 * Reconcile jobs in the pending queue against available execution contexts.
964 * A controller can force a job into the pending queue even if it's already running, but
965 * here is where we decide whether to actually execute it.
966 */
967 private void maybeRunPendingJobsH() {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800968 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700969 if (mDeviceIdleMode) {
970 // If device is idle, we will not schedule jobs to run.
971 return;
972 }
Matthew Williams75fc5252014-09-02 16:17:53 -0700973 if (DEBUG) {
974 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
975 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800976 assignJobsToContextsLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800977 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700978 }
979 }
980 }
981
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800982 private int evaluateJobPriorityLocked(JobStatus job) {
983 int priority = job.getPriority();
984 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
985 return priority;
986 }
987 if (mForegroundUids.get(job.getSourceUid())) {
988 return JobInfo.PRIORITY_FOREGROUND_APP;
989 }
990 return priority;
991 }
992
Christopher Tate7060b042014-06-09 19:50:00 -0700993 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +0000994 * Takes jobs from pending queue and runs them on available contexts.
995 * If no contexts are available, preempts lower priority jobs to
996 * run higher priority ones.
997 * Lock on mJobs before calling this function.
998 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800999 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001000 if (DEBUG) {
1001 Slog.d(TAG, printPendingQueue());
1002 }
1003
1004 // This array essentially stores the state of mActiveServices array.
1005 // ith index stores the job present on the ith JobServiceContext.
1006 // We manipulate this array until we arrive at what jobs should be running on
1007 // what JobServiceContext.
1008 JobStatus[] contextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
1009 // Indicates whether we need to act on this jobContext id
1010 boolean[] act = new boolean[MAX_JOB_CONTEXTS_COUNT];
1011 int[] preferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
1012 for (int i=0; i<mActiveServices.size(); i++) {
1013 contextIdToJobMap[i] = mActiveServices.get(i).getRunningJob();
1014 preferredUidForContext[i] = mActiveServices.get(i).getPreferredUid();
1015 }
1016 if (DEBUG) {
1017 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1018 }
1019 Iterator<JobStatus> it = mPendingJobs.iterator();
1020 while (it.hasNext()) {
1021 JobStatus nextPending = it.next();
1022
1023 // If job is already running, go to next job.
1024 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1025 if (jobRunningContext != -1) {
1026 continue;
1027 }
1028
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001029 nextPending.lastEvaluatedPriority = evaluateJobPriorityLocked(nextPending);
1030
Shreyas Basarge5db09082016-01-07 13:38:29 +00001031 // Find a context for nextPending. The context should be available OR
1032 // it should have lowest priority among all running jobs
1033 // (sharing the same Uid as nextPending)
1034 int minPriority = Integer.MAX_VALUE;
1035 int minPriorityContextId = -1;
1036 for (int i=0; i<mActiveServices.size(); i++) {
1037 JobStatus job = contextIdToJobMap[i];
1038 int preferredUid = preferredUidForContext[i];
1039 if (job == null && (preferredUid == nextPending.getUid() ||
1040 preferredUid == JobServiceContext.NO_PREFERRED_UID) ) {
1041 minPriorityContextId = i;
1042 break;
1043 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001044 if (job == null) {
1045 // No job on this context, but nextPending can't run here because
1046 // the context has a preferred Uid.
1047 continue;
1048 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001049 if (job.getUid() != nextPending.getUid()) {
1050 continue;
1051 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001052 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001053 continue;
1054 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001055 if (minPriority > nextPending.lastEvaluatedPriority) {
1056 minPriority = nextPending.lastEvaluatedPriority;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001057 minPriorityContextId = i;
1058 }
1059 }
1060 if (minPriorityContextId != -1) {
1061 contextIdToJobMap[minPriorityContextId] = nextPending;
1062 act[minPriorityContextId] = true;
1063 }
1064 }
1065 if (DEBUG) {
1066 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1067 }
1068 for (int i=0; i<mActiveServices.size(); i++) {
1069 boolean preservePreferredUid = false;
1070 if (act[i]) {
1071 JobStatus js = mActiveServices.get(i).getRunningJob();
1072 if (js != null) {
1073 if (DEBUG) {
1074 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
1075 }
1076 // preferredUid will be set to uid of currently running job.
1077 mActiveServices.get(i).preemptExecutingJob();
1078 preservePreferredUid = true;
1079 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001080 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001081 if (DEBUG) {
1082 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001083 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001084 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001085 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001086 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001087 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001088 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1089 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001090 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001091 mPendingJobs.remove(pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001092 }
1093 }
1094 if (!preservePreferredUid) {
1095 mActiveServices.get(i).clearPreferredUid();
1096 }
1097 }
1098 }
1099
1100 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1101 for (int i=0; i<map.length; i++) {
1102 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1103 return i;
1104 }
1105 }
1106 return -1;
1107 }
1108
1109 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001110 * Binder stub trampoline implementation
1111 */
1112 final class JobSchedulerStub extends IJobScheduler.Stub {
1113 /** Cache determination of whether a given app can persist jobs
1114 * key is uid of the calling app; value is undetermined/true/false
1115 */
1116 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1117
1118 // Enforce that only the app itself (or shared uid participant) can schedule a
1119 // job that runs one of the app's services, as well as verifying that the
1120 // named service properly requires the BIND_JOB_SERVICE permission
1121 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001122 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001123 final ComponentName service = job.getService();
1124 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001125 ServiceInfo si = pm.getServiceInfo(service,
1126 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001127 if (si == null) {
1128 throw new IllegalArgumentException("No such service " + service);
1129 }
Christopher Tate7060b042014-06-09 19:50:00 -07001130 if (si.applicationInfo.uid != uid) {
1131 throw new IllegalArgumentException("uid " + uid +
1132 " cannot schedule job in " + service.getPackageName());
1133 }
1134 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1135 throw new IllegalArgumentException("Scheduled service " + service
1136 + " does not require android.permission.BIND_JOB_SERVICE permission");
1137 }
Christopher Tate5568f542014-06-18 13:53:31 -07001138 } catch (RemoteException e) {
1139 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001140 }
1141 }
1142
1143 private boolean canPersistJobs(int pid, int uid) {
1144 // If we get this far we're good to go; all we need to do now is check
1145 // whether the app is allowed to persist its scheduled work.
1146 final boolean canPersist;
1147 synchronized (mPersistCache) {
1148 Boolean cached = mPersistCache.get(uid);
1149 if (cached != null) {
1150 canPersist = cached.booleanValue();
1151 } else {
1152 // Persisting jobs is tantamount to running at boot, so we permit
1153 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1154 // permission
1155 int result = getContext().checkPermission(
1156 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1157 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1158 mPersistCache.put(uid, canPersist);
1159 }
1160 }
1161 return canPersist;
1162 }
1163
1164 // IJobScheduler implementation
1165 @Override
1166 public int schedule(JobInfo job) throws RemoteException {
1167 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001168 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001169 }
1170 final int pid = Binder.getCallingPid();
1171 final int uid = Binder.getCallingUid();
1172
1173 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001174 if (job.isPersisted()) {
1175 if (!canPersistJobs(pid, uid)) {
1176 throw new IllegalArgumentException("Error: requested job be persisted without"
1177 + " holding RECEIVE_BOOT_COMPLETED permission.");
1178 }
1179 }
Christopher Tate7060b042014-06-09 19:50:00 -07001180
1181 long ident = Binder.clearCallingIdentity();
1182 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001183 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001184 } finally {
1185 Binder.restoreCallingIdentity(ident);
1186 }
1187 }
1188
1189 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001190 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001191 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001192 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001193 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001194 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1195 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001196 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001197
1198 if (packageName == null) {
1199 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001200 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001201
1202 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1203 android.Manifest.permission.UPDATE_DEVICE_STATS);
1204 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1205 throw new SecurityException("Caller uid " + callerUid
1206 + " not permitted to schedule jobs for other apps");
1207 }
1208
Shreyas Basarge968ac752016-01-11 23:09:26 +00001209 long ident = Binder.clearCallingIdentity();
1210 try {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001211 return JobSchedulerService.this.scheduleAsPackage(job, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001212 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001213 } finally {
1214 Binder.restoreCallingIdentity(ident);
1215 }
1216 }
1217
1218 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001219 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1220 final int uid = Binder.getCallingUid();
1221
1222 long ident = Binder.clearCallingIdentity();
1223 try {
1224 return JobSchedulerService.this.getPendingJobs(uid);
1225 } finally {
1226 Binder.restoreCallingIdentity(ident);
1227 }
1228 }
1229
1230 @Override
1231 public void cancelAll() throws RemoteException {
1232 final int uid = Binder.getCallingUid();
1233
1234 long ident = Binder.clearCallingIdentity();
1235 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001236 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001237 } finally {
1238 Binder.restoreCallingIdentity(ident);
1239 }
1240 }
1241
1242 @Override
1243 public void cancel(int jobId) throws RemoteException {
1244 final int uid = Binder.getCallingUid();
1245
1246 long ident = Binder.clearCallingIdentity();
1247 try {
1248 JobSchedulerService.this.cancelJob(uid, jobId);
1249 } finally {
1250 Binder.restoreCallingIdentity(ident);
1251 }
1252 }
1253
1254 /**
1255 * "dumpsys" infrastructure
1256 */
1257 @Override
1258 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1259 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1260
1261 long identityToken = Binder.clearCallingIdentity();
1262 try {
1263 JobSchedulerService.this.dumpInternal(pw);
1264 } finally {
1265 Binder.restoreCallingIdentity(identityToken);
1266 }
1267 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001268 };
1269
1270 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1271 StringBuilder s = new StringBuilder(initial + ": ");
1272 for (int i=0; i<map.length; i++) {
1273 s.append("(")
1274 .append(map[i] == null? -1: map[i].getJobId())
1275 .append(map[i] == null? -1: map[i].getUid())
1276 .append(")" );
1277 }
1278 return s.toString();
1279 }
1280
1281 private String printPendingQueue() {
1282 StringBuilder s = new StringBuilder("Pending queue: ");
1283 Iterator<JobStatus> it = mPendingJobs.iterator();
1284 while (it.hasNext()) {
1285 JobStatus js = it.next();
1286 s.append("(")
1287 .append(js.getJob().getId())
1288 .append(", ")
1289 .append(js.getUid())
1290 .append(") ");
1291 }
1292 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001293 }
Christopher Tate7060b042014-06-09 19:50:00 -07001294
Christopher Tate2f36fd62016-02-18 18:36:08 -08001295 void dumpInternal(final PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001296 final long now = SystemClock.elapsedRealtime();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001297 synchronized (mLock) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001298 pw.print("Started users: ");
1299 for (int i=0; i<mStartedUsers.size(); i++) {
1300 pw.print("u" + mStartedUsers.get(i) + " ");
1301 }
1302 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07001303 pw.println("Registered jobs:");
1304 if (mJobs.size() > 0) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001305 mJobs.forEachJob(new JobStatusFunctor() {
1306 private int index = 0;
1307
1308 @Override
1309 public void process(JobStatus job) {
1310 pw.print(" Job #"); pw.print(index++); pw.print(": ");
1311 pw.println(job.toShortString());
1312 job.dump(pw, " ");
1313 pw.print(" Ready: ");
1314 pw.print(mHandler.isReadyToBeExecutedLocked(job));
1315 pw.print(" (job=");
1316 pw.print(job.isReady());
1317 pw.print(" pending=");
1318 pw.print(mPendingJobs.contains(job));
1319 pw.print(" active=");
1320 pw.print(isCurrentlyActiveLocked(job));
1321 pw.print(" user=");
1322 pw.print(mStartedUsers.contains(job.getUserId()));
1323 pw.println(")");
1324 }
1325 });
Christopher Tate7060b042014-06-09 19:50:00 -07001326 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001327 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001328 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001329 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001330 pw.println();
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001331 mControllers.get(i).dumpControllerStateLocked(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001332 }
1333 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001334 pw.println("Foreground uids:");
1335 for (int i=0; i<mForegroundUids.size(); i++) {
1336 pw.print(" "); pw.println(UserHandle.formatUid(mForegroundUids.keyAt(i)));
1337 }
1338 pw.println();
1339 pw.println("Pending queue:");
1340 for (int i=0; i<mPendingJobs.size(); i++) {
1341 JobStatus job = mPendingJobs.get(i);
1342 pw.print(" Pending #"); pw.print(i); pw.print(": ");
1343 pw.println(job.toShortString());
1344 int priority = evaluateJobPriorityLocked(job);
1345 if (priority != JobInfo.PRIORITY_DEFAULT) {
1346 pw.print(" Evaluated priority: "); pw.println(priority);
1347 }
1348 pw.print(" Tag: "); pw.println(job.getTag());
1349 }
Christopher Tate7060b042014-06-09 19:50:00 -07001350 pw.println();
1351 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001352 for (int i=0; i<mActiveServices.size(); i++) {
1353 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001354 if (jsc.getRunningJob() == null) {
Christopher Tate7060b042014-06-09 19:50:00 -07001355 continue;
1356 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001357 final long timeout = jsc.getTimeoutElapsed();
1358 pw.print("Running for: ");
1359 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1360 pw.print("s timeout=");
1361 pw.print(timeout);
1362 pw.print(" fromnow=");
1363 pw.println(timeout-now);
1364 jsc.getRunningJob().dump(pw, " ");
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001365 int priority = evaluateJobPriorityLocked(jsc.getRunningJob());
1366 if (priority != JobInfo.PRIORITY_DEFAULT) {
1367 pw.print(" Evaluated priority: "); pw.println(priority);
1368 }
Christopher Tate7060b042014-06-09 19:50:00 -07001369 }
1370 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001371 pw.println();
1372 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001373 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001374 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001375 }
1376 pw.println();
1377 }
1378}