blob: 24519db850a388c320b9e0679370894cc22841de [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;
63import com.android.server.job.controllers.IdleController;
64import com.android.server.job.controllers.JobStatus;
65import com.android.server.job.controllers.StateController;
66import com.android.server.job.controllers.TimeController;
67
Christopher Tate7060b042014-06-09 19:50:00 -070068/**
69 * Responsible for taking jobs representing work to be performed by a client app, and determining
70 * based on the criteria specified when that job should be run against the client application's
71 * endpoint.
72 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
73 * about constraints, or the state of active jobs. It receives callbacks from the various
74 * controllers and completed jobs and operates accordingly.
75 *
76 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
77 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
78 * @hide
79 */
80public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070081 implements StateChangedListener, JobCompletedListener {
Matthew Williamsaa984312015-10-15 16:08:05 -070082 public static final boolean DEBUG = false;
Christopher Tate7060b042014-06-09 19:50:00 -070083 /** The number of concurrent jobs we run at one time. */
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070084 private static final int MAX_JOB_CONTEXTS_COUNT
85 = ActivityManager.isLowRamDeviceStatic() ? 1 : 3;
Matthew Williamsbe0c4172014-08-06 18:14:16 -070086 static final String TAG = "JobSchedulerService";
Christopher Tate7060b042014-06-09 19:50:00 -070087 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070088 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -070089
90 static final int MSG_JOB_EXPIRED = 0;
91 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070092 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +000093 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -070094
95 // Policy constants
96 /**
97 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
98 * early.
99 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700100 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -0700101 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700102 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
103 * early.
104 */
105 static final int MIN_CHARGING_COUNT = 1;
106 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700107 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
108 * things early.
109 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700110 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700111 /**
112 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
113 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700114 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700115 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700116 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700117
118 /**
119 * Track Services that have currently active or pending jobs. The index is provided by
120 * {@link JobStatus#getServiceToken()}
121 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700122 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700123 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700124 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700125 /**
126 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
127 * when ready to execute them.
128 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700129 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700130
Shreyas Basarge5db09082016-01-07 13:38:29 +0000131 final ArrayList<Integer> mStartedUsers = new ArrayList<>();
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700132
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700133 final JobHandler mHandler;
134 final JobSchedulerStub mJobSchedulerStub;
135
136 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700137 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800138 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700139
140 /**
141 * Set to true once we are allowed to run third party apps.
142 */
143 boolean mReadyToRock;
144
Christopher Tate7060b042014-06-09 19:50:00 -0700145 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700146 * True when in device idle mode, so we don't want to schedule any jobs.
147 */
148 boolean mDeviceIdleMode;
149
150 /**
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800151 * What we last reported to DeviceIdleController about wheter we are active.
152 */
153 boolean mReportedActive;
154
155 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700156 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
157 * still clean up. On reinstall the package will have a new uid.
158 */
159 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
160 @Override
161 public void onReceive(Context context, Intent intent) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000162 Slog.d(TAG, "Receieved: " + intent.getAction());
163 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700164 // If this is an outright uninstall rather than the first half of an
165 // app update sequence, cancel the jobs associated with the app.
166 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
167 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
168 if (DEBUG) {
169 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
170 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700171 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700172 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000173 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
Christopher Tate7060b042014-06-09 19:50:00 -0700174 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
175 if (DEBUG) {
176 Slog.d(TAG, "Removing jobs for user: " + userId);
177 }
178 cancelJobsForUser(userId);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000179 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())
180 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700181 updateIdleMode(mPowerManager != null
182 ? (mPowerManager.isDeviceIdleMode()
Shreyas Basarge5db09082016-01-07 13:38:29 +0000183 || mPowerManager.isLightDeviceIdleMode())
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700184 : false);
Christopher Tate7060b042014-06-09 19:50:00 -0700185 }
186 }
187 };
188
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700189 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
190 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
191 }
192
193 @Override public void onUidGone(int uid) throws RemoteException {
194 }
195
196 @Override public void onUidActive(int uid) throws RemoteException {
197 }
198
199 @Override public void onUidIdle(int uid) throws RemoteException {
200 cancelJobsForUid(uid, false);
201 }
202 };
203
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700204 @Override
205 public void onStartUser(int userHandle) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000206 mStartedUsers.add(userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700207 // Let's kick any outstanding jobs for this user.
208 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
209 }
210
211 @Override
212 public void onStopUser(int userHandle) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000213 mStartedUsers.remove(Integer.valueOf(userHandle));
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700214 }
215
Christopher Tate7060b042014-06-09 19:50:00 -0700216 /**
217 * Entry point from client to schedule the provided job.
218 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
219 * @param job JobInfo object containing execution parameters
220 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700221 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
222 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700223 public int schedule(JobInfo job, int uId) {
Shreyas Basarge968ac752016-01-11 23:09:26 +0000224 return scheduleAsPackage(job, uId, null, -1);
225 }
226
227 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId) {
Matthew Williams900c67f2014-07-09 12:46:53 -0700228 JobStatus jobStatus = new JobStatus(job, uId);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000229 if (packageName != null) {
230 jobStatus.setSource(packageName, userId);
231 }
Christopher Tate7060b042014-06-09 19:50:00 -0700232 cancelJob(uId, job.getId());
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700233 try {
234 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
235 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
236 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
237 + " -- package not allowed to start");
238 return JobScheduler.RESULT_FAILURE;
239 }
240 } catch (RemoteException e) {
241 }
Christopher Tate7060b042014-06-09 19:50:00 -0700242 startTrackingJob(jobStatus);
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700243 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700244 return JobScheduler.RESULT_SUCCESS;
245 }
246
247 public List<JobInfo> getPendingJobs(int uid) {
248 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
249 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700250 ArraySet<JobStatus> jobs = mJobs.getJobs();
251 for (int i=0; i<jobs.size(); i++) {
252 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700253 if (job.getUid() == uid) {
254 outList.add(job.getJob());
255 }
256 }
257 }
258 return outList;
259 }
260
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700261 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700262 List<JobStatus> jobsForUser;
Christopher Tate7060b042014-06-09 19:50:00 -0700263 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700264 jobsForUser = mJobs.getJobsByUser(userHandle);
265 }
266 for (int i=0; i<jobsForUser.size(); i++) {
267 JobStatus toRemove = jobsForUser.get(i);
268 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700269 }
270 }
271
272 /**
273 * Entry point from client to cancel all jobs originating from their uid.
274 * This will remove the job from the master list, and cancel the job if it was staged for
275 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700276 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700277 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
278 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700279 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700280 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700281 List<JobStatus> jobsForUid;
Christopher Tate7060b042014-06-09 19:50:00 -0700282 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700283 jobsForUid = mJobs.getJobsByUid(uid);
284 }
285 for (int i=0; i<jobsForUid.size(); i++) {
286 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700287 if (!forceAll) {
288 String packageName = toRemove.getServiceComponent().getPackageName();
289 try {
290 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
291 != ActivityManager.APP_START_MODE_DISABLED) {
292 continue;
293 }
294 } catch (RemoteException e) {
295 }
296 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700297 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700298 }
299 }
300
301 /**
302 * Entry point from client to cancel the job corresponding to the jobId provided.
303 * This will remove the job from the master list, and cancel the job if it was staged for
304 * execution or being executed.
305 * @param uid Uid of the calling client.
306 * @param jobId Id of the job, provided at schedule-time.
307 */
308 public void cancelJob(int uid, int jobId) {
309 JobStatus toCancel;
310 synchronized (mJobs) {
311 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700312 }
313 if (toCancel != null) {
314 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700315 }
316 }
317
Matthew Williams48a30db2014-09-23 13:39:36 -0700318 private void cancelJobImpl(JobStatus cancelled) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700319 if (DEBUG) {
320 Slog.d(TAG, "Cancelling: " + cancelled);
321 }
Christopher Tate7060b042014-06-09 19:50:00 -0700322 stopTrackingJob(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700323 synchronized (mJobs) {
324 // Remove from pending queue.
325 mPendingJobs.remove(cancelled);
326 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000327 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800328 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700329 }
Christopher Tate7060b042014-06-09 19:50:00 -0700330 }
331
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700332 void updateIdleMode(boolean enabled) {
333 boolean changed = false;
334 boolean rocking;
335 synchronized (mJobs) {
336 if (mDeviceIdleMode != enabled) {
337 changed = true;
338 }
339 rocking = mReadyToRock;
340 }
341 if (changed) {
342 if (rocking) {
343 for (int i=0; i<mControllers.size(); i++) {
344 mControllers.get(i).deviceIdleModeChanged(enabled);
345 }
346 }
347 synchronized (mJobs) {
348 mDeviceIdleMode = enabled;
349 if (enabled) {
350 // When becoming idle, make sure no jobs are actively running.
351 for (int i=0; i<mActiveServices.size(); i++) {
352 JobServiceContext jsc = mActiveServices.get(i);
353 final JobStatus executing = jsc.getRunningJob();
354 if (executing != null) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000355 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700356 }
357 }
358 } else {
359 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800360 if (rocking) {
361 if (mLocalDeviceIdleController != null) {
362 if (!mReportedActive) {
363 mReportedActive = true;
364 mLocalDeviceIdleController.setJobsActive(true);
365 }
366 }
367 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700368 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
369 }
370 }
371 }
372 }
373
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800374 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000375 // active is true if pending queue contains jobs OR some job is running.
376 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800377 if (mPendingJobs.size() <= 0) {
378 for (int i=0; i<mActiveServices.size(); i++) {
379 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000380 if (jsc.getRunningJob() != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800381 active = true;
382 break;
383 }
384 }
385 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000386
387 if (mReportedActive != active) {
388 mReportedActive = active;
389 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800390 mLocalDeviceIdleController.setJobsActive(active);
391 }
392 }
393 }
394
Christopher Tate7060b042014-06-09 19:50:00 -0700395 /**
396 * Initializes the system service.
397 * <p>
398 * Subclasses must define a single argument constructor that accepts the context
399 * and passes it to super.
400 * </p>
401 *
402 * @param context The system server context.
403 */
404 public JobSchedulerService(Context context) {
405 super(context);
406 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700407 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700408 mControllers.add(ConnectivityController.get(this));
409 mControllers.add(TimeController.get(this));
410 mControllers.add(IdleController.get(this));
411 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800412 mControllers.add(AppIdleController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700413
414 mHandler = new JobHandler(context.getMainLooper());
415 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700416 mJobs = JobStore.initAndGet(this);
417 }
418
419 @Override
420 public void onStart() {
421 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
422 }
423
424 @Override
425 public void onBootPhase(int phase) {
426 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000427 // Register br for package removals and user removals.
Christopher Tate7060b042014-06-09 19:50:00 -0700428 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
429 filter.addDataScheme("package");
430 getContext().registerReceiverAsUser(
431 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
432 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700433 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700434 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700435 getContext().registerReceiverAsUser(
436 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000437 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700438 try {
439 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
440 ActivityManager.UID_OBSERVER_IDLE);
441 } catch (RemoteException e) {
442 // ignored; both services live in system_server
443 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700444 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
445 synchronized (mJobs) {
446 // Let's go!
447 mReadyToRock = true;
448 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
449 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800450 mLocalDeviceIdleController
451 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700452 // Create the "runners".
453 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
454 mActiveServices.add(
455 new JobServiceContext(this, mBatteryStats,
456 getContext().getMainLooper()));
457 }
458 // Attach jobs to their controllers.
459 ArraySet<JobStatus> jobs = mJobs.getJobs();
460 for (int i=0; i<jobs.size(); i++) {
461 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700462 for (int controller=0; controller<mControllers.size(); controller++) {
Dianne Hackborn2bf51f42015-03-24 14:17:12 -0700463 mControllers.get(controller).deviceIdleModeChanged(mDeviceIdleMode);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700464 mControllers.get(controller).maybeStartTrackingJob(job);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700465 }
466 }
467 // GO GO GO!
468 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
469 }
Christopher Tate7060b042014-06-09 19:50:00 -0700470 }
471 }
472
473 /**
474 * Called when we have a job status object that we need to insert in our
475 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
476 * about.
477 */
478 private void startTrackingJob(JobStatus jobStatus) {
479 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700480 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700481 synchronized (mJobs) {
482 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700483 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700484 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700485 if (rocking) {
486 for (int i=0; i<mControllers.size(); i++) {
487 StateController controller = mControllers.get(i);
488 if (update) {
489 controller.maybeStopTrackingJob(jobStatus);
490 }
491 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700492 }
Christopher Tate7060b042014-06-09 19:50:00 -0700493 }
494 }
495
496 /**
497 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
498 * object removed.
499 */
500 private boolean stopTrackingJob(JobStatus jobStatus) {
501 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700502 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700503 synchronized (mJobs) {
504 // Remove from store as well as controllers.
505 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700506 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700507 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700508 if (removed && rocking) {
509 for (int i=0; i<mControllers.size(); i++) {
510 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700511 controller.maybeStopTrackingJob(jobStatus);
512 }
513 }
514 return removed;
515 }
516
Shreyas Basarge5db09082016-01-07 13:38:29 +0000517 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700518 for (int i=0; i<mActiveServices.size(); i++) {
519 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700520 final JobStatus executing = jsc.getRunningJob();
521 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000522 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700523 return true;
524 }
525 }
526 return false;
527 }
528
529 /**
530 * @param job JobStatus we are querying against.
531 * @return Whether or not the job represented by the status object is currently being run or
532 * is pending.
533 */
534 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700535 for (int i=0; i<mActiveServices.size(); i++) {
536 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700537 final JobStatus running = serviceContext.getRunningJob();
538 if (running != null && running.matches(job.getUid(), job.getJobId())) {
539 return true;
540 }
541 }
542 return false;
543 }
544
545 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700546 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
547 * specify an override deadline on a failed job (the failed job will run even though it's not
548 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
549 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
550 *
Christopher Tate7060b042014-06-09 19:50:00 -0700551 * @param failureToReschedule Provided job status that we will reschedule.
552 * @return A newly instantiated JobStatus with the same constraints as the last job except
553 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700554 *
555 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700556 */
557 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
558 final long elapsedNowMillis = SystemClock.elapsedRealtime();
559 final JobInfo job = failureToReschedule.getJob();
560
561 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700562 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
563 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700564
565 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700566 case JobInfo.BACKOFF_POLICY_LINEAR:
567 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700568 break;
569 default:
570 if (DEBUG) {
571 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
572 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700573 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
574 delayMillis =
575 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700576 break;
577 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700578 delayMillis =
579 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
580 return new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
581 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Christopher Tate7060b042014-06-09 19:50:00 -0700582 }
583
584 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700585 * Called after a periodic has executed so we can reschedule it. We take the last execution
586 * time of the job to be the time of completion (i.e. the time at which this function is
587 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700588 * This could be inaccurate b/c the job can run for as long as
589 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
590 * to underscheduling at least, rather than if we had taken the last execution time to be the
591 * start of the execution.
592 * @return A new job representing the execution criteria for this instantiation of the
593 * recurring job.
594 */
595 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
596 final long elapsedNow = SystemClock.elapsedRealtime();
597 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700598 long runEarly = 0L;
599
600 // If this periodic was rescheduled it won't have a deadline.
601 if (periodicToReschedule.hasDeadlineConstraint()) {
602 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
603 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000604 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700605 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000606 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
607 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -0700608
609 if (DEBUG) {
610 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
611 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
612 }
613 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
614 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
615 }
616
617 // JobCompletedListener implementations.
618
619 /**
620 * A job just finished executing. We fetch the
621 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
622 * whether we want to reschedule we readd it to the controllers.
623 * @param jobStatus Completed job.
624 * @param needsReschedule Whether the implementing class should reschedule this job.
625 */
626 @Override
627 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
628 if (DEBUG) {
629 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
630 }
631 if (!stopTrackingJob(jobStatus)) {
632 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700633 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700634 }
635 return;
636 }
637 if (needsReschedule) {
638 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
639 startTrackingJob(rescheduled);
640 } else if (jobStatus.getJob().isPeriodic()) {
641 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
642 startTrackingJob(rescheduledPeriodic);
643 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000644 reportActive();
645 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700646 }
647
648 // StateChangedListener implementations.
649
650 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700651 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
652 * some controller's state has changed, so as to run through the list of jobs and start/stop
653 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700654 */
655 @Override
656 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700657 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700658 }
659
660 @Override
661 public void onRunJobNow(JobStatus jobStatus) {
662 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
663 }
664
Christopher Tate7060b042014-06-09 19:50:00 -0700665 private class JobHandler extends Handler {
666
667 public JobHandler(Looper looper) {
668 super(looper);
669 }
670
671 @Override
672 public void handleMessage(Message message) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700673 synchronized (mJobs) {
674 if (!mReadyToRock) {
675 return;
676 }
677 }
Christopher Tate7060b042014-06-09 19:50:00 -0700678 switch (message.what) {
679 case MSG_JOB_EXPIRED:
680 synchronized (mJobs) {
681 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700682 // runNow can be null, which is a controller's way of indicating that its
683 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700684 if (runNow != null && !mPendingJobs.contains(runNow)
685 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700686 mPendingJobs.add(runNow);
687 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700688 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700689 }
Christopher Tate7060b042014-06-09 19:50:00 -0700690 break;
691 case MSG_CHECK_JOB:
Matthew Williams48a30db2014-09-23 13:39:36 -0700692 synchronized (mJobs) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000693 if (mReportedActive) {
694 // if jobs are currently being run, queue all ready jobs for execution.
695 queueReadyJobsForExecutionLockedH();
696 } else {
697 // Check the list of jobs and run some of them if we feel inclined.
698 maybeQueueReadyJobsForExecutionLockedH();
699 }
700 }
701 break;
702 case MSG_CHECK_JOB_GREEDY:
703 synchronized (mJobs) {
704 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700705 }
Christopher Tate7060b042014-06-09 19:50:00 -0700706 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700707 case MSG_STOP_JOB:
708 cancelJobImpl((JobStatus)message.obj);
709 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700710 }
711 maybeRunPendingJobsH();
712 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
713 removeMessages(MSG_CHECK_JOB);
714 }
715
716 /**
717 * Run through list of jobs and execute all possible - at least one is expired so we do
718 * as many as we can.
719 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700720 private void queueReadyJobsForExecutionLockedH() {
721 ArraySet<JobStatus> jobs = mJobs.getJobs();
Shreyas Basarge5db09082016-01-07 13:38:29 +0000722 mPendingJobs.clear();
Matthew Williams48a30db2014-09-23 13:39:36 -0700723 if (DEBUG) {
724 Slog.d(TAG, "queuing all ready jobs for execution:");
725 }
726 for (int i=0; i<jobs.size(); i++) {
727 JobStatus job = jobs.valueAt(i);
728 if (isReadyToBeExecutedLocked(job)) {
729 if (DEBUG) {
730 Slog.d(TAG, " queued " + job.toShortString());
Christopher Tate7060b042014-06-09 19:50:00 -0700731 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700732 mPendingJobs.add(job);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000733 } else if (areJobConstraintsNotSatisfied(job)) {
734 stopJobOnServiceContextLocked(job,
735 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700736 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700737 }
738 if (DEBUG) {
739 final int queuedJobs = mPendingJobs.size();
740 if (queuedJobs == 0) {
741 Slog.d(TAG, "No jobs pending.");
742 } else {
743 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700744 }
Christopher Tate7060b042014-06-09 19:50:00 -0700745 }
746 }
747
748 /**
749 * The state of at least one job has changed. Here is where we could enforce various
750 * policies on when we want to execute jobs.
751 * Right now the policy is such:
752 * If >1 of the ready jobs is idle mode we send all of them off
753 * if more than 2 network connectivity jobs are ready we send them all off.
754 * If more than 4 jobs total are ready we send them all off.
755 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
756 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700757 private void maybeQueueReadyJobsForExecutionLockedH() {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000758 mPendingJobs.clear();
Matthew Williams48a30db2014-09-23 13:39:36 -0700759 int chargingCount = 0;
Shreyas Basarge5db09082016-01-07 13:38:29 +0000760 int idleCount = 0;
Matthew Williams48a30db2014-09-23 13:39:36 -0700761 int backoffCount = 0;
762 int connectivityCount = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700763 List<JobStatus> runnableJobs = null;
Matthew Williams48a30db2014-09-23 13:39:36 -0700764 ArraySet<JobStatus> jobs = mJobs.getJobs();
765 for (int i=0; i<jobs.size(); i++) {
766 JobStatus job = jobs.valueAt(i);
767 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700768 try {
769 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
770 job.getJob().getService().getPackageName())
771 == ActivityManager.APP_START_MODE_DISABLED) {
772 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
773 + job.getJob().toString() + " -- package not allowed to start");
774 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
775 continue;
776 }
777 } catch (RemoteException e) {
778 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700779 if (job.getNumFailures() > 0) {
780 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700781 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700782 if (job.hasIdleConstraint()) {
783 idleCount++;
784 }
785 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
786 connectivityCount++;
787 }
788 if (job.hasChargingConstraint()) {
789 chargingCount++;
790 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700791 if (runnableJobs == null) {
792 runnableJobs = new ArrayList<>();
793 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700794 runnableJobs.add(job);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000795 } else if (areJobConstraintsNotSatisfied(job)) {
796 stopJobOnServiceContextLocked(job,
797 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -0700798 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700799 }
800 if (backoffCount > 0 ||
801 idleCount >= MIN_IDLE_COUNT ||
802 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
803 chargingCount >= MIN_CHARGING_COUNT ||
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700804 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700805 if (DEBUG) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700806 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
Christopher Tate7060b042014-06-09 19:50:00 -0700807 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700808 for (int i=0; i<runnableJobs.size(); i++) {
809 mPendingJobs.add(runnableJobs.get(i));
810 }
811 } else {
812 if (DEBUG) {
813 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
814 }
815 }
Christopher Tate7060b042014-06-09 19:50:00 -0700816 }
817
818 /**
819 * Criteria for moving a job into the pending queue:
820 * - It's ready.
821 * - It's not pending.
822 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700823 * - The user that requested the job is running.
Christopher Tate7060b042014-06-09 19:50:00 -0700824 */
825 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700826 final boolean jobReady = job.isReady();
827 final boolean jobPending = mPendingJobs.contains(job);
828 final boolean jobActive = isCurrentlyActiveLocked(job);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000829 final boolean userRunning = mStartedUsers.contains(job.getUserId());
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700830 if (DEBUG) {
831 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
832 + " ready=" + jobReady + " pending=" + jobPending
Shreyas Basarge5db09082016-01-07 13:38:29 +0000833 + " active=" + jobActive + " userRunning=" + userRunning);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700834 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000835 return userRunning && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700836 }
837
838 /**
839 * Criteria for cancelling an active job:
840 * - It's not ready
841 * - It's running on a JSC.
842 */
Shreyas Basarge5db09082016-01-07 13:38:29 +0000843 private boolean areJobConstraintsNotSatisfied(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -0700844 return !job.isReady() && isCurrentlyActiveLocked(job);
845 }
846
847 /**
848 * Reconcile jobs in the pending queue against available execution contexts.
849 * A controller can force a job into the pending queue even if it's already running, but
850 * here is where we decide whether to actually execute it.
851 */
852 private void maybeRunPendingJobsH() {
853 synchronized (mJobs) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700854 if (mDeviceIdleMode) {
855 // If device is idle, we will not schedule jobs to run.
856 return;
857 }
Matthew Williams75fc5252014-09-02 16:17:53 -0700858 if (DEBUG) {
859 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
860 }
Shreyas Basarge5db09082016-01-07 13:38:29 +0000861 assignJobsToContextsH();
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800862 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700863 }
864 }
865 }
866
867 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +0000868 * Takes jobs from pending queue and runs them on available contexts.
869 * If no contexts are available, preempts lower priority jobs to
870 * run higher priority ones.
871 * Lock on mJobs before calling this function.
872 */
873 private void assignJobsToContextsH() {
874 if (DEBUG) {
875 Slog.d(TAG, printPendingQueue());
876 }
877
878 // This array essentially stores the state of mActiveServices array.
879 // ith index stores the job present on the ith JobServiceContext.
880 // We manipulate this array until we arrive at what jobs should be running on
881 // what JobServiceContext.
882 JobStatus[] contextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
883 // Indicates whether we need to act on this jobContext id
884 boolean[] act = new boolean[MAX_JOB_CONTEXTS_COUNT];
885 int[] preferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
886 for (int i=0; i<mActiveServices.size(); i++) {
887 contextIdToJobMap[i] = mActiveServices.get(i).getRunningJob();
888 preferredUidForContext[i] = mActiveServices.get(i).getPreferredUid();
889 }
890 if (DEBUG) {
891 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
892 }
893 Iterator<JobStatus> it = mPendingJobs.iterator();
894 while (it.hasNext()) {
895 JobStatus nextPending = it.next();
896
897 // If job is already running, go to next job.
898 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
899 if (jobRunningContext != -1) {
900 continue;
901 }
902
903 // Find a context for nextPending. The context should be available OR
904 // it should have lowest priority among all running jobs
905 // (sharing the same Uid as nextPending)
906 int minPriority = Integer.MAX_VALUE;
907 int minPriorityContextId = -1;
908 for (int i=0; i<mActiveServices.size(); i++) {
909 JobStatus job = contextIdToJobMap[i];
910 int preferredUid = preferredUidForContext[i];
911 if (job == null && (preferredUid == nextPending.getUid() ||
912 preferredUid == JobServiceContext.NO_PREFERRED_UID) ) {
913 minPriorityContextId = i;
914 break;
915 }
916 if (job.getUid() != nextPending.getUid()) {
917 continue;
918 }
919 if (job.getPriority() >= nextPending.getPriority()) {
920 continue;
921 }
922 if (minPriority > nextPending.getPriority()) {
923 minPriority = nextPending.getPriority();
924 minPriorityContextId = i;
925 }
926 }
927 if (minPriorityContextId != -1) {
928 contextIdToJobMap[minPriorityContextId] = nextPending;
929 act[minPriorityContextId] = true;
930 }
931 }
932 if (DEBUG) {
933 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
934 }
935 for (int i=0; i<mActiveServices.size(); i++) {
936 boolean preservePreferredUid = false;
937 if (act[i]) {
938 JobStatus js = mActiveServices.get(i).getRunningJob();
939 if (js != null) {
940 if (DEBUG) {
941 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
942 }
943 // preferredUid will be set to uid of currently running job.
944 mActiveServices.get(i).preemptExecutingJob();
945 preservePreferredUid = true;
946 } else {
947 if (DEBUG) {
948 Slog.d(TAG, "About to run job on context "
949 + String.valueOf(i) + ", job: " + contextIdToJobMap[i]);
950 }
951 if (!mActiveServices.get(i).executeRunnableJob(contextIdToJobMap[i])) {
952 Slog.d(TAG, "Error executing " + contextIdToJobMap[i]);
953 }
954 mPendingJobs.remove(contextIdToJobMap[i]);
955 }
956 }
957 if (!preservePreferredUid) {
958 mActiveServices.get(i).clearPreferredUid();
959 }
960 }
961 }
962
963 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
964 for (int i=0; i<map.length; i++) {
965 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
966 return i;
967 }
968 }
969 return -1;
970 }
971
972 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700973 * Binder stub trampoline implementation
974 */
975 final class JobSchedulerStub extends IJobScheduler.Stub {
976 /** Cache determination of whether a given app can persist jobs
977 * key is uid of the calling app; value is undetermined/true/false
978 */
979 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
980
981 // Enforce that only the app itself (or shared uid participant) can schedule a
982 // job that runs one of the app's services, as well as verifying that the
983 // named service properly requires the BIND_JOB_SERVICE permission
984 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700985 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700986 final ComponentName service = job.getService();
987 try {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000988 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -0700989 if (si == null) {
990 throw new IllegalArgumentException("No such service " + service);
991 }
Christopher Tate7060b042014-06-09 19:50:00 -0700992 if (si.applicationInfo.uid != uid) {
993 throw new IllegalArgumentException("uid " + uid +
994 " cannot schedule job in " + service.getPackageName());
995 }
996 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
997 throw new IllegalArgumentException("Scheduled service " + service
998 + " does not require android.permission.BIND_JOB_SERVICE permission");
999 }
Christopher Tate5568f542014-06-18 13:53:31 -07001000 } catch (RemoteException e) {
1001 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001002 }
1003 }
1004
1005 private boolean canPersistJobs(int pid, int uid) {
1006 // If we get this far we're good to go; all we need to do now is check
1007 // whether the app is allowed to persist its scheduled work.
1008 final boolean canPersist;
1009 synchronized (mPersistCache) {
1010 Boolean cached = mPersistCache.get(uid);
1011 if (cached != null) {
1012 canPersist = cached.booleanValue();
1013 } else {
1014 // Persisting jobs is tantamount to running at boot, so we permit
1015 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1016 // permission
1017 int result = getContext().checkPermission(
1018 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1019 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1020 mPersistCache.put(uid, canPersist);
1021 }
1022 }
1023 return canPersist;
1024 }
1025
1026 // IJobScheduler implementation
1027 @Override
1028 public int schedule(JobInfo job) throws RemoteException {
1029 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001030 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001031 }
1032 final int pid = Binder.getCallingPid();
1033 final int uid = Binder.getCallingUid();
1034
1035 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001036 if (job.isPersisted()) {
1037 if (!canPersistJobs(pid, uid)) {
1038 throw new IllegalArgumentException("Error: requested job be persisted without"
1039 + " holding RECEIVE_BOOT_COMPLETED permission.");
1040 }
1041 }
Christopher Tate7060b042014-06-09 19:50:00 -07001042
1043 long ident = Binder.clearCallingIdentity();
1044 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001045 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001046 } finally {
1047 Binder.restoreCallingIdentity(ident);
1048 }
1049 }
1050
1051 @Override
Shreyas Basarge968ac752016-01-11 23:09:26 +00001052 public int scheduleAsPackage(JobInfo job, String packageName, int userId)
1053 throws RemoteException {
1054 if (DEBUG) {
1055 Slog.d(TAG, "Scheduling job: " + job.toString() + " on behalf of " + packageName);
1056 }
1057 final int uid = Binder.getCallingUid();
1058 if (uid != Process.SYSTEM_UID) {
1059 throw new IllegalArgumentException("Only system process is allowed"
1060 + "to set packageName");
1061 }
1062 long ident = Binder.clearCallingIdentity();
1063 try {
1064 return JobSchedulerService.this.scheduleAsPackage(job, uid, packageName, userId);
1065 } finally {
1066 Binder.restoreCallingIdentity(ident);
1067 }
1068 }
1069
1070 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001071 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1072 final int uid = Binder.getCallingUid();
1073
1074 long ident = Binder.clearCallingIdentity();
1075 try {
1076 return JobSchedulerService.this.getPendingJobs(uid);
1077 } finally {
1078 Binder.restoreCallingIdentity(ident);
1079 }
1080 }
1081
1082 @Override
1083 public void cancelAll() throws RemoteException {
1084 final int uid = Binder.getCallingUid();
1085
1086 long ident = Binder.clearCallingIdentity();
1087 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001088 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001089 } finally {
1090 Binder.restoreCallingIdentity(ident);
1091 }
1092 }
1093
1094 @Override
1095 public void cancel(int jobId) throws RemoteException {
1096 final int uid = Binder.getCallingUid();
1097
1098 long ident = Binder.clearCallingIdentity();
1099 try {
1100 JobSchedulerService.this.cancelJob(uid, jobId);
1101 } finally {
1102 Binder.restoreCallingIdentity(ident);
1103 }
1104 }
1105
1106 /**
1107 * "dumpsys" infrastructure
1108 */
1109 @Override
1110 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1111 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1112
1113 long identityToken = Binder.clearCallingIdentity();
1114 try {
1115 JobSchedulerService.this.dumpInternal(pw);
1116 } finally {
1117 Binder.restoreCallingIdentity(identityToken);
1118 }
1119 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001120 };
1121
1122 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1123 StringBuilder s = new StringBuilder(initial + ": ");
1124 for (int i=0; i<map.length; i++) {
1125 s.append("(")
1126 .append(map[i] == null? -1: map[i].getJobId())
1127 .append(map[i] == null? -1: map[i].getUid())
1128 .append(")" );
1129 }
1130 return s.toString();
1131 }
1132
1133 private String printPendingQueue() {
1134 StringBuilder s = new StringBuilder("Pending queue: ");
1135 Iterator<JobStatus> it = mPendingJobs.iterator();
1136 while (it.hasNext()) {
1137 JobStatus js = it.next();
1138 s.append("(")
1139 .append(js.getJob().getId())
1140 .append(", ")
1141 .append(js.getUid())
1142 .append(") ");
1143 }
1144 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001145 }
Christopher Tate7060b042014-06-09 19:50:00 -07001146
1147 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001148 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -07001149 synchronized (mJobs) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001150 pw.print("Started users: ");
1151 for (int i=0; i<mStartedUsers.size(); i++) {
1152 pw.print("u" + mStartedUsers.get(i) + " ");
1153 }
1154 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07001155 pw.println("Registered jobs:");
1156 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001157 ArraySet<JobStatus> jobs = mJobs.getJobs();
1158 for (int i=0; i<jobs.size(); i++) {
1159 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001160 job.dump(pw, " ");
1161 }
1162 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001163 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001164 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001165 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001166 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001167 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001168 }
1169 pw.println();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001170 pw.println(printPendingQueue());
Christopher Tate7060b042014-06-09 19:50:00 -07001171 pw.println();
1172 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001173 for (int i=0; i<mActiveServices.size(); i++) {
1174 JobServiceContext jsc = mActiveServices.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001175 if (jsc.getRunningJob() == null) {
Christopher Tate7060b042014-06-09 19:50:00 -07001176 continue;
1177 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001178 final long timeout = jsc.getTimeoutElapsed();
1179 pw.print("Running for: ");
1180 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1181 pw.print("s timeout=");
1182 pw.print(timeout);
1183 pw.print(" fromnow=");
1184 pw.println(timeout-now);
1185 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -07001186 }
1187 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001188 pw.println();
1189 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001190 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001191 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001192 }
1193 pw.println();
1194 }
1195}