blob: 4028372816092f6bc01552c1a653abff1abe32fd [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.job;
18
Shreyas Basarge5db09082016-01-07 13:38:29 +000019import java.io.FileDescriptor;
20import java.io.PrintWriter;
21import java.util.ArrayList;
22import java.util.Iterator;
23import java.util.List;
24
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070025import android.app.ActivityManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070026import android.app.ActivityManagerNative;
Christopher Tate5568f542014-06-18 13:53:31 -070027import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000030import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070031import android.app.job.JobScheduler;
32import android.app.job.JobService;
Shreyas Basarge5db09082016-01-07 13:38:29 +000033import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070034import android.content.BroadcastReceiver;
35import android.content.ComponentName;
36import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070039import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070040import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.content.pm.ServiceInfo;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070042import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070043import android.os.Binder;
44import android.os.Handler;
45import android.os.Looper;
46import android.os.Message;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070047import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070048import android.os.RemoteException;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070049import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070050import android.os.SystemClock;
51import android.os.UserHandle;
Shreyas Basarge968ac752016-01-11 23:09:26 +000052import android.os.Process;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070053import android.util.ArraySet;
Christopher Tate7060b042014-06-09 19:50:00 -070054import android.util.Slog;
55import android.util.SparseArray;
56
Dianne Hackbornfdb19562014-07-11 16:03:36 -070057import com.android.internal.app.IBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080058import com.android.server.DeviceIdleController;
59import com.android.server.LocalServices;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080060import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070061import com.android.server.job.controllers.BatteryController;
62import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080063import com.android.server.job.controllers.ContentObserverController;
Christopher Tate7060b042014-06-09 19:50:00 -070064import com.android.server.job.controllers.IdleController;
65import com.android.server.job.controllers.JobStatus;
66import com.android.server.job.controllers.StateController;
67import com.android.server.job.controllers.TimeController;
68
Christopher Tate7060b042014-06-09 19:50:00 -070069/**
70 * Responsible for taking jobs representing work to be performed by a client app, and determining
71 * based on the criteria specified when that job should be run against the client application's
72 * endpoint.
73 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
74 * about constraints, or the state of active jobs. It receives callbacks from the various
75 * controllers and completed jobs and operates accordingly.
76 *
77 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
78 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
79 * @hide
80 */
81public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070082 implements StateChangedListener, JobCompletedListener {
Matthew Williamsaa984312015-10-15 16:08:05 -070083 public static final boolean DEBUG = false;
Christopher Tate7060b042014-06-09 19:50:00 -070084 /** The number of concurrent jobs we run at one time. */
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070085 private static final int MAX_JOB_CONTEXTS_COUNT
Shreyas Basarge8c834c02016-01-07 13:53:16 +000086 = ActivityManager.isLowRamDeviceStatic() ? 3 : 6;
Matthew Williamsbe0c4172014-08-06 18:14:16 -070087 static final String TAG = "JobSchedulerService";
Christopher Tate7060b042014-06-09 19:50:00 -070088 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070089 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -070090
91 static final int MSG_JOB_EXPIRED = 0;
92 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070093 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +000094 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -070095
96 // Policy constants
97 /**
98 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
99 * early.
100 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700101 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -0700102 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700103 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
104 * early.
105 */
106 static final int MIN_CHARGING_COUNT = 1;
107 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700108 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
109 * things early.
110 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700111 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700112 /**
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800113 * Minimum # of content trigger jobs that must be ready in order to force the JMS to schedule
114 * things early.
115 */
116 static final int MIN_CONTENT_COUNT = 1;
117 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700118 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
119 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700120 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700121 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700122 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700123
124 /**
125 * Track Services that have currently active or pending jobs. The index is provided by
126 * {@link JobStatus#getServiceToken()}
127 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700128 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700129 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700130 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700131 /**
132 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
133 * when ready to execute them.
134 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700135 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700136
Shreyas Basarge5db09082016-01-07 13:38:29 +0000137 final ArrayList<Integer> mStartedUsers = new ArrayList<>();
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700138
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700139 final JobHandler mHandler;
140 final JobSchedulerStub mJobSchedulerStub;
141
142 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700143 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800144 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700145
146 /**
147 * Set to true once we are allowed to run third party apps.
148 */
149 boolean mReadyToRock;
150
Christopher Tate7060b042014-06-09 19:50:00 -0700151 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700152 * True when in device idle mode, so we don't want to schedule any jobs.
153 */
154 boolean mDeviceIdleMode;
155
156 /**
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800157 * What we last reported to DeviceIdleController about wheter we are active.
158 */
159 boolean mReportedActive;
160
161 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700162 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
163 * still clean up. On reinstall the package will have a new uid.
164 */
165 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
166 @Override
167 public void onReceive(Context context, Intent intent) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000168 Slog.d(TAG, "Receieved: " + intent.getAction());
169 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700170 // If this is an outright uninstall rather than the first half of an
171 // app update sequence, cancel the jobs associated with the app.
172 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
173 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
174 if (DEBUG) {
175 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
176 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700177 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700178 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000179 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700180 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
181 if (DEBUG) {
182 Slog.d(TAG, "Removing jobs for user: " + userId);
183 }
184 cancelJobsForUser(userId);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000185 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())
186 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700187 updateIdleMode(mPowerManager != null
188 ? (mPowerManager.isDeviceIdleMode()
Shreyas Basarge5db09082016-01-07 13:38:29 +0000189 || mPowerManager.isLightDeviceIdleMode())
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700190 : false);
Christopher Tate7060b042014-06-09 19:50:00 -0700191 }
192 }
193 };
194
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700195 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
196 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
197 }
198
199 @Override public void onUidGone(int uid) throws RemoteException {
200 }
201
202 @Override public void onUidActive(int uid) throws RemoteException {
203 }
204
205 @Override public void onUidIdle(int uid) throws RemoteException {
206 cancelJobsForUid(uid, false);
207 }
208 };
209
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700210 @Override
211 public void onStartUser(int userHandle) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000212 mStartedUsers.add(userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700213 // Let's kick any outstanding jobs for this user.
214 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
215 }
216
217 @Override
218 public void onStopUser(int userHandle) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000219 mStartedUsers.remove(Integer.valueOf(userHandle));
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700220 }
221
Christopher Tate7060b042014-06-09 19:50:00 -0700222 /**
223 * Entry point from client to schedule the provided job.
224 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
225 * @param job JobInfo object containing execution parameters
226 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700227 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
228 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700229 public int schedule(JobInfo job, int uId) {
Shreyas Basarge968ac752016-01-11 23:09:26 +0000230 return scheduleAsPackage(job, uId, null, -1);
231 }
232
233 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId) {
Matthew Williams900c67f2014-07-09 12:46:53 -0700234 JobStatus jobStatus = new JobStatus(job, uId);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000235 if (packageName != null) {
236 jobStatus.setSource(packageName, userId);
237 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700238 try {
239 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
240 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
241 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
242 + " -- package not allowed to start");
243 return JobScheduler.RESULT_FAILURE;
244 }
245 } catch (RemoteException e) {
246 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800247 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
248 JobStatus toCancel;
249 synchronized (mJobs) {
250 toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
251 }
252 startTrackingJob(jobStatus, toCancel);
253 if (toCancel != null) {
254 cancelJobImpl(toCancel);
255 }
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700256 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700257 return JobScheduler.RESULT_SUCCESS;
258 }
259
260 public List<JobInfo> getPendingJobs(int uid) {
261 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
262 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700263 ArraySet<JobStatus> jobs = mJobs.getJobs();
264 for (int i=0; i<jobs.size(); i++) {
265 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700266 if (job.getUid() == uid) {
267 outList.add(job.getJob());
268 }
269 }
270 }
271 return outList;
272 }
273
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700274 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700275 List<JobStatus> jobsForUser;
Christopher Tate7060b042014-06-09 19:50:00 -0700276 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700277 jobsForUser = mJobs.getJobsByUser(userHandle);
278 }
279 for (int i=0; i<jobsForUser.size(); i++) {
280 JobStatus toRemove = jobsForUser.get(i);
281 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700282 }
283 }
284
285 /**
286 * Entry point from client to cancel all jobs originating from their uid.
287 * This will remove the job from the master list, and cancel the job if it was staged for
288 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700289 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700290 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
291 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700292 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700293 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700294 List<JobStatus> jobsForUid;
Christopher Tate7060b042014-06-09 19:50:00 -0700295 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700296 jobsForUid = mJobs.getJobsByUid(uid);
297 }
298 for (int i=0; i<jobsForUid.size(); i++) {
299 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700300 if (!forceAll) {
301 String packageName = toRemove.getServiceComponent().getPackageName();
302 try {
303 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
304 != ActivityManager.APP_START_MODE_DISABLED) {
305 continue;
306 }
307 } catch (RemoteException e) {
308 }
309 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700310 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700311 }
312 }
313
314 /**
315 * Entry point from client to cancel the job corresponding to the jobId provided.
316 * This will remove the job from the master list, and cancel the job if it was staged for
317 * execution or being executed.
318 * @param uid Uid of the calling client.
319 * @param jobId Id of the job, provided at schedule-time.
320 */
321 public void cancelJob(int uid, int jobId) {
322 JobStatus toCancel;
323 synchronized (mJobs) {
324 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700325 }
326 if (toCancel != null) {
327 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700328 }
329 }
330
Matthew Williams48a30db2014-09-23 13:39:36 -0700331 private void cancelJobImpl(JobStatus cancelled) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800332 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Shreyas Basarge73f10252016-02-11 17:06:13 +0000333 stopTrackingJob(cancelled, true /* writeBack */);
Matthew Williams48a30db2014-09-23 13:39:36 -0700334 synchronized (mJobs) {
335 // Remove from pending queue.
336 mPendingJobs.remove(cancelled);
337 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000338 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800339 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700340 }
Christopher Tate7060b042014-06-09 19:50:00 -0700341 }
342
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700343 void updateIdleMode(boolean enabled) {
344 boolean changed = false;
345 boolean rocking;
346 synchronized (mJobs) {
347 if (mDeviceIdleMode != enabled) {
348 changed = true;
349 }
350 rocking = mReadyToRock;
351 }
352 if (changed) {
353 if (rocking) {
354 for (int i=0; i<mControllers.size(); i++) {
355 mControllers.get(i).deviceIdleModeChanged(enabled);
356 }
357 }
358 synchronized (mJobs) {
359 mDeviceIdleMode = enabled;
360 if (enabled) {
361 // When becoming idle, make sure no jobs are actively running.
362 for (int i=0; i<mActiveServices.size(); i++) {
363 JobServiceContext jsc = mActiveServices.get(i);
364 final JobStatus executing = jsc.getRunningJob();
365 if (executing != null) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000366 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700367 }
368 }
369 } else {
370 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800371 if (rocking) {
372 if (mLocalDeviceIdleController != null) {
373 if (!mReportedActive) {
374 mReportedActive = true;
375 mLocalDeviceIdleController.setJobsActive(true);
376 }
377 }
378 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700379 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
380 }
381 }
382 }
383 }
384
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800385 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000386 // active is true if pending queue contains jobs OR some job is running.
387 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800388 if (mPendingJobs.size() <= 0) {
389 for (int i=0; i<mActiveServices.size(); i++) {
390 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000391 if (jsc.getRunningJob() != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800392 active = true;
393 break;
394 }
395 }
396 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000397
398 if (mReportedActive != active) {
399 mReportedActive = active;
400 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800401 mLocalDeviceIdleController.setJobsActive(active);
402 }
403 }
404 }
405
Christopher Tate7060b042014-06-09 19:50:00 -0700406 /**
407 * Initializes the system service.
408 * <p>
409 * Subclasses must define a single argument constructor that accepts the context
410 * and passes it to super.
411 * </p>
412 *
413 * @param context The system server context.
414 */
415 public JobSchedulerService(Context context) {
416 super(context);
417 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700418 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700419 mControllers.add(ConnectivityController.get(this));
420 mControllers.add(TimeController.get(this));
421 mControllers.add(IdleController.get(this));
422 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800423 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800424 mControllers.add(ContentObserverController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700425
426 mHandler = new JobHandler(context.getMainLooper());
427 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700428 mJobs = JobStore.initAndGet(this);
429 }
430
431 @Override
432 public void onStart() {
433 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
434 }
435
436 @Override
437 public void onBootPhase(int phase) {
438 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000439 // Register br for package removals and user removals.
Christopher Tate7060b042014-06-09 19:50:00 -0700440 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
441 filter.addDataScheme("package");
442 getContext().registerReceiverAsUser(
443 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
444 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700445 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700446 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700447 getContext().registerReceiverAsUser(
448 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000449 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700450 try {
451 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
452 ActivityManager.UID_OBSERVER_IDLE);
453 } catch (RemoteException e) {
454 // ignored; both services live in system_server
455 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700456 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
457 synchronized (mJobs) {
458 // Let's go!
459 mReadyToRock = true;
460 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
461 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800462 mLocalDeviceIdleController
463 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700464 // Create the "runners".
465 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
466 mActiveServices.add(
467 new JobServiceContext(this, mBatteryStats,
468 getContext().getMainLooper()));
469 }
470 // Attach jobs to their controllers.
471 ArraySet<JobStatus> jobs = mJobs.getJobs();
472 for (int i=0; i<jobs.size(); i++) {
473 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700474 for (int controller=0; controller<mControllers.size(); controller++) {
Dianne Hackborn2bf51f42015-03-24 14:17:12 -0700475 mControllers.get(controller).deviceIdleModeChanged(mDeviceIdleMode);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800476 mControllers.get(controller).maybeStartTrackingJob(job, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700477 }
478 }
479 // GO GO GO!
480 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
481 }
Christopher Tate7060b042014-06-09 19:50:00 -0700482 }
483 }
484
485 /**
486 * Called when we have a job status object that we need to insert in our
487 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
488 * about.
489 */
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800490 private void startTrackingJob(JobStatus jobStatus, JobStatus lastJob) {
Christopher Tate7060b042014-06-09 19:50:00 -0700491 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700492 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700493 synchronized (mJobs) {
494 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700495 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700496 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700497 if (rocking) {
498 for (int i=0; i<mControllers.size(); i++) {
499 StateController controller = mControllers.get(i);
500 if (update) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800501 controller.maybeStopTrackingJob(jobStatus, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700502 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800503 controller.maybeStartTrackingJob(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -0700504 }
Christopher Tate7060b042014-06-09 19:50:00 -0700505 }
506 }
507
508 /**
509 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
510 * object removed.
511 */
Shreyas Basarge73f10252016-02-11 17:06:13 +0000512 private boolean stopTrackingJob(JobStatus jobStatus, boolean writeBack) {
Christopher Tate7060b042014-06-09 19:50:00 -0700513 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700514 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700515 synchronized (mJobs) {
516 // Remove from store as well as controllers.
Shreyas Basarge73f10252016-02-11 17:06:13 +0000517 removed = mJobs.remove(jobStatus, writeBack);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700518 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700519 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700520 if (removed && rocking) {
521 for (int i=0; i<mControllers.size(); i++) {
522 StateController controller = mControllers.get(i);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800523 controller.maybeStopTrackingJob(jobStatus, false);
Christopher Tate7060b042014-06-09 19:50:00 -0700524 }
525 }
526 return removed;
527 }
528
Shreyas Basarge5db09082016-01-07 13:38:29 +0000529 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700530 for (int i=0; i<mActiveServices.size(); i++) {
531 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700532 final JobStatus executing = jsc.getRunningJob();
533 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000534 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700535 return true;
536 }
537 }
538 return false;
539 }
540
541 /**
542 * @param job JobStatus we are querying against.
543 * @return Whether or not the job represented by the status object is currently being run or
544 * is pending.
545 */
546 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700547 for (int i=0; i<mActiveServices.size(); i++) {
548 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700549 final JobStatus running = serviceContext.getRunningJob();
550 if (running != null && running.matches(job.getUid(), job.getJobId())) {
551 return true;
552 }
553 }
554 return false;
555 }
556
557 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700558 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
559 * specify an override deadline on a failed job (the failed job will run even though it's not
560 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
561 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
562 *
Christopher Tate7060b042014-06-09 19:50:00 -0700563 * @param failureToReschedule Provided job status that we will reschedule.
564 * @return A newly instantiated JobStatus with the same constraints as the last job except
565 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700566 *
567 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700568 */
569 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
570 final long elapsedNowMillis = SystemClock.elapsedRealtime();
571 final JobInfo job = failureToReschedule.getJob();
572
573 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700574 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
575 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700576
577 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700578 case JobInfo.BACKOFF_POLICY_LINEAR:
579 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700580 break;
581 default:
582 if (DEBUG) {
583 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
584 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700585 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
586 delayMillis =
587 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700588 break;
589 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700590 delayMillis =
591 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800592 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -0700593 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800594 for (int ic=0; ic<mControllers.size(); ic++) {
595 StateController controller = mControllers.get(ic);
596 controller.rescheduleForFailure(newJob, failureToReschedule);
597 }
598 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -0700599 }
600
601 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700602 * Called after a periodic has executed so we can reschedule it. We take the last execution
603 * time of the job to be the time of completion (i.e. the time at which this function is
604 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700605 * This could be inaccurate b/c the job can run for as long as
606 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
607 * to underscheduling at least, rather than if we had taken the last execution time to be the
608 * start of the execution.
609 * @return A new job representing the execution criteria for this instantiation of the
610 * recurring job.
611 */
612 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
613 final long elapsedNow = SystemClock.elapsedRealtime();
614 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700615 long runEarly = 0L;
616
617 // If this periodic was rescheduled it won't have a deadline.
618 if (periodicToReschedule.hasDeadlineConstraint()) {
619 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
620 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000621 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700622 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000623 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
624 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -0700625
626 if (DEBUG) {
627 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
628 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
629 }
630 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
631 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
632 }
633
634 // JobCompletedListener implementations.
635
636 /**
637 * A job just finished executing. We fetch the
638 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
639 * whether we want to reschedule we readd it to the controllers.
640 * @param jobStatus Completed job.
641 * @param needsReschedule Whether the implementing class should reschedule this job.
642 */
643 @Override
644 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
645 if (DEBUG) {
646 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
647 }
Shreyas Basarge73f10252016-02-11 17:06:13 +0000648 // Do not write back immediately if this is a periodic job. The job may get lost if system
649 // shuts down before it is added back.
650 if (!stopTrackingJob(jobStatus, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700651 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700652 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700653 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800654 // We still want to check for jobs to execute, because this job may have
655 // scheduled a new job under the same job id, and now we can run it.
656 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700657 return;
658 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800659 // Note: there is a small window of time in here where, when rescheduling a job,
660 // we will stop monitoring its content providers. This should be fixed by stopping
661 // the old job after scheduling the new one, but since we have no lock held here
662 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -0700663 if (needsReschedule) {
664 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800665 startTrackingJob(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700666 } else if (jobStatus.getJob().isPeriodic()) {
667 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800668 startTrackingJob(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700669 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000670 reportActive();
671 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700672 }
673
674 // StateChangedListener implementations.
675
676 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700677 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
678 * some controller's state has changed, so as to run through the list of jobs and start/stop
679 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700680 */
681 @Override
682 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700683 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700684 }
685
686 @Override
687 public void onRunJobNow(JobStatus jobStatus) {
688 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
689 }
690
Christopher Tate7060b042014-06-09 19:50:00 -0700691 private class JobHandler extends Handler {
692
693 public JobHandler(Looper looper) {
694 super(looper);
695 }
696
697 @Override
698 public void handleMessage(Message message) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700699 synchronized (mJobs) {
700 if (!mReadyToRock) {
701 return;
702 }
703 }
Christopher Tate7060b042014-06-09 19:50:00 -0700704 switch (message.what) {
705 case MSG_JOB_EXPIRED:
706 synchronized (mJobs) {
707 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700708 // runNow can be null, which is a controller's way of indicating that its
709 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700710 if (runNow != null && !mPendingJobs.contains(runNow)
711 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700712 mPendingJobs.add(runNow);
713 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700714 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700715 }
Christopher Tate7060b042014-06-09 19:50:00 -0700716 break;
717 case MSG_CHECK_JOB:
Matthew Williams48a30db2014-09-23 13:39:36 -0700718 synchronized (mJobs) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000719 if (mReportedActive) {
720 // if jobs are currently being run, queue all ready jobs for execution.
721 queueReadyJobsForExecutionLockedH();
722 } else {
723 // Check the list of jobs and run some of them if we feel inclined.
724 maybeQueueReadyJobsForExecutionLockedH();
725 }
726 }
727 break;
728 case MSG_CHECK_JOB_GREEDY:
729 synchronized (mJobs) {
730 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700731 }
Christopher Tate7060b042014-06-09 19:50:00 -0700732 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700733 case MSG_STOP_JOB:
734 cancelJobImpl((JobStatus)message.obj);
735 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700736 }
737 maybeRunPendingJobsH();
738 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
739 removeMessages(MSG_CHECK_JOB);
740 }
741
742 /**
743 * Run through list of jobs and execute all possible - at least one is expired so we do
744 * as many as we can.
745 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700746 private void queueReadyJobsForExecutionLockedH() {
747 ArraySet<JobStatus> jobs = mJobs.getJobs();
Shreyas Basarge5db09082016-01-07 13:38:29 +0000748 mPendingJobs.clear();
Matthew Williams48a30db2014-09-23 13:39:36 -0700749 if (DEBUG) {
750 Slog.d(TAG, "queuing all ready jobs for execution:");
751 }
752 for (int i=0; i<jobs.size(); i++) {
753 JobStatus job = jobs.valueAt(i);
754 if (isReadyToBeExecutedLocked(job)) {
755 if (DEBUG) {
756 Slog.d(TAG, " queued " + job.toShortString());
Christopher Tate7060b042014-06-09 19:50:00 -0700757 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700758 mPendingJobs.add(job);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000759 } else if (areJobConstraintsNotSatisfied(job)) {
760 stopJobOnServiceContextLocked(job,
761 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700762 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700763 }
764 if (DEBUG) {
765 final int queuedJobs = mPendingJobs.size();
766 if (queuedJobs == 0) {
767 Slog.d(TAG, "No jobs pending.");
768 } else {
769 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700770 }
Christopher Tate7060b042014-06-09 19:50:00 -0700771 }
772 }
773
774 /**
775 * The state of at least one job has changed. Here is where we could enforce various
776 * policies on when we want to execute jobs.
777 * Right now the policy is such:
778 * If >1 of the ready jobs is idle mode we send all of them off
779 * if more than 2 network connectivity jobs are ready we send them all off.
780 * If more than 4 jobs total are ready we send them all off.
781 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
782 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700783 private void maybeQueueReadyJobsForExecutionLockedH() {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000784 mPendingJobs.clear();
Matthew Williams48a30db2014-09-23 13:39:36 -0700785 int chargingCount = 0;
Shreyas Basarge5db09082016-01-07 13:38:29 +0000786 int idleCount = 0;
Matthew Williams48a30db2014-09-23 13:39:36 -0700787 int backoffCount = 0;
788 int connectivityCount = 0;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800789 int contentCount = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700790 List<JobStatus> runnableJobs = null;
Matthew Williams48a30db2014-09-23 13:39:36 -0700791 ArraySet<JobStatus> jobs = mJobs.getJobs();
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800792 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
Matthew Williams48a30db2014-09-23 13:39:36 -0700793 for (int i=0; i<jobs.size(); i++) {
794 JobStatus job = jobs.valueAt(i);
795 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700796 try {
797 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
798 job.getJob().getService().getPackageName())
799 == ActivityManager.APP_START_MODE_DISABLED) {
800 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
801 + job.getJob().toString() + " -- package not allowed to start");
802 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
803 continue;
804 }
805 } catch (RemoteException e) {
806 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700807 if (job.getNumFailures() > 0) {
808 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700809 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700810 if (job.hasIdleConstraint()) {
811 idleCount++;
812 }
813 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
814 connectivityCount++;
815 }
816 if (job.hasChargingConstraint()) {
817 chargingCount++;
818 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800819 if (job.hasContentTriggerConstraint()) {
820 contentCount++;
821 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700822 if (runnableJobs == null) {
823 runnableJobs = new ArrayList<>();
824 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700825 runnableJobs.add(job);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000826 } else if (areJobConstraintsNotSatisfied(job)) {
827 stopJobOnServiceContextLocked(job,
828 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700829 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700830 }
831 if (backoffCount > 0 ||
832 idleCount >= MIN_IDLE_COUNT ||
833 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
834 chargingCount >= MIN_CHARGING_COUNT ||
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800835 contentCount >= MIN_CONTENT_COUNT ||
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700836 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700837 if (DEBUG) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700838 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
Christopher Tate7060b042014-06-09 19:50:00 -0700839 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700840 for (int i=0; i<runnableJobs.size(); i++) {
841 mPendingJobs.add(runnableJobs.get(i));
842 }
843 } else {
844 if (DEBUG) {
845 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
846 }
847 }
Christopher Tate7060b042014-06-09 19:50:00 -0700848 }
849
850 /**
851 * Criteria for moving a job into the pending queue:
852 * - It's ready.
853 * - It's not pending.
854 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700855 * - The user that requested the job is running.
Christopher Tate7060b042014-06-09 19:50:00 -0700856 */
857 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700858 final boolean jobReady = job.isReady();
859 final boolean jobPending = mPendingJobs.contains(job);
860 final boolean jobActive = isCurrentlyActiveLocked(job);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000861 final boolean userRunning = mStartedUsers.contains(job.getUserId());
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700862 if (DEBUG) {
863 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
864 + " ready=" + jobReady + " pending=" + jobPending
Shreyas Basarge5db09082016-01-07 13:38:29 +0000865 + " active=" + jobActive + " userRunning=" + userRunning);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700866 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000867 return userRunning && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700868 }
869
870 /**
871 * Criteria for cancelling an active job:
872 * - It's not ready
873 * - It's running on a JSC.
874 */
Shreyas Basarge5db09082016-01-07 13:38:29 +0000875 private boolean areJobConstraintsNotSatisfied(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -0700876 return !job.isReady() && isCurrentlyActiveLocked(job);
877 }
878
879 /**
880 * Reconcile jobs in the pending queue against available execution contexts.
881 * A controller can force a job into the pending queue even if it's already running, but
882 * here is where we decide whether to actually execute it.
883 */
884 private void maybeRunPendingJobsH() {
885 synchronized (mJobs) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700886 if (mDeviceIdleMode) {
887 // If device is idle, we will not schedule jobs to run.
888 return;
889 }
Matthew Williams75fc5252014-09-02 16:17:53 -0700890 if (DEBUG) {
891 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
892 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000893 assignJobsToContextsH();
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800894 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700895 }
896 }
897 }
898
899 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +0000900 * Takes jobs from pending queue and runs them on available contexts.
901 * If no contexts are available, preempts lower priority jobs to
902 * run higher priority ones.
903 * Lock on mJobs before calling this function.
904 */
905 private void assignJobsToContextsH() {
906 if (DEBUG) {
907 Slog.d(TAG, printPendingQueue());
908 }
909
910 // This array essentially stores the state of mActiveServices array.
911 // ith index stores the job present on the ith JobServiceContext.
912 // We manipulate this array until we arrive at what jobs should be running on
913 // what JobServiceContext.
914 JobStatus[] contextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
915 // Indicates whether we need to act on this jobContext id
916 boolean[] act = new boolean[MAX_JOB_CONTEXTS_COUNT];
917 int[] preferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
918 for (int i=0; i<mActiveServices.size(); i++) {
919 contextIdToJobMap[i] = mActiveServices.get(i).getRunningJob();
920 preferredUidForContext[i] = mActiveServices.get(i).getPreferredUid();
921 }
922 if (DEBUG) {
923 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
924 }
925 Iterator<JobStatus> it = mPendingJobs.iterator();
926 while (it.hasNext()) {
927 JobStatus nextPending = it.next();
928
929 // If job is already running, go to next job.
930 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
931 if (jobRunningContext != -1) {
932 continue;
933 }
934
935 // Find a context for nextPending. The context should be available OR
936 // it should have lowest priority among all running jobs
937 // (sharing the same Uid as nextPending)
938 int minPriority = Integer.MAX_VALUE;
939 int minPriorityContextId = -1;
940 for (int i=0; i<mActiveServices.size(); i++) {
941 JobStatus job = contextIdToJobMap[i];
942 int preferredUid = preferredUidForContext[i];
943 if (job == null && (preferredUid == nextPending.getUid() ||
944 preferredUid == JobServiceContext.NO_PREFERRED_UID) ) {
945 minPriorityContextId = i;
946 break;
947 }
Shreyas Basarge347c2782016-01-15 18:24:36 +0000948 if (job == null) {
949 // No job on this context, but nextPending can't run here because
950 // the context has a preferred Uid.
951 continue;
952 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000953 if (job.getUid() != nextPending.getUid()) {
954 continue;
955 }
956 if (job.getPriority() >= nextPending.getPriority()) {
957 continue;
958 }
959 if (minPriority > nextPending.getPriority()) {
960 minPriority = nextPending.getPriority();
961 minPriorityContextId = i;
962 }
963 }
964 if (minPriorityContextId != -1) {
965 contextIdToJobMap[minPriorityContextId] = nextPending;
966 act[minPriorityContextId] = true;
967 }
968 }
969 if (DEBUG) {
970 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
971 }
972 for (int i=0; i<mActiveServices.size(); i++) {
973 boolean preservePreferredUid = false;
974 if (act[i]) {
975 JobStatus js = mActiveServices.get(i).getRunningJob();
976 if (js != null) {
977 if (DEBUG) {
978 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
979 }
980 // preferredUid will be set to uid of currently running job.
981 mActiveServices.get(i).preemptExecutingJob();
982 preservePreferredUid = true;
983 } else {
984 if (DEBUG) {
985 Slog.d(TAG, "About to run job on context "
986 + String.valueOf(i) + ", job: " + contextIdToJobMap[i]);
987 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800988 for (int ic=0; ic<mControllers.size(); ic++) {
989 StateController controller = mControllers.get(ic);
990 controller.prepareForExecution(contextIdToJobMap[i]);
991 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000992 if (!mActiveServices.get(i).executeRunnableJob(contextIdToJobMap[i])) {
993 Slog.d(TAG, "Error executing " + contextIdToJobMap[i]);
994 }
995 mPendingJobs.remove(contextIdToJobMap[i]);
996 }
997 }
998 if (!preservePreferredUid) {
999 mActiveServices.get(i).clearPreferredUid();
1000 }
1001 }
1002 }
1003
1004 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1005 for (int i=0; i<map.length; i++) {
1006 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1007 return i;
1008 }
1009 }
1010 return -1;
1011 }
1012
1013 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001014 * Binder stub trampoline implementation
1015 */
1016 final class JobSchedulerStub extends IJobScheduler.Stub {
1017 /** Cache determination of whether a given app can persist jobs
1018 * key is uid of the calling app; value is undetermined/true/false
1019 */
1020 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1021
1022 // Enforce that only the app itself (or shared uid participant) can schedule a
1023 // job that runs one of the app's services, as well as verifying that the
1024 // named service properly requires the BIND_JOB_SERVICE permission
1025 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001026 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001027 final ComponentName service = job.getService();
1028 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001029 ServiceInfo si = pm.getServiceInfo(service,
1030 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001031 if (si == null) {
1032 throw new IllegalArgumentException("No such service " + service);
1033 }
Christopher Tate7060b042014-06-09 19:50:00 -07001034 if (si.applicationInfo.uid != uid) {
1035 throw new IllegalArgumentException("uid " + uid +
1036 " cannot schedule job in " + service.getPackageName());
1037 }
1038 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1039 throw new IllegalArgumentException("Scheduled service " + service
1040 + " does not require android.permission.BIND_JOB_SERVICE permission");
1041 }
Christopher Tate5568f542014-06-18 13:53:31 -07001042 } catch (RemoteException e) {
1043 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001044 }
1045 }
1046
1047 private boolean canPersistJobs(int pid, int uid) {
1048 // If we get this far we're good to go; all we need to do now is check
1049 // whether the app is allowed to persist its scheduled work.
1050 final boolean canPersist;
1051 synchronized (mPersistCache) {
1052 Boolean cached = mPersistCache.get(uid);
1053 if (cached != null) {
1054 canPersist = cached.booleanValue();
1055 } else {
1056 // Persisting jobs is tantamount to running at boot, so we permit
1057 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1058 // permission
1059 int result = getContext().checkPermission(
1060 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1061 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1062 mPersistCache.put(uid, canPersist);
1063 }
1064 }
1065 return canPersist;
1066 }
1067
1068 // IJobScheduler implementation
1069 @Override
1070 public int schedule(JobInfo job) throws RemoteException {
1071 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001072 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001073 }
1074 final int pid = Binder.getCallingPid();
1075 final int uid = Binder.getCallingUid();
1076
1077 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001078 if (job.isPersisted()) {
1079 if (!canPersistJobs(pid, uid)) {
1080 throw new IllegalArgumentException("Error: requested job be persisted without"
1081 + " holding RECEIVE_BOOT_COMPLETED permission.");
1082 }
1083 }
Christopher Tate7060b042014-06-09 19:50:00 -07001084
1085 long ident = Binder.clearCallingIdentity();
1086 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001087 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001088 } finally {
1089 Binder.restoreCallingIdentity(ident);
1090 }
1091 }
1092
1093 @Override
Shreyas Basarge968ac752016-01-11 23:09:26 +00001094 public int scheduleAsPackage(JobInfo job, String packageName, int userId)
1095 throws RemoteException {
1096 if (DEBUG) {
1097 Slog.d(TAG, "Scheduling job: " + job.toString() + " on behalf of " + packageName);
1098 }
1099 final int uid = Binder.getCallingUid();
1100 if (uid != Process.SYSTEM_UID) {
1101 throw new IllegalArgumentException("Only system process is allowed"
1102 + "to set packageName");
1103 }
1104 long ident = Binder.clearCallingIdentity();
1105 try {
1106 return JobSchedulerService.this.scheduleAsPackage(job, uid, packageName, userId);
1107 } finally {
1108 Binder.restoreCallingIdentity(ident);
1109 }
1110 }
1111
1112 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001113 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1114 final int uid = Binder.getCallingUid();
1115
1116 long ident = Binder.clearCallingIdentity();
1117 try {
1118 return JobSchedulerService.this.getPendingJobs(uid);
1119 } finally {
1120 Binder.restoreCallingIdentity(ident);
1121 }
1122 }
1123
1124 @Override
1125 public void cancelAll() throws RemoteException {
1126 final int uid = Binder.getCallingUid();
1127
1128 long ident = Binder.clearCallingIdentity();
1129 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001130 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001131 } finally {
1132 Binder.restoreCallingIdentity(ident);
1133 }
1134 }
1135
1136 @Override
1137 public void cancel(int jobId) throws RemoteException {
1138 final int uid = Binder.getCallingUid();
1139
1140 long ident = Binder.clearCallingIdentity();
1141 try {
1142 JobSchedulerService.this.cancelJob(uid, jobId);
1143 } finally {
1144 Binder.restoreCallingIdentity(ident);
1145 }
1146 }
1147
1148 /**
1149 * "dumpsys" infrastructure
1150 */
1151 @Override
1152 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1153 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1154
1155 long identityToken = Binder.clearCallingIdentity();
1156 try {
1157 JobSchedulerService.this.dumpInternal(pw);
1158 } finally {
1159 Binder.restoreCallingIdentity(identityToken);
1160 }
1161 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001162 };
1163
1164 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1165 StringBuilder s = new StringBuilder(initial + ": ");
1166 for (int i=0; i<map.length; i++) {
1167 s.append("(")
1168 .append(map[i] == null? -1: map[i].getJobId())
1169 .append(map[i] == null? -1: map[i].getUid())
1170 .append(")" );
1171 }
1172 return s.toString();
1173 }
1174
1175 private String printPendingQueue() {
1176 StringBuilder s = new StringBuilder("Pending queue: ");
1177 Iterator<JobStatus> it = mPendingJobs.iterator();
1178 while (it.hasNext()) {
1179 JobStatus js = it.next();
1180 s.append("(")
1181 .append(js.getJob().getId())
1182 .append(", ")
1183 .append(js.getUid())
1184 .append(") ");
1185 }
1186 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001187 }
Christopher Tate7060b042014-06-09 19:50:00 -07001188
1189 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001190 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -07001191 synchronized (mJobs) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001192 pw.print("Started users: ");
1193 for (int i=0; i<mStartedUsers.size(); i++) {
1194 pw.print("u" + mStartedUsers.get(i) + " ");
1195 }
1196 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07001197 pw.println("Registered jobs:");
1198 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001199 ArraySet<JobStatus> jobs = mJobs.getJobs();
1200 for (int i=0; i<jobs.size(); i++) {
1201 JobStatus job = jobs.valueAt(i);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001202 pw.print(" Job #"); pw.print(i); pw.print(": ");
1203 pw.println(job.toShortString());
1204 job.dump(pw, " ");
1205 pw.print(" Ready: ");
1206 pw.print(mHandler.isReadyToBeExecutedLocked(job));
1207 pw.print(" (job=");
1208 pw.print(job.isReady());
1209 pw.print(" pending=");
1210 pw.print(mPendingJobs.contains(job));
1211 pw.print(" active=");
1212 pw.print(isCurrentlyActiveLocked(job));
1213 pw.print(" user=");
1214 pw.print(mStartedUsers.contains(job.getUserId()));
1215 pw.println(")");
Christopher Tate7060b042014-06-09 19:50:00 -07001216 }
1217 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001218 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001219 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001220 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001221 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001222 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001223 }
1224 pw.println();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001225 pw.println(printPendingQueue());
Christopher Tate7060b042014-06-09 19:50:00 -07001226 pw.println();
1227 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001228 for (int i=0; i<mActiveServices.size(); i++) {
1229 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001230 if (jsc.getRunningJob() == null) {
Christopher Tate7060b042014-06-09 19:50:00 -07001231 continue;
1232 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001233 final long timeout = jsc.getTimeoutElapsed();
1234 pw.print("Running for: ");
1235 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1236 pw.print("s timeout=");
1237 pw.print(timeout);
1238 pw.print(" fromnow=");
1239 pw.println(timeout-now);
1240 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -07001241 }
1242 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001243 pw.println();
1244 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001245 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001246 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001247 }
1248 pw.println();
1249 }
1250}