blob: c4a2c731260071737c8844b647d1b2540a0dcaba [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
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700260 @Override
261 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700262 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
263 // Let's kick any outstanding jobs for this user.
264 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
265 }
266
267 @Override
268 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700269 // Let's kick any outstanding jobs for this user.
270 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
271 }
272
273 @Override
274 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700275 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700276 }
277
Christopher Tate7060b042014-06-09 19:50:00 -0700278 /**
279 * Entry point from client to schedule the provided job.
280 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
281 * @param job JobInfo object containing execution parameters
282 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700283 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
284 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700285 public int schedule(JobInfo job, int uId) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800286 return scheduleAsPackage(job, uId, null, -1, null);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000287 }
288
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800289 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId,
290 String tag) {
291 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700292 try {
293 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
294 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
295 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
296 + " -- package not allowed to start");
297 return JobScheduler.RESULT_FAILURE;
298 }
299 } catch (RemoteException e) {
300 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800301 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
302 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800303 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800304 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800305 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800306 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
307 Slog.w(TAG, "Too many jobs for uid " + uId);
308 throw new IllegalStateException("Apps may not schedule more than "
309 + MAX_JOBS_PER_APP + " distinct jobs");
310 }
311 }
312
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800313 toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700314 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700315 cancelJobImpl(toCancel, jobStatus);
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700316 }
317 startTrackingJob(jobStatus, toCancel);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800318 }
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700319 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700320 return JobScheduler.RESULT_SUCCESS;
321 }
322
323 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800324 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800325 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
326 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
327 for (int i = jobs.size() - 1; i >= 0; i--) {
328 JobStatus job = jobs.get(i);
329 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700330 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800331 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700332 }
Christopher Tate7060b042014-06-09 19:50:00 -0700333 }
334
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700335 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700336 List<JobStatus> jobsForUser;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800337 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700338 jobsForUser = mJobs.getJobsByUser(userHandle);
339 }
340 for (int i=0; i<jobsForUser.size(); i++) {
341 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700342 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700343 }
344 }
345
346 /**
347 * Entry point from client to cancel all jobs originating from their uid.
348 * This will remove the job from the master list, and cancel the job if it was staged for
349 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700350 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700351 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
352 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700353 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700354 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700355 List<JobStatus> jobsForUid;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800356 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700357 jobsForUid = mJobs.getJobsByUid(uid);
358 }
359 for (int i=0; i<jobsForUid.size(); i++) {
360 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700361 if (!forceAll) {
362 String packageName = toRemove.getServiceComponent().getPackageName();
363 try {
364 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
365 != ActivityManager.APP_START_MODE_DISABLED) {
366 continue;
367 }
368 } catch (RemoteException e) {
369 }
370 }
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700371 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700372 }
373 }
374
375 /**
376 * Entry point from client to cancel the job corresponding to the jobId provided.
377 * This will remove the job from the master list, and cancel the job if it was staged for
378 * execution or being executed.
379 * @param uid Uid of the calling client.
380 * @param jobId Id of the job, provided at schedule-time.
381 */
382 public void cancelJob(int uid, int jobId) {
383 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800384 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700385 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700386 }
387 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700388 cancelJobImpl(toCancel, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700389 }
390 }
391
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700392 private void cancelJobImpl(JobStatus cancelled, JobStatus incomingJob) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800393 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700394 stopTrackingJob(cancelled, incomingJob, true /* writeBack */);
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800395 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700396 // Remove from pending queue.
Dianne Hackborn807de782016-04-07 17:54:41 -0700397 if (mPendingJobs.remove(cancelled)) {
398 mJobPackageTracker.noteNonpending(cancelled);
399 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700400 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000401 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800402 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700403 }
Christopher Tate7060b042014-06-09 19:50:00 -0700404 }
405
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800406 void updateUidState(int uid, int procState) {
407 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800408 if (procState == ActivityManager.PROCESS_STATE_TOP) {
409 // Only use this if we are exactly the top app. All others can live
410 // with just the foreground priority. This means that persistent processes
411 // can never be the top app priority... that is fine.
412 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
413 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
414 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800415 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800416 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800417 }
418 }
419 }
420
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700421 @Override
422 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800423 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700424 if (deviceIdle) {
425 // When becoming idle, make sure no jobs are actively running.
426 for (int i=0; i<mActiveServices.size(); i++) {
427 JobServiceContext jsc = mActiveServices.get(i);
428 final JobStatus executing = jsc.getRunningJob();
429 if (executing != null) {
430 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
431 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700432 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700433 } else {
434 // When coming out of idle, allow thing to start back up.
435 if (mReadyToRock) {
436 if (mLocalDeviceIdleController != null) {
437 if (!mReportedActive) {
438 mReportedActive = true;
439 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700440 }
441 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700442 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700443 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700444 }
445 }
446 }
447
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800448 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000449 // active is true if pending queue contains jobs OR some job is running.
450 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800451 if (mPendingJobs.size() <= 0) {
452 for (int i=0; i<mActiveServices.size(); i++) {
453 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000454 if (jsc.getRunningJob() != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800455 active = true;
456 break;
457 }
458 }
459 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000460
461 if (mReportedActive != active) {
462 mReportedActive = active;
463 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800464 mLocalDeviceIdleController.setJobsActive(active);
465 }
466 }
467 }
468
Christopher Tate7060b042014-06-09 19:50:00 -0700469 /**
470 * Initializes the system service.
471 * <p>
472 * Subclasses must define a single argument constructor that accepts the context
473 * and passes it to super.
474 * </p>
475 *
476 * @param context The system server context.
477 */
478 public JobSchedulerService(Context context) {
479 super(context);
480 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700481 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700482 mControllers.add(ConnectivityController.get(this));
483 mControllers.add(TimeController.get(this));
484 mControllers.add(IdleController.get(this));
485 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800486 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800487 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700488 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700489
490 mHandler = new JobHandler(context.getMainLooper());
491 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700492 mJobs = JobStore.initAndGet(this);
493 }
494
495 @Override
496 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000497 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -0700498 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
499 }
500
501 @Override
502 public void onBootPhase(int phase) {
503 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000504 // Register br for package removals and user removals.
Christopher Tate7060b042014-06-09 19:50:00 -0700505 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
506 filter.addDataScheme("package");
507 getContext().registerReceiverAsUser(
508 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
509 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
510 getContext().registerReceiverAsUser(
511 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000512 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700513 try {
514 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800515 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
516 | ActivityManager.UID_OBSERVER_IDLE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700517 } catch (RemoteException e) {
518 // ignored; both services live in system_server
519 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700520 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800521 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700522 // Let's go!
523 mReadyToRock = true;
524 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
525 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800526 mLocalDeviceIdleController
527 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700528 // Create the "runners".
529 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
530 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -0700531 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700532 getContext().getMainLooper()));
533 }
534 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -0800535 mJobs.forEachJob(new JobStatusFunctor() {
536 @Override
537 public void process(JobStatus job) {
538 for (int controller = 0; controller < mControllers.size(); controller++) {
539 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800540 sc.maybeStartTrackingJobLocked(job, null);
541 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700542 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800543 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700544 // GO GO GO!
545 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
546 }
Christopher Tate7060b042014-06-09 19:50:00 -0700547 }
548 }
549
550 /**
551 * Called when we have a job status object that we need to insert in our
552 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
553 * about.
554 */
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800555 private void startTrackingJob(JobStatus jobStatus, JobStatus lastJob) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800556 synchronized (mLock) {
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800557 final boolean update = mJobs.add(jobStatus);
558 if (mReadyToRock) {
559 for (int i = 0; i < mControllers.size(); i++) {
560 StateController controller = mControllers.get(i);
561 if (update) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700562 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800563 }
564 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700565 }
Christopher Tate7060b042014-06-09 19:50:00 -0700566 }
Christopher Tate7060b042014-06-09 19:50:00 -0700567 }
568 }
569
570 /**
571 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
572 * object removed.
573 */
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700574 private boolean stopTrackingJob(JobStatus jobStatus, JobStatus incomingJob,
575 boolean writeBack) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800576 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700577 // Remove from store as well as controllers.
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800578 final boolean removed = mJobs.remove(jobStatus, writeBack);
579 if (removed && mReadyToRock) {
580 for (int i=0; i<mControllers.size(); i++) {
581 StateController controller = mControllers.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700582 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800583 }
Christopher Tate7060b042014-06-09 19:50:00 -0700584 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800585 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -0700586 }
Christopher Tate7060b042014-06-09 19:50:00 -0700587 }
588
Shreyas Basarge5db09082016-01-07 13:38:29 +0000589 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700590 for (int i=0; i<mActiveServices.size(); i++) {
591 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700592 final JobStatus executing = jsc.getRunningJob();
593 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000594 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700595 return true;
596 }
597 }
598 return false;
599 }
600
601 /**
602 * @param job JobStatus we are querying against.
603 * @return Whether or not the job represented by the status object is currently being run or
604 * is pending.
605 */
606 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700607 for (int i=0; i<mActiveServices.size(); i++) {
608 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700609 final JobStatus running = serviceContext.getRunningJob();
610 if (running != null && running.matches(job.getUid(), job.getJobId())) {
611 return true;
612 }
613 }
614 return false;
615 }
616
Dianne Hackborn807de782016-04-07 17:54:41 -0700617 void noteJobsPending(List<JobStatus> jobs) {
618 for (int i = jobs.size() - 1; i >= 0; i--) {
619 JobStatus job = jobs.get(i);
620 mJobPackageTracker.notePending(job);
621 }
622 }
623
624 void noteJobsNonpending(List<JobStatus> jobs) {
625 for (int i = jobs.size() - 1; i >= 0; i--) {
626 JobStatus job = jobs.get(i);
627 mJobPackageTracker.noteNonpending(job);
628 }
629 }
630
Christopher Tate7060b042014-06-09 19:50:00 -0700631 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700632 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
633 * specify an override deadline on a failed job (the failed job will run even though it's not
634 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
635 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
636 *
Christopher Tate7060b042014-06-09 19:50:00 -0700637 * @param failureToReschedule Provided job status that we will reschedule.
638 * @return A newly instantiated JobStatus with the same constraints as the last job except
639 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700640 *
641 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700642 */
643 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
644 final long elapsedNowMillis = SystemClock.elapsedRealtime();
645 final JobInfo job = failureToReschedule.getJob();
646
647 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700648 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
649 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700650
651 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700652 case JobInfo.BACKOFF_POLICY_LINEAR:
653 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700654 break;
655 default:
656 if (DEBUG) {
657 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
658 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700659 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
660 delayMillis =
661 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700662 break;
663 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700664 delayMillis =
665 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800666 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -0700667 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800668 for (int ic=0; ic<mControllers.size(); ic++) {
669 StateController controller = mControllers.get(ic);
670 controller.rescheduleForFailure(newJob, failureToReschedule);
671 }
672 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -0700673 }
674
675 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700676 * Called after a periodic has executed so we can reschedule it. We take the last execution
677 * time of the job to be the time of completion (i.e. the time at which this function is
678 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700679 * This could be inaccurate b/c the job can run for as long as
680 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
681 * to underscheduling at least, rather than if we had taken the last execution time to be the
682 * start of the execution.
683 * @return A new job representing the execution criteria for this instantiation of the
684 * recurring job.
685 */
686 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
687 final long elapsedNow = SystemClock.elapsedRealtime();
688 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700689 long runEarly = 0L;
690
691 // If this periodic was rescheduled it won't have a deadline.
692 if (periodicToReschedule.hasDeadlineConstraint()) {
693 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
694 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000695 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700696 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000697 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
698 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -0700699
700 if (DEBUG) {
701 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
702 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
703 }
704 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
705 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
706 }
707
708 // JobCompletedListener implementations.
709
710 /**
711 * A job just finished executing. We fetch the
712 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
713 * whether we want to reschedule we readd it to the controllers.
714 * @param jobStatus Completed job.
715 * @param needsReschedule Whether the implementing class should reschedule this job.
716 */
717 @Override
718 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
719 if (DEBUG) {
720 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
721 }
Shreyas Basarge73f10252016-02-11 17:06:13 +0000722 // Do not write back immediately if this is a periodic job. The job may get lost if system
723 // shuts down before it is added back.
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700724 if (!stopTrackingJob(jobStatus, null, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700725 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700726 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700727 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800728 // We still want to check for jobs to execute, because this job may have
729 // scheduled a new job under the same job id, and now we can run it.
730 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700731 return;
732 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800733 // Note: there is a small window of time in here where, when rescheduling a job,
734 // we will stop monitoring its content providers. This should be fixed by stopping
735 // the old job after scheduling the new one, but since we have no lock held here
736 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -0700737 if (needsReschedule) {
738 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800739 startTrackingJob(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700740 } else if (jobStatus.getJob().isPeriodic()) {
741 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800742 startTrackingJob(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700743 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000744 reportActive();
745 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700746 }
747
748 // StateChangedListener implementations.
749
750 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700751 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
752 * some controller's state has changed, so as to run through the list of jobs and start/stop
753 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700754 */
755 @Override
756 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700757 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700758 }
759
760 @Override
761 public void onRunJobNow(JobStatus jobStatus) {
762 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
763 }
764
Christopher Tate7060b042014-06-09 19:50:00 -0700765 private class JobHandler extends Handler {
766
767 public JobHandler(Looper looper) {
768 super(looper);
769 }
770
771 @Override
772 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800773 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700774 if (!mReadyToRock) {
775 return;
776 }
777 }
Christopher Tate7060b042014-06-09 19:50:00 -0700778 switch (message.what) {
779 case MSG_JOB_EXPIRED:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800780 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700781 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700782 // runNow can be null, which is a controller's way of indicating that its
783 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700784 if (runNow != null && !mPendingJobs.contains(runNow)
785 && mJobs.containsJob(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -0700786 mJobPackageTracker.notePending(runNow);
Christopher Tate7060b042014-06-09 19:50:00 -0700787 mPendingJobs.add(runNow);
788 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700789 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700790 }
Christopher Tate7060b042014-06-09 19:50:00 -0700791 break;
792 case MSG_CHECK_JOB:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800793 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000794 if (mReportedActive) {
795 // if jobs are currently being run, queue all ready jobs for execution.
796 queueReadyJobsForExecutionLockedH();
797 } else {
798 // Check the list of jobs and run some of them if we feel inclined.
799 maybeQueueReadyJobsForExecutionLockedH();
800 }
801 }
802 break;
803 case MSG_CHECK_JOB_GREEDY:
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800804 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000805 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700806 }
Christopher Tate7060b042014-06-09 19:50:00 -0700807 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700808 case MSG_STOP_JOB:
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700809 cancelJobImpl((JobStatus)message.obj, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700810 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700811 }
812 maybeRunPendingJobsH();
813 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
814 removeMessages(MSG_CHECK_JOB);
815 }
816
817 /**
818 * Run through list of jobs and execute all possible - at least one is expired so we do
819 * as many as we can.
820 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700821 private void queueReadyJobsForExecutionLockedH() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700822 if (DEBUG) {
823 Slog.d(TAG, "queuing all ready jobs for execution:");
824 }
Dianne Hackborn807de782016-04-07 17:54:41 -0700825 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800826 mPendingJobs.clear();
827 mJobs.forEachJob(mReadyQueueFunctor);
828 mReadyQueueFunctor.postProcess();
829
Matthew Williams48a30db2014-09-23 13:39:36 -0700830 if (DEBUG) {
831 final int queuedJobs = mPendingJobs.size();
832 if (queuedJobs == 0) {
833 Slog.d(TAG, "No jobs pending.");
834 } else {
835 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700836 }
Christopher Tate7060b042014-06-09 19:50:00 -0700837 }
838 }
839
Christopher Tate2f36fd62016-02-18 18:36:08 -0800840 class ReadyJobQueueFunctor implements JobStatusFunctor {
841 ArrayList<JobStatus> newReadyJobs;
842
843 @Override
844 public void process(JobStatus job) {
845 if (isReadyToBeExecutedLocked(job)) {
846 if (DEBUG) {
847 Slog.d(TAG, " queued " + job.toShortString());
848 }
849 if (newReadyJobs == null) {
850 newReadyJobs = new ArrayList<JobStatus>();
851 }
852 newReadyJobs.add(job);
853 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
854 stopJobOnServiceContextLocked(job,
855 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
856 }
857 }
858
859 public void postProcess() {
860 if (newReadyJobs != null) {
Dianne Hackborn807de782016-04-07 17:54:41 -0700861 noteJobsPending(newReadyJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800862 mPendingJobs.addAll(newReadyJobs);
863 }
864 newReadyJobs = null;
865 }
866 }
867 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
868
Christopher Tate7060b042014-06-09 19:50:00 -0700869 /**
870 * The state of at least one job has changed. Here is where we could enforce various
871 * policies on when we want to execute jobs.
872 * Right now the policy is such:
873 * If >1 of the ready jobs is idle mode we send all of them off
874 * if more than 2 network connectivity jobs are ready we send them all off.
875 * If more than 4 jobs total are ready we send them all off.
876 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
877 */
Christopher Tate2f36fd62016-02-18 18:36:08 -0800878 class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
879 int chargingCount;
880 int idleCount;
881 int backoffCount;
882 int connectivityCount;
883 int contentCount;
884 List<JobStatus> runnableJobs;
885
886 public MaybeReadyJobQueueFunctor() {
887 reset();
888 }
889
890 // Functor method invoked for each job via JobStore.forEachJob()
891 @Override
892 public void process(JobStatus job) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700893 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700894 try {
895 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
896 job.getJob().getService().getPackageName())
897 == ActivityManager.APP_START_MODE_DISABLED) {
898 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
899 + job.getJob().toString() + " -- package not allowed to start");
900 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800901 return;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700902 }
903 } catch (RemoteException e) {
904 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700905 if (job.getNumFailures() > 0) {
906 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700907 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700908 if (job.hasIdleConstraint()) {
909 idleCount++;
910 }
911 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
912 connectivityCount++;
913 }
914 if (job.hasChargingConstraint()) {
915 chargingCount++;
916 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800917 if (job.hasContentTriggerConstraint()) {
918 contentCount++;
919 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700920 if (runnableJobs == null) {
921 runnableJobs = new ArrayList<>();
922 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700923 runnableJobs.add(job);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800924 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000925 stopJobOnServiceContextLocked(job,
926 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700927 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700928 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800929
930 public void postProcess() {
931 if (backoffCount > 0 ||
932 idleCount >= MIN_IDLE_COUNT ||
933 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
934 chargingCount >= MIN_CHARGING_COUNT ||
935 contentCount >= MIN_CONTENT_COUNT ||
936 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
937 if (DEBUG) {
938 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
939 }
Dianne Hackborn807de782016-04-07 17:54:41 -0700940 noteJobsPending(runnableJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800941 mPendingJobs.addAll(runnableJobs);
942 } else {
943 if (DEBUG) {
944 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
945 }
Christopher Tate7060b042014-06-09 19:50:00 -0700946 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800947
948 // Be ready for next time
949 reset();
Matthew Williams48a30db2014-09-23 13:39:36 -0700950 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800951
952 private void reset() {
953 chargingCount = 0;
954 idleCount = 0;
955 backoffCount = 0;
956 connectivityCount = 0;
957 contentCount = 0;
958 runnableJobs = null;
959 }
960 }
961 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
962
963 private void maybeQueueReadyJobsForExecutionLockedH() {
964 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
965
Dianne Hackborn807de782016-04-07 17:54:41 -0700966 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800967 mPendingJobs.clear();
968 mJobs.forEachJob(mMaybeQueueFunctor);
969 mMaybeQueueFunctor.postProcess();
Christopher Tate7060b042014-06-09 19:50:00 -0700970 }
971
972 /**
973 * Criteria for moving a job into the pending queue:
974 * - It's ready.
975 * - It's not pending.
976 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700977 * - The user that requested the job is running.
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700978 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -0700979 */
980 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700981 final boolean jobReady = job.isReady();
982 final boolean jobPending = mPendingJobs.contains(job);
983 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700984
985 final int userId = job.getUserId();
986 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
987 final boolean componentPresent;
988 try {
989 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
990 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
991 userId) != null);
992 } catch (RemoteException e) {
993 throw e.rethrowAsRuntimeException();
994 }
995
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700996 if (DEBUG) {
997 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
998 + " ready=" + jobReady + " pending=" + jobPending
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700999 + " active=" + jobActive + " userStarted=" + userStarted
1000 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001001 }
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001002 return userStarted && componentPresent && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -07001003 }
1004
1005 /**
1006 * Criteria for cancelling an active job:
1007 * - It's not ready
1008 * - It's running on a JSC.
1009 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001010 private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -07001011 return !job.isReady() && isCurrentlyActiveLocked(job);
1012 }
1013
1014 /**
1015 * Reconcile jobs in the pending queue against available execution contexts.
1016 * A controller can force a job into the pending queue even if it's already running, but
1017 * here is where we decide whether to actually execute it.
1018 */
1019 private void maybeRunPendingJobsH() {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001020 synchronized (mLock) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001021 if (DEBUG) {
1022 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1023 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001024 assignJobsToContextsLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001025 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -07001026 }
1027 }
1028 }
1029
Dianne Hackborn807de782016-04-07 17:54:41 -07001030 private int adjustJobPriority(int curPriority, JobStatus job) {
1031 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1032 float factor = mJobPackageTracker.getLoadFactor(job);
1033 if (factor >= HEAVY_USE_FACTOR) {
1034 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
1035 } else if (factor >= MODERATE_USE_FACTOR) {
1036 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1037 }
1038 }
1039 return curPriority;
1040 }
1041
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001042 private int evaluateJobPriorityLocked(JobStatus job) {
1043 int priority = job.getPriority();
1044 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001045 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001046 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001047 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1048 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001049 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001050 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001051 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001052 }
1053
Christopher Tate7060b042014-06-09 19:50:00 -07001054 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001055 * Takes jobs from pending queue and runs them on available contexts.
1056 * If no contexts are available, preempts lower priority jobs to
1057 * run higher priority ones.
1058 * Lock on mJobs before calling this function.
1059 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001060 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001061 if (DEBUG) {
1062 Slog.d(TAG, printPendingQueue());
1063 }
1064
Dianne Hackborn970510b2016-02-24 16:56:42 -08001065 int memLevel;
1066 try {
1067 memLevel = ActivityManagerNative.getDefault().getMemoryTrimLevel();
1068 } catch (RemoteException e) {
1069 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1070 }
1071 switch (memLevel) {
1072 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborn807de782016-04-07 17:54:41 -07001073 mMaxActiveJobs = ((MAX_JOB_CONTEXTS_COUNT - FG_JOB_CONTEXTS_COUNT) * 2) / 3;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001074 break;
1075 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborn807de782016-04-07 17:54:41 -07001076 mMaxActiveJobs = (MAX_JOB_CONTEXTS_COUNT - FG_JOB_CONTEXTS_COUNT) / 3;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001077 break;
1078 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
1079 mMaxActiveJobs = 1;
1080 break;
1081 default:
Dianne Hackborn807de782016-04-07 17:54:41 -07001082 mMaxActiveJobs = MAX_JOB_CONTEXTS_COUNT - FG_JOB_CONTEXTS_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001083 break;
1084 }
1085
1086 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1087 boolean[] act = mTmpAssignAct;
1088 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1089 int numActive = 0;
1090 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1091 final JobServiceContext js = mActiveServices.get(i);
1092 if ((contextIdToJobMap[i] = js.getRunningJob()) != null) {
1093 numActive++;
1094 }
1095 act[i] = false;
1096 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001097 }
1098 if (DEBUG) {
1099 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1100 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001101 for (int i=0; i<mPendingJobs.size(); i++) {
1102 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001103
1104 // If job is already running, go to next job.
1105 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1106 if (jobRunningContext != -1) {
1107 continue;
1108 }
1109
Dianne Hackborn970510b2016-02-24 16:56:42 -08001110 final int priority = evaluateJobPriorityLocked(nextPending);
1111 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001112
Shreyas Basarge5db09082016-01-07 13:38:29 +00001113 // Find a context for nextPending. The context should be available OR
1114 // it should have lowest priority among all running jobs
1115 // (sharing the same Uid as nextPending)
1116 int minPriority = Integer.MAX_VALUE;
1117 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001118 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1119 JobStatus job = contextIdToJobMap[j];
1120 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001121 if (job == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001122 if ((numActive < mMaxActiveJobs || priority >= JobInfo.PRIORITY_TOP_APP) &&
1123 (preferredUid == nextPending.getUid() ||
1124 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1125 // This slot is free, and we haven't yet hit the limit on
1126 // concurrent jobs... we can just throw the job in to here.
1127 minPriorityContextId = j;
1128 numActive++;
1129 break;
1130 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001131 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001132 // the context has a preferred Uid or we have reached the limit on
1133 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001134 continue;
1135 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001136 if (job.getUid() != nextPending.getUid()) {
1137 continue;
1138 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001139 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001140 continue;
1141 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001142 if (minPriority > nextPending.lastEvaluatedPriority) {
1143 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001144 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001145 }
1146 }
1147 if (minPriorityContextId != -1) {
1148 contextIdToJobMap[minPriorityContextId] = nextPending;
1149 act[minPriorityContextId] = true;
1150 }
1151 }
1152 if (DEBUG) {
1153 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1154 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001155 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001156 boolean preservePreferredUid = false;
1157 if (act[i]) {
1158 JobStatus js = mActiveServices.get(i).getRunningJob();
1159 if (js != null) {
1160 if (DEBUG) {
1161 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
1162 }
1163 // preferredUid will be set to uid of currently running job.
1164 mActiveServices.get(i).preemptExecutingJob();
1165 preservePreferredUid = true;
1166 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001167 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001168 if (DEBUG) {
1169 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001170 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001171 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001172 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001173 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001174 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001175 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1176 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001177 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001178 if (mPendingJobs.remove(pendingJob)) {
1179 mJobPackageTracker.noteNonpending(pendingJob);
1180 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001181 }
1182 }
1183 if (!preservePreferredUid) {
1184 mActiveServices.get(i).clearPreferredUid();
1185 }
1186 }
1187 }
1188
1189 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1190 for (int i=0; i<map.length; i++) {
1191 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1192 return i;
1193 }
1194 }
1195 return -1;
1196 }
1197
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001198 final class LocalService implements JobSchedulerInternal {
1199
1200 /**
1201 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1202 * jobs are always considered pending.
1203 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001204 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001205 public List<JobInfo> getSystemScheduledPendingJobs() {
1206 synchronized (mLock) {
1207 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1208 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1209 @Override
1210 public void process(JobStatus job) {
1211 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1212 pendingJobs.add(job.getJob());
1213 }
1214 }
1215 });
1216 return pendingJobs;
1217 }
1218 }
1219 }
1220
Shreyas Basarge5db09082016-01-07 13:38:29 +00001221 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001222 * Binder stub trampoline implementation
1223 */
1224 final class JobSchedulerStub extends IJobScheduler.Stub {
1225 /** Cache determination of whether a given app can persist jobs
1226 * key is uid of the calling app; value is undetermined/true/false
1227 */
1228 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1229
1230 // Enforce that only the app itself (or shared uid participant) can schedule a
1231 // job that runs one of the app's services, as well as verifying that the
1232 // named service properly requires the BIND_JOB_SERVICE permission
1233 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001234 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001235 final ComponentName service = job.getService();
1236 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001237 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001238 PackageManager.MATCH_DIRECT_BOOT_AWARE
1239 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001240 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001241 if (si == null) {
1242 throw new IllegalArgumentException("No such service " + service);
1243 }
Christopher Tate7060b042014-06-09 19:50:00 -07001244 if (si.applicationInfo.uid != uid) {
1245 throw new IllegalArgumentException("uid " + uid +
1246 " cannot schedule job in " + service.getPackageName());
1247 }
1248 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1249 throw new IllegalArgumentException("Scheduled service " + service
1250 + " does not require android.permission.BIND_JOB_SERVICE permission");
1251 }
Christopher Tate5568f542014-06-18 13:53:31 -07001252 } catch (RemoteException e) {
1253 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001254 }
1255 }
1256
1257 private boolean canPersistJobs(int pid, int uid) {
1258 // If we get this far we're good to go; all we need to do now is check
1259 // whether the app is allowed to persist its scheduled work.
1260 final boolean canPersist;
1261 synchronized (mPersistCache) {
1262 Boolean cached = mPersistCache.get(uid);
1263 if (cached != null) {
1264 canPersist = cached.booleanValue();
1265 } else {
1266 // Persisting jobs is tantamount to running at boot, so we permit
1267 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1268 // permission
1269 int result = getContext().checkPermission(
1270 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1271 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1272 mPersistCache.put(uid, canPersist);
1273 }
1274 }
1275 return canPersist;
1276 }
1277
1278 // IJobScheduler implementation
1279 @Override
1280 public int schedule(JobInfo job) throws RemoteException {
1281 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001282 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001283 }
1284 final int pid = Binder.getCallingPid();
1285 final int uid = Binder.getCallingUid();
1286
1287 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001288 if (job.isPersisted()) {
1289 if (!canPersistJobs(pid, uid)) {
1290 throw new IllegalArgumentException("Error: requested job be persisted without"
1291 + " holding RECEIVE_BOOT_COMPLETED permission.");
1292 }
1293 }
Christopher Tate7060b042014-06-09 19:50:00 -07001294
1295 long ident = Binder.clearCallingIdentity();
1296 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001297 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001298 } finally {
1299 Binder.restoreCallingIdentity(ident);
1300 }
1301 }
1302
1303 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001304 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001305 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001306 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001307 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001308 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1309 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001310 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001311
1312 if (packageName == null) {
1313 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001314 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001315
1316 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1317 android.Manifest.permission.UPDATE_DEVICE_STATS);
1318 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1319 throw new SecurityException("Caller uid " + callerUid
1320 + " not permitted to schedule jobs for other apps");
1321 }
1322
Shreyas Basarge968ac752016-01-11 23:09:26 +00001323 long ident = Binder.clearCallingIdentity();
1324 try {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001325 return JobSchedulerService.this.scheduleAsPackage(job, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001326 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001327 } finally {
1328 Binder.restoreCallingIdentity(ident);
1329 }
1330 }
1331
1332 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001333 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1334 final int uid = Binder.getCallingUid();
1335
1336 long ident = Binder.clearCallingIdentity();
1337 try {
1338 return JobSchedulerService.this.getPendingJobs(uid);
1339 } finally {
1340 Binder.restoreCallingIdentity(ident);
1341 }
1342 }
1343
1344 @Override
1345 public void cancelAll() throws RemoteException {
1346 final int uid = Binder.getCallingUid();
1347
1348 long ident = Binder.clearCallingIdentity();
1349 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001350 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001351 } finally {
1352 Binder.restoreCallingIdentity(ident);
1353 }
1354 }
1355
1356 @Override
1357 public void cancel(int jobId) throws RemoteException {
1358 final int uid = Binder.getCallingUid();
1359
1360 long ident = Binder.clearCallingIdentity();
1361 try {
1362 JobSchedulerService.this.cancelJob(uid, jobId);
1363 } finally {
1364 Binder.restoreCallingIdentity(ident);
1365 }
1366 }
1367
1368 /**
1369 * "dumpsys" infrastructure
1370 */
1371 @Override
1372 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1373 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1374
1375 long identityToken = Binder.clearCallingIdentity();
1376 try {
1377 JobSchedulerService.this.dumpInternal(pw);
1378 } finally {
1379 Binder.restoreCallingIdentity(identityToken);
1380 }
1381 }
Christopher Tate5d346052016-03-08 12:56:08 -08001382
1383 @Override
1384 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
1385 String[] args, ResultReceiver resultReceiver) throws RemoteException {
1386 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
1387 this, in, out, err, args, resultReceiver);
1388 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001389 };
1390
Christopher Tate5d346052016-03-08 12:56:08 -08001391 // Shell command infrastructure: run the given job immediately
1392 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
1393 if (DEBUG) {
1394 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
1395 + " " + jobId + " f=" + force);
1396 }
1397
1398 try {
1399 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0, userId);
1400 if (uid < 0) {
1401 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
1402 }
1403
1404 synchronized (mLock) {
1405 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
1406 if (js == null) {
1407 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
1408 }
1409
1410 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
1411 if (!js.isConstraintsSatisfied()) {
1412 js.overrideState = 0;
1413 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
1414 }
1415
1416 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
1417 }
1418 } catch (RemoteException e) {
1419 // can't happen
1420 }
1421 return 0;
1422 }
1423
Shreyas Basarge5db09082016-01-07 13:38:29 +00001424 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1425 StringBuilder s = new StringBuilder(initial + ": ");
1426 for (int i=0; i<map.length; i++) {
1427 s.append("(")
1428 .append(map[i] == null? -1: map[i].getJobId())
1429 .append(map[i] == null? -1: map[i].getUid())
1430 .append(")" );
1431 }
1432 return s.toString();
1433 }
1434
1435 private String printPendingQueue() {
1436 StringBuilder s = new StringBuilder("Pending queue: ");
1437 Iterator<JobStatus> it = mPendingJobs.iterator();
1438 while (it.hasNext()) {
1439 JobStatus js = it.next();
1440 s.append("(")
1441 .append(js.getJob().getId())
1442 .append(", ")
1443 .append(js.getUid())
1444 .append(") ");
1445 }
1446 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001447 }
Christopher Tate7060b042014-06-09 19:50:00 -07001448
Christopher Tate2f36fd62016-02-18 18:36:08 -08001449 void dumpInternal(final PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001450 final long now = SystemClock.elapsedRealtime();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001451 synchronized (mLock) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001452 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Christopher Tate7060b042014-06-09 19:50:00 -07001453 pw.println("Registered jobs:");
1454 if (mJobs.size() > 0) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001455 mJobs.forEachJob(new JobStatusFunctor() {
1456 private int index = 0;
1457
1458 @Override
1459 public void process(JobStatus job) {
1460 pw.print(" Job #"); pw.print(index++); pw.print(": ");
1461 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08001462 job.dump(pw, " ", true);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001463 pw.print(" Ready: ");
1464 pw.print(mHandler.isReadyToBeExecutedLocked(job));
1465 pw.print(" (job=");
1466 pw.print(job.isReady());
1467 pw.print(" pending=");
1468 pw.print(mPendingJobs.contains(job));
1469 pw.print(" active=");
1470 pw.print(isCurrentlyActiveLocked(job));
1471 pw.print(" user=");
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001472 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Christopher Tate2f36fd62016-02-18 18:36:08 -08001473 pw.println(")");
1474 }
1475 });
Christopher Tate7060b042014-06-09 19:50:00 -07001476 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001477 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001478 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001479 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001480 pw.println();
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001481 mControllers.get(i).dumpControllerStateLocked(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001482 }
1483 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001484 pw.println("Uid priority overrides:");
1485 for (int i=0; i< mUidPriorityOverride.size(); i++) {
1486 pw.print(" "); pw.print(UserHandle.formatUid(mUidPriorityOverride.keyAt(i)));
1487 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001488 }
1489 pw.println();
Dianne Hackborn807de782016-04-07 17:54:41 -07001490 mJobPackageTracker.dump(pw, "");
1491 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001492 pw.println("Pending queue:");
1493 for (int i=0; i<mPendingJobs.size(); i++) {
1494 JobStatus job = mPendingJobs.get(i);
1495 pw.print(" Pending #"); pw.print(i); pw.print(": ");
1496 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08001497 job.dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001498 int priority = evaluateJobPriorityLocked(job);
1499 if (priority != JobInfo.PRIORITY_DEFAULT) {
1500 pw.print(" Evaluated priority: "); pw.println(priority);
1501 }
1502 pw.print(" Tag: "); pw.println(job.getTag());
1503 }
Christopher Tate7060b042014-06-09 19:50:00 -07001504 pw.println();
1505 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001506 for (int i=0; i<mActiveServices.size(); i++) {
1507 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001508 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Shreyas Basarge5db09082016-01-07 13:38:29 +00001509 if (jsc.getRunningJob() == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001510 pw.println("inactive");
Christopher Tate7060b042014-06-09 19:50:00 -07001511 continue;
1512 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001513 pw.println(jsc.getRunningJob().toShortString());
1514 pw.print(" Running for: ");
1515 TimeUtils.formatDuration(now - jsc.getExecutionStartTimeElapsed(), pw);
1516 pw.print(", timeout at: ");
1517 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - now, pw);
1518 pw.println();
1519 jsc.getRunningJob().dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001520 int priority = evaluateJobPriorityLocked(jsc.getRunningJob());
1521 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001522 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001523 }
Christopher Tate7060b042014-06-09 19:50:00 -07001524 }
1525 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001526 pw.println();
1527 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001528 pw.print("mReportedActive="); pw.println(mReportedActive);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001529 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
Christopher Tate7060b042014-06-09 19:50:00 -07001530 }
1531 pw.println();
1532 }
1533}