blob: fba7e7d76ac325e818d339eb37c676464fe71b2c [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 Hackborn970510b2016-02-24 16:56:42 -080056import android.util.SparseIntArray;
57import android.util.TimeUtils;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070058import com.android.internal.app.IBatteryStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070059import com.android.internal.util.ArrayUtils;
Dianne Hackborn970510b2016-02-24 16:56:42 -080060import com.android.internal.app.ProcessStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080061import com.android.server.DeviceIdleController;
62import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080063import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080064import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070065import com.android.server.job.controllers.BatteryController;
66import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080067import com.android.server.job.controllers.ContentObserverController;
Christopher Tate7060b042014-06-09 19:50:00 -070068import com.android.server.job.controllers.IdleController;
69import com.android.server.job.controllers.JobStatus;
70import com.android.server.job.controllers.StateController;
71import com.android.server.job.controllers.TimeController;
72
Jeff Sharkey822cbd12016-02-25 11:09:55 -070073import libcore.util.EmptyArray;
74
Christopher Tate7060b042014-06-09 19:50:00 -070075/**
76 * Responsible for taking jobs representing work to be performed by a client app, and determining
77 * based on the criteria specified when that job should be run against the client application's
78 * endpoint.
79 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
80 * about constraints, or the state of active jobs. It receives callbacks from the various
81 * controllers and completed jobs and operates accordingly.
82 *
83 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
84 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
85 * @hide
86 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -080087public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070088 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -080089 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -070090 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -080091
Dianne Hackborn970510b2016-02-24 16:56:42 -080092 /** The maximum number of concurrent jobs we run at one time. */
93 private static final int MAX_JOB_CONTEXTS_COUNT = 8;
Christopher Tatedabdf6f2016-02-24 12:30:22 -080094 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -080095 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -080096 /** The maximum number of jobs that we allow an unprivileged app to schedule */
97 private static final int MAX_JOBS_PER_APP = 100;
98
Dianne Hackborn33d31c52016-02-16 10:30:33 -080099 /** Global local for all job scheduler state. */
100 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700101 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700102 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -0700103
104 static final int MSG_JOB_EXPIRED = 0;
105 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700106 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000107 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700108
109 // Policy constants
110 /**
111 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
112 * early.
113 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700114 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -0700115 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700116 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
117 * early.
118 */
119 static final int MIN_CHARGING_COUNT = 1;
120 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700121 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
122 * things early.
123 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700124 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700125 /**
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800126 * Minimum # of content trigger jobs that must be ready in order to force the JMS to schedule
127 * things early.
128 */
129 static final int MIN_CONTENT_COUNT = 1;
130 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700131 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
132 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700133 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700134 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700135 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700136
137 /**
138 * Track Services that have currently active or pending jobs. The index is provided by
139 * {@link JobStatus#getServiceToken()}
140 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700141 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700142 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700143 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700144 /**
145 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
146 * when ready to execute them.
147 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700148 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700149
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700150 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700151
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700152 final JobHandler mHandler;
153 final JobSchedulerStub mJobSchedulerStub;
154
155 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700156 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800157 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700158
159 /**
160 * Set to true once we are allowed to run third party apps.
161 */
162 boolean mReadyToRock;
163
Christopher Tate7060b042014-06-09 19:50:00 -0700164 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700165 * True when in device idle mode, so we don't want to schedule any jobs.
166 */
167 boolean mDeviceIdleMode;
168
169 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800170 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800171 */
172 boolean mReportedActive;
173
174 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800175 * Current limit on the number of concurrent JobServiceContext entries we want to
176 * keep actively running a job.
177 */
178 int mMaxActiveJobs = MAX_JOB_CONTEXTS_COUNT - 2;
179
180 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800181 * Which uids are currently in the foreground.
182 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800183 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
184
185 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
186
187 /**
188 * This array essentially stores the state of mActiveServices array.
189 * The ith index stores the job present on the ith JobServiceContext.
190 * We manipulate this array until we arrive at what jobs should be running on
191 * what JobServiceContext.
192 */
193 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
194 /**
195 * Indicates whether we need to act on this jobContext id
196 */
197 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
198 /**
199 * The uid whose jobs we would like to assign to a context.
200 */
201 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800202
203 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700204 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
205 * still clean up. On reinstall the package will have a new uid.
206 */
207 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
208 @Override
209 public void onReceive(Context context, Intent intent) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000210 Slog.d(TAG, "Receieved: " + intent.getAction());
211 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700212 // If this is an outright uninstall rather than the first half of an
213 // app update sequence, cancel the jobs associated with the app.
214 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
215 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
216 if (DEBUG) {
217 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
218 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700219 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700220 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000221 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700222 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
223 if (DEBUG) {
224 Slog.d(TAG, "Removing jobs for user: " + userId);
225 }
226 cancelJobsForUser(userId);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000227 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())
228 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700229 updateIdleMode(mPowerManager != null
230 ? (mPowerManager.isDeviceIdleMode()
Shreyas Basarge5db09082016-01-07 13:38:29 +0000231 || mPowerManager.isLightDeviceIdleMode())
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700232 : false);
Christopher Tate7060b042014-06-09 19:50:00 -0700233 }
234 }
235 };
236
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700237 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
238 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800239 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700240 }
241
242 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800243 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700244 }
245
246 @Override public void onUidActive(int uid) throws RemoteException {
247 }
248
249 @Override public void onUidIdle(int uid) throws RemoteException {
250 cancelJobsForUid(uid, false);
251 }
252 };
253
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800254 public Object getLock() {
255 return mLock;
256 }
257
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700258 @Override
259 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700260 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
261 // Let's kick any outstanding jobs for this user.
262 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
263 }
264
265 @Override
266 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700267 // Let's kick any outstanding jobs for this user.
268 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
269 }
270
271 @Override
272 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700273 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700274 }
275
Christopher Tate7060b042014-06-09 19:50:00 -0700276 /**
277 * Entry point from client to schedule the provided job.
278 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
279 * @param job JobInfo object containing execution parameters
280 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700281 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
282 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700283 public int schedule(JobInfo job, int uId) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800284 return scheduleAsPackage(job, uId, null, -1, null);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000285 }
286
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800287 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId,
288 String tag) {
289 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700290 try {
291 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
292 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
293 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
294 + " -- package not allowed to start");
295 return JobScheduler.RESULT_FAILURE;
296 }
297 } catch (RemoteException e) {
298 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800299 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
300 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800301 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800302 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800303 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800304 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
305 Slog.w(TAG, "Too many jobs for uid " + uId);
306 throw new IllegalStateException("Apps may not schedule more than "
307 + MAX_JOBS_PER_APP + " distinct jobs");
308 }
309 }
310
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800311 toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
312 }
313 startTrackingJob(jobStatus, toCancel);
314 if (toCancel != null) {
315 cancelJobImpl(toCancel);
316 }
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700317 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700318 return JobScheduler.RESULT_SUCCESS;
319 }
320
321 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800322 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800323 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
324 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
325 for (int i = jobs.size() - 1; i >= 0; i--) {
326 JobStatus job = jobs.get(i);
327 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700328 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800329 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700330 }
Christopher Tate7060b042014-06-09 19:50:00 -0700331 }
332
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700333 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700334 List<JobStatus> jobsForUser;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800335 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700336 jobsForUser = mJobs.getJobsByUser(userHandle);
337 }
338 for (int i=0; i<jobsForUser.size(); i++) {
339 JobStatus toRemove = jobsForUser.get(i);
340 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700341 }
342 }
343
344 /**
345 * Entry point from client to cancel all jobs originating from their uid.
346 * This will remove the job from the master list, and cancel the job if it was staged for
347 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700348 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700349 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
350 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700351 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700352 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700353 List<JobStatus> jobsForUid;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800354 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700355 jobsForUid = mJobs.getJobsByUid(uid);
356 }
357 for (int i=0; i<jobsForUid.size(); i++) {
358 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700359 if (!forceAll) {
360 String packageName = toRemove.getServiceComponent().getPackageName();
361 try {
362 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
363 != ActivityManager.APP_START_MODE_DISABLED) {
364 continue;
365 }
366 } catch (RemoteException e) {
367 }
368 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700369 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700370 }
371 }
372
373 /**
374 * Entry point from client to cancel the job corresponding to the jobId provided.
375 * This will remove the job from the master list, and cancel the job if it was staged for
376 * execution or being executed.
377 * @param uid Uid of the calling client.
378 * @param jobId Id of the job, provided at schedule-time.
379 */
380 public void cancelJob(int uid, int jobId) {
381 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800382 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700383 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700384 }
385 if (toCancel != null) {
386 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700387 }
388 }
389
Matthew Williams48a30db2014-09-23 13:39:36 -0700390 private void cancelJobImpl(JobStatus cancelled) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800391 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Shreyas Basarge73f10252016-02-11 17:06:13 +0000392 stopTrackingJob(cancelled, true /* writeBack */);
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800393 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700394 // Remove from pending queue.
395 mPendingJobs.remove(cancelled);
396 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000397 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800398 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700399 }
Christopher Tate7060b042014-06-09 19:50:00 -0700400 }
401
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800402 void updateUidState(int uid, int procState) {
403 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800404 if (procState == ActivityManager.PROCESS_STATE_TOP) {
405 // Only use this if we are exactly the top app. All others can live
406 // with just the foreground priority. This means that persistent processes
407 // can never be the top app priority... that is fine.
408 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
409 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
410 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800411 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800412 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800413 }
414 }
415 }
416
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700417 void updateIdleMode(boolean enabled) {
418 boolean changed = false;
419 boolean rocking;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800420 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700421 if (mDeviceIdleMode != enabled) {
422 changed = true;
423 }
424 rocking = mReadyToRock;
425 }
426 if (changed) {
427 if (rocking) {
428 for (int i=0; i<mControllers.size(); i++) {
429 mControllers.get(i).deviceIdleModeChanged(enabled);
430 }
431 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800432 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700433 mDeviceIdleMode = enabled;
434 if (enabled) {
435 // When becoming idle, make sure no jobs are actively running.
436 for (int i=0; i<mActiveServices.size(); i++) {
437 JobServiceContext jsc = mActiveServices.get(i);
438 final JobStatus executing = jsc.getRunningJob();
439 if (executing != null) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000440 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700441 }
442 }
443 } else {
444 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800445 if (rocking) {
446 if (mLocalDeviceIdleController != null) {
447 if (!mReportedActive) {
448 mReportedActive = true;
449 mLocalDeviceIdleController.setJobsActive(true);
450 }
451 }
452 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700453 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
454 }
455 }
456 }
457 }
458
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800459 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000460 // active is true if pending queue contains jobs OR some job is running.
461 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800462 if (mPendingJobs.size() <= 0) {
463 for (int i=0; i<mActiveServices.size(); i++) {
464 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000465 if (jsc.getRunningJob() != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800466 active = true;
467 break;
468 }
469 }
470 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000471
472 if (mReportedActive != active) {
473 mReportedActive = active;
474 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800475 mLocalDeviceIdleController.setJobsActive(active);
476 }
477 }
478 }
479
Christopher Tate7060b042014-06-09 19:50:00 -0700480 /**
481 * Initializes the system service.
482 * <p>
483 * Subclasses must define a single argument constructor that accepts the context
484 * and passes it to super.
485 * </p>
486 *
487 * @param context The system server context.
488 */
489 public JobSchedulerService(Context context) {
490 super(context);
491 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700492 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700493 mControllers.add(ConnectivityController.get(this));
494 mControllers.add(TimeController.get(this));
495 mControllers.add(IdleController.get(this));
496 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800497 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800498 mControllers.add(ContentObserverController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700499
500 mHandler = new JobHandler(context.getMainLooper());
501 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700502 mJobs = JobStore.initAndGet(this);
503 }
504
505 @Override
506 public void onStart() {
507 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
508 }
509
510 @Override
511 public void onBootPhase(int phase) {
512 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000513 // Register br for package removals and user removals.
Christopher Tate7060b042014-06-09 19:50:00 -0700514 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
515 filter.addDataScheme("package");
516 getContext().registerReceiverAsUser(
517 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
518 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700519 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700520 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700521 getContext().registerReceiverAsUser(
522 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000523 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700524 try {
525 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800526 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
527 | ActivityManager.UID_OBSERVER_IDLE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700528 } catch (RemoteException e) {
529 // ignored; both services live in system_server
530 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700531 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800532 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700533 // Let's go!
534 mReadyToRock = true;
535 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
536 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800537 mLocalDeviceIdleController
538 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700539 // Create the "runners".
540 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
541 mActiveServices.add(
542 new JobServiceContext(this, mBatteryStats,
543 getContext().getMainLooper()));
544 }
545 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -0800546 mJobs.forEachJob(new JobStatusFunctor() {
547 @Override
548 public void process(JobStatus job) {
549 for (int controller = 0; controller < mControllers.size(); controller++) {
550 final StateController sc = mControllers.get(controller);
551 sc.deviceIdleModeChanged(mDeviceIdleMode);
552 sc.maybeStartTrackingJobLocked(job, null);
553 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700554 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800555 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700556 // GO GO GO!
557 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
558 }
Christopher Tate7060b042014-06-09 19:50:00 -0700559 }
560 }
561
562 /**
563 * Called when we have a job status object that we need to insert in our
564 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
565 * about.
566 */
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800567 private void startTrackingJob(JobStatus jobStatus, JobStatus lastJob) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800568 synchronized (mLock) {
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800569 final boolean update = mJobs.add(jobStatus);
570 if (mReadyToRock) {
571 for (int i = 0; i < mControllers.size(); i++) {
572 StateController controller = mControllers.get(i);
573 if (update) {
574 controller.maybeStopTrackingJobLocked(jobStatus, true);
575 }
576 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700577 }
Christopher Tate7060b042014-06-09 19:50:00 -0700578 }
Christopher Tate7060b042014-06-09 19:50:00 -0700579 }
580 }
581
582 /**
583 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
584 * object removed.
585 */
Shreyas Basarge73f10252016-02-11 17:06:13 +0000586 private boolean stopTrackingJob(JobStatus jobStatus, boolean writeBack) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800587 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700588 // Remove from store as well as controllers.
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800589 final boolean removed = mJobs.remove(jobStatus, writeBack);
590 if (removed && mReadyToRock) {
591 for (int i=0; i<mControllers.size(); i++) {
592 StateController controller = mControllers.get(i);
593 controller.maybeStopTrackingJobLocked(jobStatus, false);
594 }
Christopher Tate7060b042014-06-09 19:50:00 -0700595 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800596 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -0700597 }
Christopher Tate7060b042014-06-09 19:50:00 -0700598 }
599
Shreyas Basarge5db09082016-01-07 13:38:29 +0000600 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700601 for (int i=0; i<mActiveServices.size(); i++) {
602 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700603 final JobStatus executing = jsc.getRunningJob();
604 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000605 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700606 return true;
607 }
608 }
609 return false;
610 }
611
612 /**
613 * @param job JobStatus we are querying against.
614 * @return Whether or not the job represented by the status object is currently being run or
615 * is pending.
616 */
617 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700618 for (int i=0; i<mActiveServices.size(); i++) {
619 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700620 final JobStatus running = serviceContext.getRunningJob();
621 if (running != null && running.matches(job.getUid(), job.getJobId())) {
622 return true;
623 }
624 }
625 return false;
626 }
627
628 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700629 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
630 * specify an override deadline on a failed job (the failed job will run even though it's not
631 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
632 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
633 *
Christopher Tate7060b042014-06-09 19:50:00 -0700634 * @param failureToReschedule Provided job status that we will reschedule.
635 * @return A newly instantiated JobStatus with the same constraints as the last job except
636 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700637 *
638 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700639 */
640 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
641 final long elapsedNowMillis = SystemClock.elapsedRealtime();
642 final JobInfo job = failureToReschedule.getJob();
643
644 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700645 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
646 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700647
648 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700649 case JobInfo.BACKOFF_POLICY_LINEAR:
650 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700651 break;
652 default:
653 if (DEBUG) {
654 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
655 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700656 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
657 delayMillis =
658 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700659 break;
660 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700661 delayMillis =
662 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800663 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -0700664 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800665 for (int ic=0; ic<mControllers.size(); ic++) {
666 StateController controller = mControllers.get(ic);
667 controller.rescheduleForFailure(newJob, failureToReschedule);
668 }
669 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -0700670 }
671
672 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700673 * Called after a periodic has executed so we can reschedule it. We take the last execution
674 * time of the job to be the time of completion (i.e. the time at which this function is
675 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700676 * This could be inaccurate b/c the job can run for as long as
677 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
678 * to underscheduling at least, rather than if we had taken the last execution time to be the
679 * start of the execution.
680 * @return A new job representing the execution criteria for this instantiation of the
681 * recurring job.
682 */
683 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
684 final long elapsedNow = SystemClock.elapsedRealtime();
685 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700686 long runEarly = 0L;
687
688 // If this periodic was rescheduled it won't have a deadline.
689 if (periodicToReschedule.hasDeadlineConstraint()) {
690 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
691 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000692 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700693 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000694 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
695 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -0700696
697 if (DEBUG) {
698 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
699 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
700 }
701 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
702 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
703 }
704
705 // JobCompletedListener implementations.
706
707 /**
708 * A job just finished executing. We fetch the
709 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
710 * whether we want to reschedule we readd it to the controllers.
711 * @param jobStatus Completed job.
712 * @param needsReschedule Whether the implementing class should reschedule this job.
713 */
714 @Override
715 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
716 if (DEBUG) {
717 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
718 }
Shreyas Basarge73f10252016-02-11 17:06:13 +0000719 // Do not write back immediately if this is a periodic job. The job may get lost if system
720 // shuts down before it is added back.
721 if (!stopTrackingJob(jobStatus, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700722 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700723 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700724 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800725 // We still want to check for jobs to execute, because this job may have
726 // scheduled a new job under the same job id, and now we can run it.
727 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700728 return;
729 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800730 // Note: there is a small window of time in here where, when rescheduling a job,
731 // we will stop monitoring its content providers. This should be fixed by stopping
732 // the old job after scheduling the new one, but since we have no lock held here
733 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -0700734 if (needsReschedule) {
735 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800736 startTrackingJob(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700737 } else if (jobStatus.getJob().isPeriodic()) {
738 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800739 startTrackingJob(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700740 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000741 reportActive();
742 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700743 }
744
745 // StateChangedListener implementations.
746
747 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700748 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
749 * some controller's state has changed, so as to run through the list of jobs and start/stop
750 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700751 */
752 @Override
753 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700754 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700755 }
756
757 @Override
758 public void onRunJobNow(JobStatus jobStatus) {
759 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
760 }
761
Christopher Tate7060b042014-06-09 19:50:00 -0700762 private class JobHandler extends Handler {
763
764 public JobHandler(Looper looper) {
765 super(looper);
766 }
767
768 @Override
769 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800770 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700771 if (!mReadyToRock) {
772 return;
773 }
774 }
Christopher Tate7060b042014-06-09 19:50:00 -0700775 switch (message.what) {
776 case MSG_JOB_EXPIRED:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800777 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700778 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700779 // runNow can be null, which is a controller's way of indicating that its
780 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700781 if (runNow != null && !mPendingJobs.contains(runNow)
782 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700783 mPendingJobs.add(runNow);
784 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700785 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700786 }
Christopher Tate7060b042014-06-09 19:50:00 -0700787 break;
788 case MSG_CHECK_JOB:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800789 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000790 if (mReportedActive) {
791 // if jobs are currently being run, queue all ready jobs for execution.
792 queueReadyJobsForExecutionLockedH();
793 } else {
794 // Check the list of jobs and run some of them if we feel inclined.
795 maybeQueueReadyJobsForExecutionLockedH();
796 }
797 }
798 break;
799 case MSG_CHECK_JOB_GREEDY:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800800 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000801 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700802 }
Christopher Tate7060b042014-06-09 19:50:00 -0700803 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700804 case MSG_STOP_JOB:
805 cancelJobImpl((JobStatus)message.obj);
806 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700807 }
808 maybeRunPendingJobsH();
809 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
810 removeMessages(MSG_CHECK_JOB);
811 }
812
813 /**
814 * Run through list of jobs and execute all possible - at least one is expired so we do
815 * as many as we can.
816 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700817 private void queueReadyJobsForExecutionLockedH() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700818 if (DEBUG) {
819 Slog.d(TAG, "queuing all ready jobs for execution:");
820 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800821 mPendingJobs.clear();
822 mJobs.forEachJob(mReadyQueueFunctor);
823 mReadyQueueFunctor.postProcess();
824
Matthew Williams48a30db2014-09-23 13:39:36 -0700825 if (DEBUG) {
826 final int queuedJobs = mPendingJobs.size();
827 if (queuedJobs == 0) {
828 Slog.d(TAG, "No jobs pending.");
829 } else {
830 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700831 }
Christopher Tate7060b042014-06-09 19:50:00 -0700832 }
833 }
834
Christopher Tate2f36fd62016-02-18 18:36:08 -0800835 class ReadyJobQueueFunctor implements JobStatusFunctor {
836 ArrayList<JobStatus> newReadyJobs;
837
838 @Override
839 public void process(JobStatus job) {
840 if (isReadyToBeExecutedLocked(job)) {
841 if (DEBUG) {
842 Slog.d(TAG, " queued " + job.toShortString());
843 }
844 if (newReadyJobs == null) {
845 newReadyJobs = new ArrayList<JobStatus>();
846 }
847 newReadyJobs.add(job);
848 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
849 stopJobOnServiceContextLocked(job,
850 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
851 }
852 }
853
854 public void postProcess() {
855 if (newReadyJobs != null) {
856 mPendingJobs.addAll(newReadyJobs);
857 }
858 newReadyJobs = null;
859 }
860 }
861 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
862
Christopher Tate7060b042014-06-09 19:50:00 -0700863 /**
864 * The state of at least one job has changed. Here is where we could enforce various
865 * policies on when we want to execute jobs.
866 * Right now the policy is such:
867 * If >1 of the ready jobs is idle mode we send all of them off
868 * if more than 2 network connectivity jobs are ready we send them all off.
869 * If more than 4 jobs total are ready we send them all off.
870 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
871 */
Christopher Tate2f36fd62016-02-18 18:36:08 -0800872 class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
873 int chargingCount;
874 int idleCount;
875 int backoffCount;
876 int connectivityCount;
877 int contentCount;
878 List<JobStatus> runnableJobs;
879
880 public MaybeReadyJobQueueFunctor() {
881 reset();
882 }
883
884 // Functor method invoked for each job via JobStore.forEachJob()
885 @Override
886 public void process(JobStatus job) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700887 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700888 try {
889 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
890 job.getJob().getService().getPackageName())
891 == ActivityManager.APP_START_MODE_DISABLED) {
892 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
893 + job.getJob().toString() + " -- package not allowed to start");
894 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800895 return;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700896 }
897 } catch (RemoteException e) {
898 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700899 if (job.getNumFailures() > 0) {
900 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700901 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700902 if (job.hasIdleConstraint()) {
903 idleCount++;
904 }
905 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
906 connectivityCount++;
907 }
908 if (job.hasChargingConstraint()) {
909 chargingCount++;
910 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800911 if (job.hasContentTriggerConstraint()) {
912 contentCount++;
913 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700914 if (runnableJobs == null) {
915 runnableJobs = new ArrayList<>();
916 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700917 runnableJobs.add(job);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800918 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000919 stopJobOnServiceContextLocked(job,
920 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700921 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700922 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800923
924 public void postProcess() {
925 if (backoffCount > 0 ||
926 idleCount >= MIN_IDLE_COUNT ||
927 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
928 chargingCount >= MIN_CHARGING_COUNT ||
929 contentCount >= MIN_CONTENT_COUNT ||
930 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
931 if (DEBUG) {
932 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
933 }
934 mPendingJobs.addAll(runnableJobs);
935 } else {
936 if (DEBUG) {
937 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
938 }
Christopher Tate7060b042014-06-09 19:50:00 -0700939 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800940
941 // Be ready for next time
942 reset();
Matthew Williams48a30db2014-09-23 13:39:36 -0700943 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800944
945 private void reset() {
946 chargingCount = 0;
947 idleCount = 0;
948 backoffCount = 0;
949 connectivityCount = 0;
950 contentCount = 0;
951 runnableJobs = null;
952 }
953 }
954 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
955
956 private void maybeQueueReadyJobsForExecutionLockedH() {
957 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
958
959 mPendingJobs.clear();
960 mJobs.forEachJob(mMaybeQueueFunctor);
961 mMaybeQueueFunctor.postProcess();
Christopher Tate7060b042014-06-09 19:50:00 -0700962 }
963
964 /**
965 * Criteria for moving a job into the pending queue:
966 * - It's ready.
967 * - It's not pending.
968 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700969 * - The user that requested the job is running.
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700970 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -0700971 */
972 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700973 final boolean jobReady = job.isReady();
974 final boolean jobPending = mPendingJobs.contains(job);
975 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700976
977 final int userId = job.getUserId();
978 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
979 final boolean componentPresent;
980 try {
981 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
982 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
983 userId) != null);
984 } catch (RemoteException e) {
985 throw e.rethrowAsRuntimeException();
986 }
987
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700988 if (DEBUG) {
989 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
990 + " ready=" + jobReady + " pending=" + jobPending
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700991 + " active=" + jobActive + " userStarted=" + userStarted
992 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700993 }
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700994 return userStarted && componentPresent && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700995 }
996
997 /**
998 * Criteria for cancelling an active job:
999 * - It's not ready
1000 * - It's running on a JSC.
1001 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001002 private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -07001003 return !job.isReady() && isCurrentlyActiveLocked(job);
1004 }
1005
1006 /**
1007 * Reconcile jobs in the pending queue against available execution contexts.
1008 * A controller can force a job into the pending queue even if it's already running, but
1009 * here is where we decide whether to actually execute it.
1010 */
1011 private void maybeRunPendingJobsH() {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001012 synchronized (mLock) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001013 if (mDeviceIdleMode) {
1014 // If device is idle, we will not schedule jobs to run.
1015 return;
1016 }
Matthew Williams75fc5252014-09-02 16:17:53 -07001017 if (DEBUG) {
1018 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1019 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001020 assignJobsToContextsLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001021 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -07001022 }
1023 }
1024 }
1025
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001026 private int evaluateJobPriorityLocked(JobStatus job) {
1027 int priority = job.getPriority();
1028 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
1029 return priority;
1030 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001031 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1032 if (override != 0) {
1033 return override;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001034 }
1035 return priority;
1036 }
1037
Christopher Tate7060b042014-06-09 19:50:00 -07001038 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001039 * Takes jobs from pending queue and runs them on available contexts.
1040 * If no contexts are available, preempts lower priority jobs to
1041 * run higher priority ones.
1042 * Lock on mJobs before calling this function.
1043 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001044 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001045 if (DEBUG) {
1046 Slog.d(TAG, printPendingQueue());
1047 }
1048
Dianne Hackborn970510b2016-02-24 16:56:42 -08001049 int memLevel;
1050 try {
1051 memLevel = ActivityManagerNative.getDefault().getMemoryTrimLevel();
1052 } catch (RemoteException e) {
1053 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1054 }
1055 switch (memLevel) {
1056 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
1057 mMaxActiveJobs = ((MAX_JOB_CONTEXTS_COUNT - 2) * 2) / 3;
1058 break;
1059 case ProcessStats.ADJ_MEM_FACTOR_LOW:
1060 mMaxActiveJobs = (MAX_JOB_CONTEXTS_COUNT - 2) / 3;
1061 break;
1062 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
1063 mMaxActiveJobs = 1;
1064 break;
1065 default:
1066 mMaxActiveJobs = MAX_JOB_CONTEXTS_COUNT - 2;
1067 break;
1068 }
1069
1070 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1071 boolean[] act = mTmpAssignAct;
1072 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1073 int numActive = 0;
1074 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1075 final JobServiceContext js = mActiveServices.get(i);
1076 if ((contextIdToJobMap[i] = js.getRunningJob()) != null) {
1077 numActive++;
1078 }
1079 act[i] = false;
1080 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001081 }
1082 if (DEBUG) {
1083 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1084 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001085 for (int i=0; i<mPendingJobs.size(); i++) {
1086 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001087
1088 // If job is already running, go to next job.
1089 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1090 if (jobRunningContext != -1) {
1091 continue;
1092 }
1093
Dianne Hackborn970510b2016-02-24 16:56:42 -08001094 final int priority = evaluateJobPriorityLocked(nextPending);
1095 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001096
Shreyas Basarge5db09082016-01-07 13:38:29 +00001097 // Find a context for nextPending. The context should be available OR
1098 // it should have lowest priority among all running jobs
1099 // (sharing the same Uid as nextPending)
1100 int minPriority = Integer.MAX_VALUE;
1101 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001102 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1103 JobStatus job = contextIdToJobMap[j];
1104 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001105 if (job == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001106 if ((numActive < mMaxActiveJobs || priority >= JobInfo.PRIORITY_TOP_APP) &&
1107 (preferredUid == nextPending.getUid() ||
1108 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1109 // This slot is free, and we haven't yet hit the limit on
1110 // concurrent jobs... we can just throw the job in to here.
1111 minPriorityContextId = j;
1112 numActive++;
1113 break;
1114 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001115 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001116 // the context has a preferred Uid or we have reached the limit on
1117 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001118 continue;
1119 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001120 if (job.getUid() != nextPending.getUid()) {
1121 continue;
1122 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001123 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001124 continue;
1125 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001126 if (minPriority > nextPending.lastEvaluatedPriority) {
1127 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001128 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001129 }
1130 }
1131 if (minPriorityContextId != -1) {
1132 contextIdToJobMap[minPriorityContextId] = nextPending;
1133 act[minPriorityContextId] = true;
1134 }
1135 }
1136 if (DEBUG) {
1137 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1138 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001139 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001140 boolean preservePreferredUid = false;
1141 if (act[i]) {
1142 JobStatus js = mActiveServices.get(i).getRunningJob();
1143 if (js != null) {
1144 if (DEBUG) {
1145 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
1146 }
1147 // preferredUid will be set to uid of currently running job.
1148 mActiveServices.get(i).preemptExecutingJob();
1149 preservePreferredUid = true;
1150 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001151 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001152 if (DEBUG) {
1153 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001154 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001155 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001156 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001157 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001158 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001159 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1160 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001161 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001162 mPendingJobs.remove(pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001163 }
1164 }
1165 if (!preservePreferredUid) {
1166 mActiveServices.get(i).clearPreferredUid();
1167 }
1168 }
1169 }
1170
1171 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1172 for (int i=0; i<map.length; i++) {
1173 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1174 return i;
1175 }
1176 }
1177 return -1;
1178 }
1179
1180 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001181 * Binder stub trampoline implementation
1182 */
1183 final class JobSchedulerStub extends IJobScheduler.Stub {
1184 /** Cache determination of whether a given app can persist jobs
1185 * key is uid of the calling app; value is undetermined/true/false
1186 */
1187 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1188
1189 // Enforce that only the app itself (or shared uid participant) can schedule a
1190 // job that runs one of the app's services, as well as verifying that the
1191 // named service properly requires the BIND_JOB_SERVICE permission
1192 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001193 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001194 final ComponentName service = job.getService();
1195 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001196 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001197 PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE,
1198 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001199 if (si == null) {
1200 throw new IllegalArgumentException("No such service " + service);
1201 }
Christopher Tate7060b042014-06-09 19:50:00 -07001202 if (si.applicationInfo.uid != uid) {
1203 throw new IllegalArgumentException("uid " + uid +
1204 " cannot schedule job in " + service.getPackageName());
1205 }
1206 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1207 throw new IllegalArgumentException("Scheduled service " + service
1208 + " does not require android.permission.BIND_JOB_SERVICE permission");
1209 }
Christopher Tate5568f542014-06-18 13:53:31 -07001210 } catch (RemoteException e) {
1211 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001212 }
1213 }
1214
1215 private boolean canPersistJobs(int pid, int uid) {
1216 // If we get this far we're good to go; all we need to do now is check
1217 // whether the app is allowed to persist its scheduled work.
1218 final boolean canPersist;
1219 synchronized (mPersistCache) {
1220 Boolean cached = mPersistCache.get(uid);
1221 if (cached != null) {
1222 canPersist = cached.booleanValue();
1223 } else {
1224 // Persisting jobs is tantamount to running at boot, so we permit
1225 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1226 // permission
1227 int result = getContext().checkPermission(
1228 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1229 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1230 mPersistCache.put(uid, canPersist);
1231 }
1232 }
1233 return canPersist;
1234 }
1235
1236 // IJobScheduler implementation
1237 @Override
1238 public int schedule(JobInfo job) throws RemoteException {
1239 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001240 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001241 }
1242 final int pid = Binder.getCallingPid();
1243 final int uid = Binder.getCallingUid();
1244
1245 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001246 if (job.isPersisted()) {
1247 if (!canPersistJobs(pid, uid)) {
1248 throw new IllegalArgumentException("Error: requested job be persisted without"
1249 + " holding RECEIVE_BOOT_COMPLETED permission.");
1250 }
1251 }
Christopher Tate7060b042014-06-09 19:50:00 -07001252
1253 long ident = Binder.clearCallingIdentity();
1254 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001255 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001256 } finally {
1257 Binder.restoreCallingIdentity(ident);
1258 }
1259 }
1260
1261 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001262 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001263 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001264 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001265 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001266 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1267 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001268 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001269
1270 if (packageName == null) {
1271 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001272 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001273
1274 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1275 android.Manifest.permission.UPDATE_DEVICE_STATS);
1276 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1277 throw new SecurityException("Caller uid " + callerUid
1278 + " not permitted to schedule jobs for other apps");
1279 }
1280
Shreyas Basarge968ac752016-01-11 23:09:26 +00001281 long ident = Binder.clearCallingIdentity();
1282 try {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001283 return JobSchedulerService.this.scheduleAsPackage(job, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001284 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001285 } finally {
1286 Binder.restoreCallingIdentity(ident);
1287 }
1288 }
1289
1290 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001291 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1292 final int uid = Binder.getCallingUid();
1293
1294 long ident = Binder.clearCallingIdentity();
1295 try {
1296 return JobSchedulerService.this.getPendingJobs(uid);
1297 } finally {
1298 Binder.restoreCallingIdentity(ident);
1299 }
1300 }
1301
1302 @Override
1303 public void cancelAll() throws RemoteException {
1304 final int uid = Binder.getCallingUid();
1305
1306 long ident = Binder.clearCallingIdentity();
1307 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001308 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001309 } finally {
1310 Binder.restoreCallingIdentity(ident);
1311 }
1312 }
1313
1314 @Override
1315 public void cancel(int jobId) throws RemoteException {
1316 final int uid = Binder.getCallingUid();
1317
1318 long ident = Binder.clearCallingIdentity();
1319 try {
1320 JobSchedulerService.this.cancelJob(uid, jobId);
1321 } finally {
1322 Binder.restoreCallingIdentity(ident);
1323 }
1324 }
1325
1326 /**
1327 * "dumpsys" infrastructure
1328 */
1329 @Override
1330 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1331 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1332
1333 long identityToken = Binder.clearCallingIdentity();
1334 try {
1335 JobSchedulerService.this.dumpInternal(pw);
1336 } finally {
1337 Binder.restoreCallingIdentity(identityToken);
1338 }
1339 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001340 };
1341
1342 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1343 StringBuilder s = new StringBuilder(initial + ": ");
1344 for (int i=0; i<map.length; i++) {
1345 s.append("(")
1346 .append(map[i] == null? -1: map[i].getJobId())
1347 .append(map[i] == null? -1: map[i].getUid())
1348 .append(")" );
1349 }
1350 return s.toString();
1351 }
1352
1353 private String printPendingQueue() {
1354 StringBuilder s = new StringBuilder("Pending queue: ");
1355 Iterator<JobStatus> it = mPendingJobs.iterator();
1356 while (it.hasNext()) {
1357 JobStatus js = it.next();
1358 s.append("(")
1359 .append(js.getJob().getId())
1360 .append(", ")
1361 .append(js.getUid())
1362 .append(") ");
1363 }
1364 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001365 }
Christopher Tate7060b042014-06-09 19:50:00 -07001366
Christopher Tate2f36fd62016-02-18 18:36:08 -08001367 void dumpInternal(final PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001368 final long now = SystemClock.elapsedRealtime();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001369 synchronized (mLock) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001370 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Christopher Tate7060b042014-06-09 19:50:00 -07001371 pw.println("Registered jobs:");
1372 if (mJobs.size() > 0) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001373 mJobs.forEachJob(new JobStatusFunctor() {
1374 private int index = 0;
1375
1376 @Override
1377 public void process(JobStatus job) {
1378 pw.print(" Job #"); pw.print(index++); pw.print(": ");
1379 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08001380 job.dump(pw, " ", true);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001381 pw.print(" Ready: ");
1382 pw.print(mHandler.isReadyToBeExecutedLocked(job));
1383 pw.print(" (job=");
1384 pw.print(job.isReady());
1385 pw.print(" pending=");
1386 pw.print(mPendingJobs.contains(job));
1387 pw.print(" active=");
1388 pw.print(isCurrentlyActiveLocked(job));
1389 pw.print(" user=");
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001390 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Christopher Tate2f36fd62016-02-18 18:36:08 -08001391 pw.println(")");
1392 }
1393 });
Christopher Tate7060b042014-06-09 19:50:00 -07001394 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001395 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001396 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001397 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001398 pw.println();
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001399 mControllers.get(i).dumpControllerStateLocked(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001400 }
1401 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001402 pw.println("Uid priority overrides:");
1403 for (int i=0; i< mUidPriorityOverride.size(); i++) {
1404 pw.print(" "); pw.print(UserHandle.formatUid(mUidPriorityOverride.keyAt(i)));
1405 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001406 }
1407 pw.println();
1408 pw.println("Pending queue:");
1409 for (int i=0; i<mPendingJobs.size(); i++) {
1410 JobStatus job = mPendingJobs.get(i);
1411 pw.print(" Pending #"); pw.print(i); pw.print(": ");
1412 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08001413 job.dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001414 int priority = evaluateJobPriorityLocked(job);
1415 if (priority != JobInfo.PRIORITY_DEFAULT) {
1416 pw.print(" Evaluated priority: "); pw.println(priority);
1417 }
1418 pw.print(" Tag: "); pw.println(job.getTag());
1419 }
Christopher Tate7060b042014-06-09 19:50:00 -07001420 pw.println();
1421 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001422 for (int i=0; i<mActiveServices.size(); i++) {
1423 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001424 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Shreyas Basarge5db09082016-01-07 13:38:29 +00001425 if (jsc.getRunningJob() == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001426 pw.println("inactive");
Christopher Tate7060b042014-06-09 19:50:00 -07001427 continue;
1428 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001429 pw.println(jsc.getRunningJob().toShortString());
1430 pw.print(" Running for: ");
1431 TimeUtils.formatDuration(now - jsc.getExecutionStartTimeElapsed(), pw);
1432 pw.print(", timeout at: ");
1433 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - now, pw);
1434 pw.println();
1435 jsc.getRunningJob().dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001436 int priority = evaluateJobPriorityLocked(jsc.getRunningJob());
1437 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001438 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001439 }
Christopher Tate7060b042014-06-09 19:50:00 -07001440 }
1441 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001442 pw.println();
1443 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001444 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001445 pw.print("mReportedActive="); pw.println(mReportedActive);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001446 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
Christopher Tate7060b042014-06-09 19:50:00 -07001447 }
1448 pw.println();
1449 }
1450}