blob: 7df8ffd7c8221dab645684a4ae798fcf0c438785 [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;
Shreyas Basargecbf5ae92016-03-08 16:13:06 +000048import android.os.Process;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070049import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070050import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080051import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070052import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070053import android.os.SystemClock;
54import android.os.UserHandle;
55import android.util.Slog;
56import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080057import android.util.SparseIntArray;
58import android.util.TimeUtils;
Christopher Tate5d346052016-03-08 12:56:08 -080059
Dianne Hackbornfdb19562014-07-11 16:03:36 -070060import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070061import com.android.internal.app.procstats.ProcessStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070062import com.android.internal.util.ArrayUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080063import com.android.server.DeviceIdleController;
64import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080065import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080066import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070067import com.android.server.job.controllers.BatteryController;
68import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080069import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070070import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070071import com.android.server.job.controllers.IdleController;
72import com.android.server.job.controllers.JobStatus;
73import com.android.server.job.controllers.StateController;
74import com.android.server.job.controllers.TimeController;
75
Jeff Sharkey822cbd12016-02-25 11:09:55 -070076import libcore.util.EmptyArray;
77
Christopher Tate7060b042014-06-09 19:50:00 -070078/**
79 * Responsible for taking jobs representing work to be performed by a client app, and determining
80 * based on the criteria specified when that job should be run against the client application's
81 * endpoint.
82 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
83 * about constraints, or the state of active jobs. It receives callbacks from the various
84 * controllers and completed jobs and operates accordingly.
85 *
86 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
87 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
88 * @hide
89 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -080090public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070091 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -080092 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -070093 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -080094
Dianne Hackborn970510b2016-02-24 16:56:42 -080095 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborn807de782016-04-07 17:54:41 -070096 private static final int MAX_JOB_CONTEXTS_COUNT = 12;
97 /** The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app. */
98 private static final int FG_JOB_CONTEXTS_COUNT = 4;
Christopher Tatedabdf6f2016-02-24 12:30:22 -080099 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800100 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800101 /** The maximum number of jobs that we allow an unprivileged app to schedule */
102 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborn807de782016-04-07 17:54:41 -0700103 /** This is the job execution factor that is considered to be heavy use of the system. */
104 private static final float HEAVY_USE_FACTOR = .9f;
105 /** This is the job execution factor that is considered to be moderate use of the system. */
106 private static final float MODERATE_USE_FACTOR = .5f;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800107
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800108 /** Global local for all job scheduler state. */
109 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700110 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700111 final JobStore mJobs;
Dianne Hackborn807de782016-04-07 17:54:41 -0700112 /** Tracking amount of time each package runs for. */
113 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700114
115 static final int MSG_JOB_EXPIRED = 0;
116 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700117 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000118 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700119
120 // Policy constants
121 /**
122 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
123 * early.
124 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700125 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -0700126 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700127 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
128 * early.
129 */
130 static final int MIN_CHARGING_COUNT = 1;
131 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700132 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
133 * things early.
134 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700135 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700136 /**
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800137 * Minimum # of content trigger jobs that must be ready in order to force the JMS to schedule
138 * things early.
139 */
140 static final int MIN_CONTENT_COUNT = 1;
141 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700142 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
143 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700144 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700145 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700146 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700147
148 /**
149 * Track Services that have currently active or pending jobs. The index is provided by
150 * {@link JobStatus#getServiceToken()}
151 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700152 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700153 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700154 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700155 /**
156 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
157 * when ready to execute them.
158 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700159 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700160
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700161 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700162
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700163 final JobHandler mHandler;
164 final JobSchedulerStub mJobSchedulerStub;
165
166 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700167 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800168 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700169
170 /**
171 * Set to true once we are allowed to run third party apps.
172 */
173 boolean mReadyToRock;
174
Christopher Tate7060b042014-06-09 19:50:00 -0700175 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800176 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800177 */
178 boolean mReportedActive;
179
180 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800181 * Current limit on the number of concurrent JobServiceContext entries we want to
182 * keep actively running a job.
183 */
Dianne Hackborn807de782016-04-07 17:54:41 -0700184 int mMaxActiveJobs = MAX_JOB_CONTEXTS_COUNT - FG_JOB_CONTEXTS_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800185
186 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800187 * Which uids are currently in the foreground.
188 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800189 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
190
191 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
192
193 /**
194 * This array essentially stores the state of mActiveServices array.
195 * The ith index stores the job present on the ith JobServiceContext.
196 * We manipulate this array until we arrive at what jobs should be running on
197 * what JobServiceContext.
198 */
199 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
200 /**
201 * Indicates whether we need to act on this jobContext id
202 */
203 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
204 /**
205 * The uid whose jobs we would like to assign to a context.
206 */
207 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800208
209 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700210 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
211 * still clean up. On reinstall the package will have a new uid.
212 */
213 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
214 @Override
215 public void onReceive(Context context, Intent intent) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700216 if (DEBUG) {
217 Slog.d(TAG, "Receieved: " + intent.getAction());
218 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000219 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700220 // If this is an outright uninstall rather than the first half of an
221 // app update sequence, cancel the jobs associated with the app.
222 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
223 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
224 if (DEBUG) {
225 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
226 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700227 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700228 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000229 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700230 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
231 if (DEBUG) {
232 Slog.d(TAG, "Removing jobs for user: " + userId);
233 }
234 cancelJobsForUser(userId);
235 }
236 }
237 };
238
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700239 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
240 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800241 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700242 }
243
244 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800245 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700246 }
247
248 @Override public void onUidActive(int uid) throws RemoteException {
249 }
250
251 @Override public void onUidIdle(int uid) throws RemoteException {
252 cancelJobsForUid(uid, false);
253 }
254 };
255
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800256 public Object getLock() {
257 return mLock;
258 }
259
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700260 public JobStore getJobStore() {
261 return mJobs;
262 }
263
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700264 @Override
265 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700266 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
267 // Let's kick any outstanding jobs for this user.
268 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
269 }
270
271 @Override
272 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700273 // Let's kick any outstanding jobs for this user.
274 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
275 }
276
277 @Override
278 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700279 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700280 }
281
Christopher Tate7060b042014-06-09 19:50:00 -0700282 /**
283 * Entry point from client to schedule the provided job.
284 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
285 * @param job JobInfo object containing execution parameters
286 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700287 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
288 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700289 public int schedule(JobInfo job, int uId) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800290 return scheduleAsPackage(job, uId, null, -1, null);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000291 }
292
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800293 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId,
294 String tag) {
295 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700296 try {
297 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
298 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
299 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
300 + " -- package not allowed to start");
301 return JobScheduler.RESULT_FAILURE;
302 }
303 } catch (RemoteException e) {
304 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800305 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
306 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800307 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800308 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800309 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800310 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
311 Slog.w(TAG, "Too many jobs for uid " + uId);
312 throw new IllegalStateException("Apps may not schedule more than "
313 + MAX_JOBS_PER_APP + " distinct jobs");
314 }
315 }
316
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800317 toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700318 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700319 cancelJobImpl(toCancel, jobStatus);
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700320 }
321 startTrackingJob(jobStatus, toCancel);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800322 }
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700323 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700324 return JobScheduler.RESULT_SUCCESS;
325 }
326
327 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800328 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800329 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
330 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
331 for (int i = jobs.size() - 1; i >= 0; i--) {
332 JobStatus job = jobs.get(i);
333 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700334 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800335 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700336 }
Christopher Tate7060b042014-06-09 19:50:00 -0700337 }
338
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700339 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700340 List<JobStatus> jobsForUser;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800341 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700342 jobsForUser = mJobs.getJobsByUser(userHandle);
343 }
344 for (int i=0; i<jobsForUser.size(); i++) {
345 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700346 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700347 }
348 }
349
350 /**
351 * Entry point from client to cancel all jobs originating from their uid.
352 * This will remove the job from the master list, and cancel the job if it was staged for
353 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700354 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700355 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
356 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700357 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700358 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700359 List<JobStatus> jobsForUid;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800360 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700361 jobsForUid = mJobs.getJobsByUid(uid);
362 }
363 for (int i=0; i<jobsForUid.size(); i++) {
364 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700365 if (!forceAll) {
366 String packageName = toRemove.getServiceComponent().getPackageName();
367 try {
368 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
369 != ActivityManager.APP_START_MODE_DISABLED) {
370 continue;
371 }
372 } catch (RemoteException e) {
373 }
374 }
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700375 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700376 }
377 }
378
379 /**
380 * Entry point from client to cancel the job corresponding to the jobId provided.
381 * This will remove the job from the master list, and cancel the job if it was staged for
382 * execution or being executed.
383 * @param uid Uid of the calling client.
384 * @param jobId Id of the job, provided at schedule-time.
385 */
386 public void cancelJob(int uid, int jobId) {
387 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800388 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700389 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700390 }
391 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700392 cancelJobImpl(toCancel, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700393 }
394 }
395
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700396 private void cancelJobImpl(JobStatus cancelled, JobStatus incomingJob) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800397 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700398 stopTrackingJob(cancelled, incomingJob, true /* writeBack */);
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800399 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700400 // Remove from pending queue.
Dianne Hackborn807de782016-04-07 17:54:41 -0700401 if (mPendingJobs.remove(cancelled)) {
402 mJobPackageTracker.noteNonpending(cancelled);
403 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700404 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000405 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800406 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700407 }
Christopher Tate7060b042014-06-09 19:50:00 -0700408 }
409
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800410 void updateUidState(int uid, int procState) {
411 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800412 if (procState == ActivityManager.PROCESS_STATE_TOP) {
413 // Only use this if we are exactly the top app. All others can live
414 // with just the foreground priority. This means that persistent processes
415 // can never be the top app priority... that is fine.
416 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
417 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
418 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800419 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800420 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800421 }
422 }
423 }
424
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700425 @Override
426 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800427 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700428 if (deviceIdle) {
429 // When becoming idle, make sure no jobs are actively running.
430 for (int i=0; i<mActiveServices.size(); i++) {
431 JobServiceContext jsc = mActiveServices.get(i);
432 final JobStatus executing = jsc.getRunningJob();
433 if (executing != null) {
434 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
435 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700436 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700437 } else {
438 // When coming out of idle, allow thing to start back up.
439 if (mReadyToRock) {
440 if (mLocalDeviceIdleController != null) {
441 if (!mReportedActive) {
442 mReportedActive = true;
443 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700444 }
445 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700446 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700447 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700448 }
449 }
450 }
451
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800452 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000453 // active is true if pending queue contains jobs OR some job is running.
454 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800455 if (mPendingJobs.size() <= 0) {
456 for (int i=0; i<mActiveServices.size(); i++) {
457 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000458 if (jsc.getRunningJob() != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800459 active = true;
460 break;
461 }
462 }
463 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000464
465 if (mReportedActive != active) {
466 mReportedActive = active;
467 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800468 mLocalDeviceIdleController.setJobsActive(active);
469 }
470 }
471 }
472
Christopher Tate7060b042014-06-09 19:50:00 -0700473 /**
474 * Initializes the system service.
475 * <p>
476 * Subclasses must define a single argument constructor that accepts the context
477 * and passes it to super.
478 * </p>
479 *
480 * @param context The system server context.
481 */
482 public JobSchedulerService(Context context) {
483 super(context);
484 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700485 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700486 mControllers.add(ConnectivityController.get(this));
487 mControllers.add(TimeController.get(this));
488 mControllers.add(IdleController.get(this));
489 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800490 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800491 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700492 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700493
494 mHandler = new JobHandler(context.getMainLooper());
495 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700496 mJobs = JobStore.initAndGet(this);
497 }
498
499 @Override
500 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000501 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -0700502 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
503 }
504
505 @Override
506 public void onBootPhase(int phase) {
507 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000508 // Register br for package removals and user removals.
Christopher Tate7060b042014-06-09 19:50:00 -0700509 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
510 filter.addDataScheme("package");
511 getContext().registerReceiverAsUser(
512 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
513 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
514 getContext().registerReceiverAsUser(
515 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000516 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700517 try {
518 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800519 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
520 | ActivityManager.UID_OBSERVER_IDLE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700521 } catch (RemoteException e) {
522 // ignored; both services live in system_server
523 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700524 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800525 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700526 // Let's go!
527 mReadyToRock = true;
528 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
529 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800530 mLocalDeviceIdleController
531 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700532 // Create the "runners".
533 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
534 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -0700535 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700536 getContext().getMainLooper()));
537 }
538 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -0800539 mJobs.forEachJob(new JobStatusFunctor() {
540 @Override
541 public void process(JobStatus job) {
542 for (int controller = 0; controller < mControllers.size(); controller++) {
543 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800544 sc.maybeStartTrackingJobLocked(job, null);
545 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700546 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800547 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700548 // GO GO GO!
549 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
550 }
Christopher Tate7060b042014-06-09 19:50:00 -0700551 }
552 }
553
554 /**
555 * Called when we have a job status object that we need to insert in our
556 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
557 * about.
558 */
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800559 private void startTrackingJob(JobStatus jobStatus, JobStatus lastJob) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800560 synchronized (mLock) {
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800561 final boolean update = mJobs.add(jobStatus);
562 if (mReadyToRock) {
563 for (int i = 0; i < mControllers.size(); i++) {
564 StateController controller = mControllers.get(i);
565 if (update) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700566 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800567 }
568 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700569 }
Christopher Tate7060b042014-06-09 19:50:00 -0700570 }
Christopher Tate7060b042014-06-09 19:50:00 -0700571 }
572 }
573
574 /**
575 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
576 * object removed.
577 */
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700578 private boolean stopTrackingJob(JobStatus jobStatus, JobStatus incomingJob,
579 boolean writeBack) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800580 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700581 // Remove from store as well as controllers.
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800582 final boolean removed = mJobs.remove(jobStatus, writeBack);
583 if (removed && mReadyToRock) {
584 for (int i=0; i<mControllers.size(); i++) {
585 StateController controller = mControllers.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700586 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800587 }
Christopher Tate7060b042014-06-09 19:50:00 -0700588 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800589 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -0700590 }
Christopher Tate7060b042014-06-09 19:50:00 -0700591 }
592
Shreyas Basarge5db09082016-01-07 13:38:29 +0000593 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700594 for (int i=0; i<mActiveServices.size(); i++) {
595 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700596 final JobStatus executing = jsc.getRunningJob();
597 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000598 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700599 return true;
600 }
601 }
602 return false;
603 }
604
605 /**
606 * @param job JobStatus we are querying against.
607 * @return Whether or not the job represented by the status object is currently being run or
608 * is pending.
609 */
610 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700611 for (int i=0; i<mActiveServices.size(); i++) {
612 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700613 final JobStatus running = serviceContext.getRunningJob();
614 if (running != null && running.matches(job.getUid(), job.getJobId())) {
615 return true;
616 }
617 }
618 return false;
619 }
620
Dianne Hackborn807de782016-04-07 17:54:41 -0700621 void noteJobsPending(List<JobStatus> jobs) {
622 for (int i = jobs.size() - 1; i >= 0; i--) {
623 JobStatus job = jobs.get(i);
624 mJobPackageTracker.notePending(job);
625 }
626 }
627
628 void noteJobsNonpending(List<JobStatus> jobs) {
629 for (int i = jobs.size() - 1; i >= 0; i--) {
630 JobStatus job = jobs.get(i);
631 mJobPackageTracker.noteNonpending(job);
632 }
633 }
634
Christopher Tate7060b042014-06-09 19:50:00 -0700635 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700636 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
637 * specify an override deadline on a failed job (the failed job will run even though it's not
638 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
639 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
640 *
Christopher Tate7060b042014-06-09 19:50:00 -0700641 * @param failureToReschedule Provided job status that we will reschedule.
642 * @return A newly instantiated JobStatus with the same constraints as the last job except
643 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700644 *
645 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700646 */
647 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
648 final long elapsedNowMillis = SystemClock.elapsedRealtime();
649 final JobInfo job = failureToReschedule.getJob();
650
651 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700652 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
653 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700654
655 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700656 case JobInfo.BACKOFF_POLICY_LINEAR:
657 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700658 break;
659 default:
660 if (DEBUG) {
661 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
662 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700663 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
664 delayMillis =
665 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700666 break;
667 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700668 delayMillis =
669 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800670 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -0700671 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800672 for (int ic=0; ic<mControllers.size(); ic++) {
673 StateController controller = mControllers.get(ic);
674 controller.rescheduleForFailure(newJob, failureToReschedule);
675 }
676 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -0700677 }
678
679 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700680 * Called after a periodic has executed so we can reschedule it. We take the last execution
681 * time of the job to be the time of completion (i.e. the time at which this function is
682 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700683 * This could be inaccurate b/c the job can run for as long as
684 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
685 * to underscheduling at least, rather than if we had taken the last execution time to be the
686 * start of the execution.
687 * @return A new job representing the execution criteria for this instantiation of the
688 * recurring job.
689 */
690 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
691 final long elapsedNow = SystemClock.elapsedRealtime();
692 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700693 long runEarly = 0L;
694
695 // If this periodic was rescheduled it won't have a deadline.
696 if (periodicToReschedule.hasDeadlineConstraint()) {
697 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
698 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000699 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700700 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000701 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
702 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -0700703
704 if (DEBUG) {
705 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
706 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
707 }
708 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
709 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
710 }
711
712 // JobCompletedListener implementations.
713
714 /**
715 * A job just finished executing. We fetch the
716 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
717 * whether we want to reschedule we readd it to the controllers.
718 * @param jobStatus Completed job.
719 * @param needsReschedule Whether the implementing class should reschedule this job.
720 */
721 @Override
722 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
723 if (DEBUG) {
724 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
725 }
Shreyas Basarge73f10252016-02-11 17:06:13 +0000726 // Do not write back immediately if this is a periodic job. The job may get lost if system
727 // shuts down before it is added back.
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700728 if (!stopTrackingJob(jobStatus, null, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700729 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700730 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700731 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800732 // We still want to check for jobs to execute, because this job may have
733 // scheduled a new job under the same job id, and now we can run it.
734 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700735 return;
736 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800737 // Note: there is a small window of time in here where, when rescheduling a job,
738 // we will stop monitoring its content providers. This should be fixed by stopping
739 // the old job after scheduling the new one, but since we have no lock held here
740 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -0700741 if (needsReschedule) {
742 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800743 startTrackingJob(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700744 } else if (jobStatus.getJob().isPeriodic()) {
745 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800746 startTrackingJob(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700747 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000748 reportActive();
749 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700750 }
751
752 // StateChangedListener implementations.
753
754 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700755 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
756 * some controller's state has changed, so as to run through the list of jobs and start/stop
757 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700758 */
759 @Override
760 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700761 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700762 }
763
764 @Override
765 public void onRunJobNow(JobStatus jobStatus) {
766 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
767 }
768
Christopher Tate7060b042014-06-09 19:50:00 -0700769 private class JobHandler extends Handler {
770
771 public JobHandler(Looper looper) {
772 super(looper);
773 }
774
775 @Override
776 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800777 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700778 if (!mReadyToRock) {
779 return;
780 }
781 }
Christopher Tate7060b042014-06-09 19:50:00 -0700782 switch (message.what) {
783 case MSG_JOB_EXPIRED:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800784 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700785 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700786 // runNow can be null, which is a controller's way of indicating that its
787 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700788 if (runNow != null && !mPendingJobs.contains(runNow)
789 && mJobs.containsJob(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -0700790 mJobPackageTracker.notePending(runNow);
Christopher Tate7060b042014-06-09 19:50:00 -0700791 mPendingJobs.add(runNow);
792 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700793 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700794 }
Christopher Tate7060b042014-06-09 19:50:00 -0700795 break;
796 case MSG_CHECK_JOB:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800797 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000798 if (mReportedActive) {
799 // if jobs are currently being run, queue all ready jobs for execution.
800 queueReadyJobsForExecutionLockedH();
801 } else {
802 // Check the list of jobs and run some of them if we feel inclined.
803 maybeQueueReadyJobsForExecutionLockedH();
804 }
805 }
806 break;
807 case MSG_CHECK_JOB_GREEDY:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800808 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000809 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700810 }
Christopher Tate7060b042014-06-09 19:50:00 -0700811 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700812 case MSG_STOP_JOB:
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700813 cancelJobImpl((JobStatus)message.obj, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700814 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700815 }
816 maybeRunPendingJobsH();
817 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
818 removeMessages(MSG_CHECK_JOB);
819 }
820
821 /**
822 * Run through list of jobs and execute all possible - at least one is expired so we do
823 * as many as we can.
824 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700825 private void queueReadyJobsForExecutionLockedH() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700826 if (DEBUG) {
827 Slog.d(TAG, "queuing all ready jobs for execution:");
828 }
Dianne Hackborn807de782016-04-07 17:54:41 -0700829 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800830 mPendingJobs.clear();
831 mJobs.forEachJob(mReadyQueueFunctor);
832 mReadyQueueFunctor.postProcess();
833
Matthew Williams48a30db2014-09-23 13:39:36 -0700834 if (DEBUG) {
835 final int queuedJobs = mPendingJobs.size();
836 if (queuedJobs == 0) {
837 Slog.d(TAG, "No jobs pending.");
838 } else {
839 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700840 }
Christopher Tate7060b042014-06-09 19:50:00 -0700841 }
842 }
843
Christopher Tate2f36fd62016-02-18 18:36:08 -0800844 class ReadyJobQueueFunctor implements JobStatusFunctor {
845 ArrayList<JobStatus> newReadyJobs;
846
847 @Override
848 public void process(JobStatus job) {
849 if (isReadyToBeExecutedLocked(job)) {
850 if (DEBUG) {
851 Slog.d(TAG, " queued " + job.toShortString());
852 }
853 if (newReadyJobs == null) {
854 newReadyJobs = new ArrayList<JobStatus>();
855 }
856 newReadyJobs.add(job);
857 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
858 stopJobOnServiceContextLocked(job,
859 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
860 }
861 }
862
863 public void postProcess() {
864 if (newReadyJobs != null) {
Dianne Hackborn807de782016-04-07 17:54:41 -0700865 noteJobsPending(newReadyJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800866 mPendingJobs.addAll(newReadyJobs);
867 }
868 newReadyJobs = null;
869 }
870 }
871 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
872
Christopher Tate7060b042014-06-09 19:50:00 -0700873 /**
874 * The state of at least one job has changed. Here is where we could enforce various
875 * policies on when we want to execute jobs.
876 * Right now the policy is such:
877 * If >1 of the ready jobs is idle mode we send all of them off
878 * if more than 2 network connectivity jobs are ready we send them all off.
879 * If more than 4 jobs total are ready we send them all off.
880 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
881 */
Christopher Tate2f36fd62016-02-18 18:36:08 -0800882 class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
883 int chargingCount;
884 int idleCount;
885 int backoffCount;
886 int connectivityCount;
887 int contentCount;
888 List<JobStatus> runnableJobs;
889
890 public MaybeReadyJobQueueFunctor() {
891 reset();
892 }
893
894 // Functor method invoked for each job via JobStore.forEachJob()
895 @Override
896 public void process(JobStatus job) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700897 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700898 try {
899 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
900 job.getJob().getService().getPackageName())
901 == ActivityManager.APP_START_MODE_DISABLED) {
902 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
903 + job.getJob().toString() + " -- package not allowed to start");
904 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800905 return;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700906 }
907 } catch (RemoteException e) {
908 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700909 if (job.getNumFailures() > 0) {
910 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700911 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700912 if (job.hasIdleConstraint()) {
913 idleCount++;
914 }
915 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
916 connectivityCount++;
917 }
918 if (job.hasChargingConstraint()) {
919 chargingCount++;
920 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800921 if (job.hasContentTriggerConstraint()) {
922 contentCount++;
923 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700924 if (runnableJobs == null) {
925 runnableJobs = new ArrayList<>();
926 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700927 runnableJobs.add(job);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800928 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000929 stopJobOnServiceContextLocked(job,
930 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700931 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700932 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800933
934 public void postProcess() {
935 if (backoffCount > 0 ||
936 idleCount >= MIN_IDLE_COUNT ||
937 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
938 chargingCount >= MIN_CHARGING_COUNT ||
939 contentCount >= MIN_CONTENT_COUNT ||
940 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
941 if (DEBUG) {
942 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
943 }
Dianne Hackborn807de782016-04-07 17:54:41 -0700944 noteJobsPending(runnableJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800945 mPendingJobs.addAll(runnableJobs);
946 } else {
947 if (DEBUG) {
948 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
949 }
Christopher Tate7060b042014-06-09 19:50:00 -0700950 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800951
952 // Be ready for next time
953 reset();
Matthew Williams48a30db2014-09-23 13:39:36 -0700954 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800955
956 private void reset() {
957 chargingCount = 0;
958 idleCount = 0;
959 backoffCount = 0;
960 connectivityCount = 0;
961 contentCount = 0;
962 runnableJobs = null;
963 }
964 }
965 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
966
967 private void maybeQueueReadyJobsForExecutionLockedH() {
968 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
969
Dianne Hackborn807de782016-04-07 17:54:41 -0700970 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800971 mPendingJobs.clear();
972 mJobs.forEachJob(mMaybeQueueFunctor);
973 mMaybeQueueFunctor.postProcess();
Christopher Tate7060b042014-06-09 19:50:00 -0700974 }
975
976 /**
977 * Criteria for moving a job into the pending queue:
978 * - It's ready.
979 * - It's not pending.
980 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700981 * - The user that requested the job is running.
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700982 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -0700983 */
984 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700985 final boolean jobReady = job.isReady();
986 final boolean jobPending = mPendingJobs.contains(job);
987 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700988
989 final int userId = job.getUserId();
990 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
991 final boolean componentPresent;
992 try {
993 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
994 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
995 userId) != null);
996 } catch (RemoteException e) {
997 throw e.rethrowAsRuntimeException();
998 }
999
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001000 if (DEBUG) {
1001 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1002 + " ready=" + jobReady + " pending=" + jobPending
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001003 + " active=" + jobActive + " userStarted=" + userStarted
1004 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001005 }
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001006 return userStarted && componentPresent && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -07001007 }
1008
1009 /**
1010 * Criteria for cancelling an active job:
1011 * - It's not ready
1012 * - It's running on a JSC.
1013 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001014 private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -07001015 return !job.isReady() && isCurrentlyActiveLocked(job);
1016 }
1017
1018 /**
1019 * Reconcile jobs in the pending queue against available execution contexts.
1020 * A controller can force a job into the pending queue even if it's already running, but
1021 * here is where we decide whether to actually execute it.
1022 */
1023 private void maybeRunPendingJobsH() {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001024 synchronized (mLock) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001025 if (DEBUG) {
1026 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1027 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001028 assignJobsToContextsLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001029 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -07001030 }
1031 }
1032 }
1033
Dianne Hackborn807de782016-04-07 17:54:41 -07001034 private int adjustJobPriority(int curPriority, JobStatus job) {
1035 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1036 float factor = mJobPackageTracker.getLoadFactor(job);
1037 if (factor >= HEAVY_USE_FACTOR) {
1038 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
1039 } else if (factor >= MODERATE_USE_FACTOR) {
1040 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1041 }
1042 }
1043 return curPriority;
1044 }
1045
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001046 private int evaluateJobPriorityLocked(JobStatus job) {
1047 int priority = job.getPriority();
1048 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001049 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001050 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001051 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1052 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001053 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001054 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001055 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001056 }
1057
Christopher Tate7060b042014-06-09 19:50:00 -07001058 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001059 * Takes jobs from pending queue and runs them on available contexts.
1060 * If no contexts are available, preempts lower priority jobs to
1061 * run higher priority ones.
1062 * Lock on mJobs before calling this function.
1063 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001064 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001065 if (DEBUG) {
1066 Slog.d(TAG, printPendingQueue());
1067 }
1068
Dianne Hackborn970510b2016-02-24 16:56:42 -08001069 int memLevel;
1070 try {
1071 memLevel = ActivityManagerNative.getDefault().getMemoryTrimLevel();
1072 } catch (RemoteException e) {
1073 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1074 }
1075 switch (memLevel) {
1076 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborn807de782016-04-07 17:54:41 -07001077 mMaxActiveJobs = ((MAX_JOB_CONTEXTS_COUNT - FG_JOB_CONTEXTS_COUNT) * 2) / 3;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001078 break;
1079 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborn807de782016-04-07 17:54:41 -07001080 mMaxActiveJobs = (MAX_JOB_CONTEXTS_COUNT - FG_JOB_CONTEXTS_COUNT) / 3;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001081 break;
1082 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
1083 mMaxActiveJobs = 1;
1084 break;
1085 default:
Dianne Hackborn807de782016-04-07 17:54:41 -07001086 mMaxActiveJobs = MAX_JOB_CONTEXTS_COUNT - FG_JOB_CONTEXTS_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001087 break;
1088 }
1089
1090 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1091 boolean[] act = mTmpAssignAct;
1092 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1093 int numActive = 0;
1094 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1095 final JobServiceContext js = mActiveServices.get(i);
1096 if ((contextIdToJobMap[i] = js.getRunningJob()) != null) {
1097 numActive++;
1098 }
1099 act[i] = false;
1100 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001101 }
1102 if (DEBUG) {
1103 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1104 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001105 for (int i=0; i<mPendingJobs.size(); i++) {
1106 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001107
1108 // If job is already running, go to next job.
1109 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1110 if (jobRunningContext != -1) {
1111 continue;
1112 }
1113
Dianne Hackborn970510b2016-02-24 16:56:42 -08001114 final int priority = evaluateJobPriorityLocked(nextPending);
1115 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001116
Shreyas Basarge5db09082016-01-07 13:38:29 +00001117 // Find a context for nextPending. The context should be available OR
1118 // it should have lowest priority among all running jobs
1119 // (sharing the same Uid as nextPending)
1120 int minPriority = Integer.MAX_VALUE;
1121 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001122 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1123 JobStatus job = contextIdToJobMap[j];
1124 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001125 if (job == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001126 if ((numActive < mMaxActiveJobs || priority >= JobInfo.PRIORITY_TOP_APP) &&
1127 (preferredUid == nextPending.getUid() ||
1128 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1129 // This slot is free, and we haven't yet hit the limit on
1130 // concurrent jobs... we can just throw the job in to here.
1131 minPriorityContextId = j;
1132 numActive++;
1133 break;
1134 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001135 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001136 // the context has a preferred Uid or we have reached the limit on
1137 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001138 continue;
1139 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001140 if (job.getUid() != nextPending.getUid()) {
1141 continue;
1142 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001143 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001144 continue;
1145 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001146 if (minPriority > nextPending.lastEvaluatedPriority) {
1147 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001148 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001149 }
1150 }
1151 if (minPriorityContextId != -1) {
1152 contextIdToJobMap[minPriorityContextId] = nextPending;
1153 act[minPriorityContextId] = true;
1154 }
1155 }
1156 if (DEBUG) {
1157 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1158 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001159 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001160 boolean preservePreferredUid = false;
1161 if (act[i]) {
1162 JobStatus js = mActiveServices.get(i).getRunningJob();
1163 if (js != null) {
1164 if (DEBUG) {
1165 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
1166 }
1167 // preferredUid will be set to uid of currently running job.
1168 mActiveServices.get(i).preemptExecutingJob();
1169 preservePreferredUid = true;
1170 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001171 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001172 if (DEBUG) {
1173 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001174 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001175 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001176 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001177 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001178 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001179 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1180 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001181 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001182 if (mPendingJobs.remove(pendingJob)) {
1183 mJobPackageTracker.noteNonpending(pendingJob);
1184 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001185 }
1186 }
1187 if (!preservePreferredUid) {
1188 mActiveServices.get(i).clearPreferredUid();
1189 }
1190 }
1191 }
1192
1193 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1194 for (int i=0; i<map.length; i++) {
1195 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1196 return i;
1197 }
1198 }
1199 return -1;
1200 }
1201
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001202 final class LocalService implements JobSchedulerInternal {
1203
1204 /**
1205 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1206 * jobs are always considered pending.
1207 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001208 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001209 public List<JobInfo> getSystemScheduledPendingJobs() {
1210 synchronized (mLock) {
1211 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1212 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1213 @Override
1214 public void process(JobStatus job) {
1215 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1216 pendingJobs.add(job.getJob());
1217 }
1218 }
1219 });
1220 return pendingJobs;
1221 }
1222 }
1223 }
1224
Shreyas Basarge5db09082016-01-07 13:38:29 +00001225 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001226 * Binder stub trampoline implementation
1227 */
1228 final class JobSchedulerStub extends IJobScheduler.Stub {
1229 /** Cache determination of whether a given app can persist jobs
1230 * key is uid of the calling app; value is undetermined/true/false
1231 */
1232 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1233
1234 // Enforce that only the app itself (or shared uid participant) can schedule a
1235 // job that runs one of the app's services, as well as verifying that the
1236 // named service properly requires the BIND_JOB_SERVICE permission
1237 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001238 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001239 final ComponentName service = job.getService();
1240 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001241 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001242 PackageManager.MATCH_DIRECT_BOOT_AWARE
1243 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001244 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001245 if (si == null) {
1246 throw new IllegalArgumentException("No such service " + service);
1247 }
Christopher Tate7060b042014-06-09 19:50:00 -07001248 if (si.applicationInfo.uid != uid) {
1249 throw new IllegalArgumentException("uid " + uid +
1250 " cannot schedule job in " + service.getPackageName());
1251 }
1252 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1253 throw new IllegalArgumentException("Scheduled service " + service
1254 + " does not require android.permission.BIND_JOB_SERVICE permission");
1255 }
Christopher Tate5568f542014-06-18 13:53:31 -07001256 } catch (RemoteException e) {
1257 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001258 }
1259 }
1260
1261 private boolean canPersistJobs(int pid, int uid) {
1262 // If we get this far we're good to go; all we need to do now is check
1263 // whether the app is allowed to persist its scheduled work.
1264 final boolean canPersist;
1265 synchronized (mPersistCache) {
1266 Boolean cached = mPersistCache.get(uid);
1267 if (cached != null) {
1268 canPersist = cached.booleanValue();
1269 } else {
1270 // Persisting jobs is tantamount to running at boot, so we permit
1271 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1272 // permission
1273 int result = getContext().checkPermission(
1274 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1275 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1276 mPersistCache.put(uid, canPersist);
1277 }
1278 }
1279 return canPersist;
1280 }
1281
1282 // IJobScheduler implementation
1283 @Override
1284 public int schedule(JobInfo job) throws RemoteException {
1285 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001286 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001287 }
1288 final int pid = Binder.getCallingPid();
1289 final int uid = Binder.getCallingUid();
1290
1291 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001292 if (job.isPersisted()) {
1293 if (!canPersistJobs(pid, uid)) {
1294 throw new IllegalArgumentException("Error: requested job be persisted without"
1295 + " holding RECEIVE_BOOT_COMPLETED permission.");
1296 }
1297 }
Christopher Tate7060b042014-06-09 19:50:00 -07001298
1299 long ident = Binder.clearCallingIdentity();
1300 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001301 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001302 } finally {
1303 Binder.restoreCallingIdentity(ident);
1304 }
1305 }
1306
1307 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001308 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001309 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001310 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001311 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001312 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1313 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001314 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001315
1316 if (packageName == null) {
1317 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001318 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001319
1320 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1321 android.Manifest.permission.UPDATE_DEVICE_STATS);
1322 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1323 throw new SecurityException("Caller uid " + callerUid
1324 + " not permitted to schedule jobs for other apps");
1325 }
1326
Shreyas Basarge968ac752016-01-11 23:09:26 +00001327 long ident = Binder.clearCallingIdentity();
1328 try {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001329 return JobSchedulerService.this.scheduleAsPackage(job, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001330 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001331 } finally {
1332 Binder.restoreCallingIdentity(ident);
1333 }
1334 }
1335
1336 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001337 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1338 final int uid = Binder.getCallingUid();
1339
1340 long ident = Binder.clearCallingIdentity();
1341 try {
1342 return JobSchedulerService.this.getPendingJobs(uid);
1343 } finally {
1344 Binder.restoreCallingIdentity(ident);
1345 }
1346 }
1347
1348 @Override
1349 public void cancelAll() throws RemoteException {
1350 final int uid = Binder.getCallingUid();
1351
1352 long ident = Binder.clearCallingIdentity();
1353 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001354 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001355 } finally {
1356 Binder.restoreCallingIdentity(ident);
1357 }
1358 }
1359
1360 @Override
1361 public void cancel(int jobId) throws RemoteException {
1362 final int uid = Binder.getCallingUid();
1363
1364 long ident = Binder.clearCallingIdentity();
1365 try {
1366 JobSchedulerService.this.cancelJob(uid, jobId);
1367 } finally {
1368 Binder.restoreCallingIdentity(ident);
1369 }
1370 }
1371
1372 /**
1373 * "dumpsys" infrastructure
1374 */
1375 @Override
1376 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1377 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1378
1379 long identityToken = Binder.clearCallingIdentity();
1380 try {
1381 JobSchedulerService.this.dumpInternal(pw);
1382 } finally {
1383 Binder.restoreCallingIdentity(identityToken);
1384 }
1385 }
Christopher Tate5d346052016-03-08 12:56:08 -08001386
1387 @Override
1388 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
1389 String[] args, ResultReceiver resultReceiver) throws RemoteException {
1390 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
1391 this, in, out, err, args, resultReceiver);
1392 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001393 };
1394
Christopher Tate5d346052016-03-08 12:56:08 -08001395 // Shell command infrastructure: run the given job immediately
1396 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
1397 if (DEBUG) {
1398 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
1399 + " " + jobId + " f=" + force);
1400 }
1401
1402 try {
1403 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0, userId);
1404 if (uid < 0) {
1405 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
1406 }
1407
1408 synchronized (mLock) {
1409 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
1410 if (js == null) {
1411 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
1412 }
1413
1414 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
1415 if (!js.isConstraintsSatisfied()) {
1416 js.overrideState = 0;
1417 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
1418 }
1419
1420 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
1421 }
1422 } catch (RemoteException e) {
1423 // can't happen
1424 }
1425 return 0;
1426 }
1427
Shreyas Basarge5db09082016-01-07 13:38:29 +00001428 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1429 StringBuilder s = new StringBuilder(initial + ": ");
1430 for (int i=0; i<map.length; i++) {
1431 s.append("(")
1432 .append(map[i] == null? -1: map[i].getJobId())
1433 .append(map[i] == null? -1: map[i].getUid())
1434 .append(")" );
1435 }
1436 return s.toString();
1437 }
1438
1439 private String printPendingQueue() {
1440 StringBuilder s = new StringBuilder("Pending queue: ");
1441 Iterator<JobStatus> it = mPendingJobs.iterator();
1442 while (it.hasNext()) {
1443 JobStatus js = it.next();
1444 s.append("(")
1445 .append(js.getJob().getId())
1446 .append(", ")
1447 .append(js.getUid())
1448 .append(") ");
1449 }
1450 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001451 }
Christopher Tate7060b042014-06-09 19:50:00 -07001452
Christopher Tate2f36fd62016-02-18 18:36:08 -08001453 void dumpInternal(final PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001454 final long now = SystemClock.elapsedRealtime();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001455 synchronized (mLock) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001456 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Christopher Tate7060b042014-06-09 19:50:00 -07001457 pw.println("Registered jobs:");
1458 if (mJobs.size() > 0) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001459 mJobs.forEachJob(new JobStatusFunctor() {
1460 private int index = 0;
1461
1462 @Override
1463 public void process(JobStatus job) {
1464 pw.print(" Job #"); pw.print(index++); pw.print(": ");
1465 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08001466 job.dump(pw, " ", true);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001467 pw.print(" Ready: ");
1468 pw.print(mHandler.isReadyToBeExecutedLocked(job));
1469 pw.print(" (job=");
1470 pw.print(job.isReady());
1471 pw.print(" pending=");
1472 pw.print(mPendingJobs.contains(job));
1473 pw.print(" active=");
1474 pw.print(isCurrentlyActiveLocked(job));
1475 pw.print(" user=");
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001476 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Christopher Tate2f36fd62016-02-18 18:36:08 -08001477 pw.println(")");
1478 }
1479 });
Christopher Tate7060b042014-06-09 19:50:00 -07001480 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001481 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001482 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001483 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001484 pw.println();
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001485 mControllers.get(i).dumpControllerStateLocked(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001486 }
1487 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001488 pw.println("Uid priority overrides:");
1489 for (int i=0; i< mUidPriorityOverride.size(); i++) {
1490 pw.print(" "); pw.print(UserHandle.formatUid(mUidPriorityOverride.keyAt(i)));
1491 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001492 }
1493 pw.println();
Dianne Hackborn807de782016-04-07 17:54:41 -07001494 mJobPackageTracker.dump(pw, "");
1495 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001496 pw.println("Pending queue:");
1497 for (int i=0; i<mPendingJobs.size(); i++) {
1498 JobStatus job = mPendingJobs.get(i);
1499 pw.print(" Pending #"); pw.print(i); pw.print(": ");
1500 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08001501 job.dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001502 int priority = evaluateJobPriorityLocked(job);
1503 if (priority != JobInfo.PRIORITY_DEFAULT) {
1504 pw.print(" Evaluated priority: "); pw.println(priority);
1505 }
1506 pw.print(" Tag: "); pw.println(job.getTag());
1507 }
Christopher Tate7060b042014-06-09 19:50:00 -07001508 pw.println();
1509 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001510 for (int i=0; i<mActiveServices.size(); i++) {
1511 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001512 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Shreyas Basarge5db09082016-01-07 13:38:29 +00001513 if (jsc.getRunningJob() == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001514 pw.println("inactive");
Christopher Tate7060b042014-06-09 19:50:00 -07001515 continue;
1516 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001517 pw.println(jsc.getRunningJob().toShortString());
1518 pw.print(" Running for: ");
1519 TimeUtils.formatDuration(now - jsc.getExecutionStartTimeElapsed(), pw);
1520 pw.print(", timeout at: ");
1521 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - now, pw);
1522 pw.println();
1523 jsc.getRunningJob().dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001524 int priority = evaluateJobPriorityLocked(jsc.getRunningJob());
1525 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001526 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001527 }
Christopher Tate7060b042014-06-09 19:50:00 -07001528 }
1529 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001530 pw.println();
1531 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001532 pw.print("mReportedActive="); pw.println(mReportedActive);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001533 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
Christopher Tate7060b042014-06-09 19:50:00 -07001534 }
1535 pw.println();
1536 }
1537}