blob: 3530d80577c71a6e24572a11e921f956f39e5b35 [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
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070019import android.app.ActivityManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070020import android.app.ActivityManagerNative;
Christopher Tate5568f542014-06-18 13:53:31 -070021import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070022import android.app.IUidObserver;
Jeff Sharkey5217cac2015-12-20 15:34:01 -070023import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070024import android.app.job.JobInfo;
25import android.app.job.JobScheduler;
26import android.app.job.JobService;
Christopher Tate7060b042014-06-09 19:50:00 -070027import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070032import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070033import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070034import android.content.pm.ServiceInfo;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070035import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070036import android.os.Binder;
37import android.os.Handler;
38import android.os.Looper;
39import android.os.Message;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070040import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.os.RemoteException;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070042import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070043import android.os.SystemClock;
44import android.os.UserHandle;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070045import android.util.ArraySet;
Christopher Tate7060b042014-06-09 19:50:00 -070046import android.util.Slog;
47import android.util.SparseArray;
48
Dianne Hackbornfdb19562014-07-11 16:03:36 -070049import com.android.internal.app.IBatteryStats;
Jeff Sharkey5217cac2015-12-20 15:34:01 -070050import com.android.internal.util.ArrayUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080051import com.android.server.DeviceIdleController;
52import com.android.server.LocalServices;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080053import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070054import com.android.server.job.controllers.BatteryController;
55import com.android.server.job.controllers.ConnectivityController;
56import com.android.server.job.controllers.IdleController;
57import com.android.server.job.controllers.JobStatus;
58import com.android.server.job.controllers.StateController;
59import com.android.server.job.controllers.TimeController;
60
Jeff Sharkey5217cac2015-12-20 15:34:01 -070061import libcore.util.EmptyArray;
62
63import java.io.FileDescriptor;
64import java.io.PrintWriter;
65import java.util.ArrayList;
66import java.util.Arrays;
67import java.util.Iterator;
68import java.util.List;
69
Christopher Tate7060b042014-06-09 19:50:00 -070070/**
71 * Responsible for taking jobs representing work to be performed by a client app, and determining
72 * based on the criteria specified when that job should be run against the client application's
73 * endpoint.
74 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
75 * about constraints, or the state of active jobs. It receives callbacks from the various
76 * controllers and completed jobs and operates accordingly.
77 *
78 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
79 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
80 * @hide
81 */
82public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070083 implements StateChangedListener, JobCompletedListener {
Matthew Williamsaa984312015-10-15 16:08:05 -070084 public static final boolean DEBUG = false;
Christopher Tate7060b042014-06-09 19:50:00 -070085 /** The number of concurrent jobs we run at one time. */
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070086 private static final int MAX_JOB_CONTEXTS_COUNT
87 = ActivityManager.isLowRamDeviceStatic() ? 1 : 3;
Matthew Williamsbe0c4172014-08-06 18:14:16 -070088 static final String TAG = "JobSchedulerService";
Christopher Tate7060b042014-06-09 19:50:00 -070089 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070090 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -070091
92 static final int MSG_JOB_EXPIRED = 0;
93 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070094 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +000095 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -070096
97 // Policy constants
98 /**
99 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
100 * early.
101 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700102 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -0700103 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700104 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
105 * early.
106 */
107 static final int MIN_CHARGING_COUNT = 1;
108 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700109 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
110 * things early.
111 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700112 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700113 /**
114 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
115 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700116 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700117 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700118 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700119
120 /**
121 * Track Services that have currently active or pending jobs. The index is provided by
122 * {@link JobStatus#getServiceToken()}
123 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700124 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700125 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700126 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700127 /**
128 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
129 * when ready to execute them.
130 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700131 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700132
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700133 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700134
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700135 final JobHandler mHandler;
136 final JobSchedulerStub mJobSchedulerStub;
137
138 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700139 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800140 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700141
142 /**
143 * Set to true once we are allowed to run third party apps.
144 */
145 boolean mReadyToRock;
146
Christopher Tate7060b042014-06-09 19:50:00 -0700147 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700148 * True when in device idle mode, so we don't want to schedule any jobs.
149 */
150 boolean mDeviceIdleMode;
151
152 /**
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800153 * What we last reported to DeviceIdleController about wheter we are active.
154 */
155 boolean mReportedActive;
156
157 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700158 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
159 * still clean up. On reinstall the package will have a new uid.
160 */
161 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
162 @Override
163 public void onReceive(Context context, Intent intent) {
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700164 final String action = intent.getAction();
165 Slog.d(TAG, "Receieved: " + action);
166 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700167 // If this is an outright uninstall rather than the first half of an
168 // app update sequence, cancel the jobs associated with the app.
169 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
170 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
171 if (DEBUG) {
172 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
173 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700174 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700175 }
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700176 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700177 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
178 if (DEBUG) {
179 Slog.d(TAG, "Removing jobs for user: " + userId);
180 }
181 cancelJobsForUser(userId);
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700182 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(action)
183 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(action)) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700184 updateIdleMode(mPowerManager != null
185 ? (mPowerManager.isDeviceIdleMode()
186 || mPowerManager.isLightDeviceIdleMode())
187 : false);
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700188 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
189 // Kick off pending jobs for any apps that re-appeared
190 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
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) {
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700212 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
213 // Let's kick any outstanding jobs for this user.
214 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
215 }
216
217 @Override
218 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700219 // Let's kick any outstanding jobs for this user.
220 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
221 }
222
223 @Override
224 public void onStopUser(int userHandle) {
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700225 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700226 }
227
Christopher Tate7060b042014-06-09 19:50:00 -0700228 /**
229 * Entry point from client to schedule the provided job.
230 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
231 * @param job JobInfo object containing execution parameters
232 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700233 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
234 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700235 public int schedule(JobInfo job, int uId) {
236 JobStatus jobStatus = new JobStatus(job, uId);
Christopher Tate7060b042014-06-09 19:50:00 -0700237 cancelJob(uId, job.getId());
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 }
Christopher Tate7060b042014-06-09 19:50:00 -0700247 startTrackingJob(jobStatus);
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700248 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700249 return JobScheduler.RESULT_SUCCESS;
250 }
251
252 public List<JobInfo> getPendingJobs(int uid) {
253 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
254 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700255 ArraySet<JobStatus> jobs = mJobs.getJobs();
256 for (int i=0; i<jobs.size(); i++) {
257 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700258 if (job.getUid() == uid) {
259 outList.add(job.getJob());
260 }
261 }
262 }
263 return outList;
264 }
265
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700266 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700267 List<JobStatus> jobsForUser;
Christopher Tate7060b042014-06-09 19:50:00 -0700268 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700269 jobsForUser = mJobs.getJobsByUser(userHandle);
270 }
271 for (int i=0; i<jobsForUser.size(); i++) {
272 JobStatus toRemove = jobsForUser.get(i);
273 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700274 }
275 }
276
277 /**
278 * Entry point from client to cancel all jobs originating from their uid.
279 * This will remove the job from the master list, and cancel the job if it was staged for
280 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700281 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700282 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
283 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700284 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700285 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700286 List<JobStatus> jobsForUid;
Christopher Tate7060b042014-06-09 19:50:00 -0700287 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700288 jobsForUid = mJobs.getJobsByUid(uid);
289 }
290 for (int i=0; i<jobsForUid.size(); i++) {
291 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700292 if (!forceAll) {
293 String packageName = toRemove.getServiceComponent().getPackageName();
294 try {
295 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
296 != ActivityManager.APP_START_MODE_DISABLED) {
297 continue;
298 }
299 } catch (RemoteException e) {
300 }
301 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700302 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700303 }
304 }
305
306 /**
307 * Entry point from client to cancel the job corresponding to the jobId provided.
308 * This will remove the job from the master list, and cancel the job if it was staged for
309 * execution or being executed.
310 * @param uid Uid of the calling client.
311 * @param jobId Id of the job, provided at schedule-time.
312 */
313 public void cancelJob(int uid, int jobId) {
314 JobStatus toCancel;
315 synchronized (mJobs) {
316 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700317 }
318 if (toCancel != null) {
319 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700320 }
321 }
322
Matthew Williams48a30db2014-09-23 13:39:36 -0700323 private void cancelJobImpl(JobStatus cancelled) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700324 if (DEBUG) {
325 Slog.d(TAG, "Cancelling: " + cancelled);
326 }
Christopher Tate7060b042014-06-09 19:50:00 -0700327 stopTrackingJob(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700328 synchronized (mJobs) {
329 // Remove from pending queue.
330 mPendingJobs.remove(cancelled);
331 // Cancel if running.
332 stopJobOnServiceContextLocked(cancelled);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800333 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700334 }
Christopher Tate7060b042014-06-09 19:50:00 -0700335 }
336
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700337 void updateIdleMode(boolean enabled) {
338 boolean changed = false;
339 boolean rocking;
340 synchronized (mJobs) {
341 if (mDeviceIdleMode != enabled) {
342 changed = true;
343 }
344 rocking = mReadyToRock;
345 }
346 if (changed) {
347 if (rocking) {
348 for (int i=0; i<mControllers.size(); i++) {
349 mControllers.get(i).deviceIdleModeChanged(enabled);
350 }
351 }
352 synchronized (mJobs) {
353 mDeviceIdleMode = enabled;
354 if (enabled) {
355 // When becoming idle, make sure no jobs are actively running.
356 for (int i=0; i<mActiveServices.size(); i++) {
357 JobServiceContext jsc = mActiveServices.get(i);
358 final JobStatus executing = jsc.getRunningJob();
359 if (executing != null) {
360 jsc.cancelExecutingJob();
361 }
362 }
363 } else {
364 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800365 if (rocking) {
366 if (mLocalDeviceIdleController != null) {
367 if (!mReportedActive) {
368 mReportedActive = true;
369 mLocalDeviceIdleController.setJobsActive(true);
370 }
371 }
372 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700373 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
374 }
375 }
376 }
377 }
378
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800379 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000380 // active is true if pending queue contains jobs OR some job is running.
381 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800382 if (mPendingJobs.size() <= 0) {
383 for (int i=0; i<mActiveServices.size(); i++) {
384 JobServiceContext jsc = mActiveServices.get(i);
385 if (!jsc.isAvailable()) {
386 active = true;
387 break;
388 }
389 }
390 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000391
392 if (mReportedActive != active) {
393 mReportedActive = active;
394 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800395 mLocalDeviceIdleController.setJobsActive(active);
396 }
397 }
398 }
399
Christopher Tate7060b042014-06-09 19:50:00 -0700400 /**
401 * Initializes the system service.
402 * <p>
403 * Subclasses must define a single argument constructor that accepts the context
404 * and passes it to super.
405 * </p>
406 *
407 * @param context The system server context.
408 */
409 public JobSchedulerService(Context context) {
410 super(context);
411 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700412 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700413 mControllers.add(ConnectivityController.get(this));
414 mControllers.add(TimeController.get(this));
415 mControllers.add(IdleController.get(this));
416 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800417 mControllers.add(AppIdleController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700418
419 mHandler = new JobHandler(context.getMainLooper());
420 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700421 mJobs = JobStore.initAndGet(this);
422 }
423
424 @Override
425 public void onStart() {
426 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
427 }
428
429 @Override
430 public void onBootPhase(int phase) {
431 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700432 // Register for package removals and user removals.
Christopher Tate7060b042014-06-09 19:50:00 -0700433 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
434 filter.addDataScheme("package");
435 getContext().registerReceiverAsUser(
436 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700437
Christopher Tate7060b042014-06-09 19:50:00 -0700438 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700439 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700440 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700441 getContext().registerReceiverAsUser(
442 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700443
444 final IntentFilter storageFilter = new IntentFilter();
445 storageFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
446 getContext().registerReceiverAsUser(
447 mBroadcastReceiver, UserHandle.ALL, storageFilter, null, null);
448
449 mPowerManager = getContext().getSystemService(PowerManager.class);
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);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700476 mControllers.get(controller).maybeStartTrackingJob(job);
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 */
490 private void startTrackingJob(JobStatus jobStatus) {
491 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) {
501 controller.maybeStopTrackingJob(jobStatus);
502 }
503 controller.maybeStartTrackingJob(jobStatus);
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 */
512 private boolean stopTrackingJob(JobStatus jobStatus) {
513 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.
517 removed = mJobs.remove(jobStatus);
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);
Christopher Tate7060b042014-06-09 19:50:00 -0700523 controller.maybeStopTrackingJob(jobStatus);
524 }
525 }
526 return removed;
527 }
528
529 private boolean stopJobOnServiceContextLocked(JobStatus job) {
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())) {
534 jsc.cancelExecutingJob();
535 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);
592 return new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
593 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Christopher Tate7060b042014-06-09 19:50:00 -0700594 }
595
596 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700597 * Called after a periodic has executed so we can reschedule it. We take the last execution
598 * time of the job to be the time of completion (i.e. the time at which this function is
599 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700600 * This could be inaccurate b/c the job can run for as long as
601 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
602 * to underscheduling at least, rather than if we had taken the last execution time to be the
603 * start of the execution.
604 * @return A new job representing the execution criteria for this instantiation of the
605 * recurring job.
606 */
607 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
608 final long elapsedNow = SystemClock.elapsedRealtime();
609 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700610 long runEarly = 0L;
611
612 // If this periodic was rescheduled it won't have a deadline.
613 if (periodicToReschedule.hasDeadlineConstraint()) {
614 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
615 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000616 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700617 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000618 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
619 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -0700620
621 if (DEBUG) {
622 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
623 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
624 }
625 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
626 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
627 }
628
629 // JobCompletedListener implementations.
630
631 /**
632 * A job just finished executing. We fetch the
633 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
634 * whether we want to reschedule we readd it to the controllers.
635 * @param jobStatus Completed job.
636 * @param needsReschedule Whether the implementing class should reschedule this job.
637 */
638 @Override
639 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
640 if (DEBUG) {
641 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
642 }
643 if (!stopTrackingJob(jobStatus)) {
644 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700645 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700646 }
647 return;
648 }
649 if (needsReschedule) {
650 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
651 startTrackingJob(rescheduled);
652 } else if (jobStatus.getJob().isPeriodic()) {
653 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
654 startTrackingJob(rescheduledPeriodic);
655 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000656 reportActive();
657 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700658 }
659
660 // StateChangedListener implementations.
661
662 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700663 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
664 * some controller's state has changed, so as to run through the list of jobs and start/stop
665 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700666 */
667 @Override
668 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700669 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700670 }
671
672 @Override
673 public void onRunJobNow(JobStatus jobStatus) {
674 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
675 }
676
Christopher Tate7060b042014-06-09 19:50:00 -0700677 private class JobHandler extends Handler {
678
679 public JobHandler(Looper looper) {
680 super(looper);
681 }
682
683 @Override
684 public void handleMessage(Message message) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700685 synchronized (mJobs) {
686 if (!mReadyToRock) {
687 return;
688 }
689 }
Christopher Tate7060b042014-06-09 19:50:00 -0700690 switch (message.what) {
691 case MSG_JOB_EXPIRED:
692 synchronized (mJobs) {
693 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700694 // runNow can be null, which is a controller's way of indicating that its
695 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700696 if (runNow != null && !mPendingJobs.contains(runNow)
697 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700698 mPendingJobs.add(runNow);
699 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700700 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700701 }
Christopher Tate7060b042014-06-09 19:50:00 -0700702 break;
703 case MSG_CHECK_JOB:
Matthew Williams48a30db2014-09-23 13:39:36 -0700704 synchronized (mJobs) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000705 if (mReportedActive) {
706 // if jobs are currently being run, queue all ready jobs for execution.
707 queueReadyJobsForExecutionLockedH();
708 } else {
709 // Check the list of jobs and run some of them if we feel inclined.
710 maybeQueueReadyJobsForExecutionLockedH();
711 }
712 }
713 break;
714 case MSG_CHECK_JOB_GREEDY:
715 synchronized (mJobs) {
716 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700717 }
Christopher Tate7060b042014-06-09 19:50:00 -0700718 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700719 case MSG_STOP_JOB:
720 cancelJobImpl((JobStatus)message.obj);
721 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700722 }
723 maybeRunPendingJobsH();
724 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
725 removeMessages(MSG_CHECK_JOB);
726 }
727
728 /**
729 * Run through list of jobs and execute all possible - at least one is expired so we do
730 * as many as we can.
731 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700732 private void queueReadyJobsForExecutionLockedH() {
733 ArraySet<JobStatus> jobs = mJobs.getJobs();
734 if (DEBUG) {
735 Slog.d(TAG, "queuing all ready jobs for execution:");
736 }
737 for (int i=0; i<jobs.size(); i++) {
738 JobStatus job = jobs.valueAt(i);
739 if (isReadyToBeExecutedLocked(job)) {
740 if (DEBUG) {
741 Slog.d(TAG, " queued " + job.toShortString());
Christopher Tate7060b042014-06-09 19:50:00 -0700742 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700743 mPendingJobs.add(job);
744 } else if (isReadyToBeCancelledLocked(job)) {
745 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700746 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700747 }
748 if (DEBUG) {
749 final int queuedJobs = mPendingJobs.size();
750 if (queuedJobs == 0) {
751 Slog.d(TAG, "No jobs pending.");
752 } else {
753 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700754 }
Christopher Tate7060b042014-06-09 19:50:00 -0700755 }
756 }
757
758 /**
759 * The state of at least one job has changed. Here is where we could enforce various
760 * policies on when we want to execute jobs.
761 * Right now the policy is such:
762 * If >1 of the ready jobs is idle mode we send all of them off
763 * if more than 2 network connectivity jobs are ready we send them all off.
764 * If more than 4 jobs total are ready we send them all off.
765 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
766 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700767 private void maybeQueueReadyJobsForExecutionLockedH() {
768 int chargingCount = 0;
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700769 int idleCount = 0;
Matthew Williams48a30db2014-09-23 13:39:36 -0700770 int backoffCount = 0;
771 int connectivityCount = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700772 List<JobStatus> runnableJobs = null;
Matthew Williams48a30db2014-09-23 13:39:36 -0700773 ArraySet<JobStatus> jobs = mJobs.getJobs();
774 for (int i=0; i<jobs.size(); i++) {
775 JobStatus job = jobs.valueAt(i);
776 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700777 try {
778 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
779 job.getJob().getService().getPackageName())
780 == ActivityManager.APP_START_MODE_DISABLED) {
781 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
782 + job.getJob().toString() + " -- package not allowed to start");
783 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
784 continue;
785 }
786 } catch (RemoteException e) {
787 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700788 if (job.getNumFailures() > 0) {
789 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700790 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700791 if (job.hasIdleConstraint()) {
792 idleCount++;
793 }
794 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
795 connectivityCount++;
796 }
797 if (job.hasChargingConstraint()) {
798 chargingCount++;
799 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 if (runnableJobs == null) {
801 runnableJobs = new ArrayList<>();
802 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700803 runnableJobs.add(job);
804 } else if (isReadyToBeCancelledLocked(job)) {
805 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700806 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700807 }
808 if (backoffCount > 0 ||
809 idleCount >= MIN_IDLE_COUNT ||
810 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
811 chargingCount >= MIN_CHARGING_COUNT ||
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700812 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700813 if (DEBUG) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700814 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
Christopher Tate7060b042014-06-09 19:50:00 -0700815 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700816 for (int i=0; i<runnableJobs.size(); i++) {
817 mPendingJobs.add(runnableJobs.get(i));
818 }
819 } else {
820 if (DEBUG) {
821 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
822 }
823 }
824 if (DEBUG) {
825 Slog.d(TAG, "idle=" + idleCount + " connectivity=" +
826 connectivityCount + " charging=" + chargingCount + " tot=" +
827 runnableJobs.size());
Christopher Tate7060b042014-06-09 19:50:00 -0700828 }
829 }
830
831 /**
832 * Criteria for moving a job into the pending queue:
833 * - It's ready.
834 * - It's not pending.
835 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700836 * - The user that requested the job is running.
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700837 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -0700838 */
839 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700840 final boolean jobReady = job.isReady();
841 final boolean jobPending = mPendingJobs.contains(job);
842 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700843
844 final int userId = job.getUserId();
845 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
846 final boolean componentPresent;
847 try {
848 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700849 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700850 userId) != null);
851 } catch (RemoteException e) {
852 throw e.rethrowAsRuntimeException();
853 }
854
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700855 if (DEBUG) {
856 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
857 + " ready=" + jobReady + " pending=" + jobPending
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700858 + " active=" + jobActive + " userStarted=" + userStarted
859 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700860 }
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700861 return userStarted && componentPresent && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700862 }
863
864 /**
865 * Criteria for cancelling an active job:
866 * - It's not ready
867 * - It's running on a JSC.
868 */
869 private boolean isReadyToBeCancelledLocked(JobStatus job) {
870 return !job.isReady() && isCurrentlyActiveLocked(job);
871 }
872
873 /**
874 * Reconcile jobs in the pending queue against available execution contexts.
875 * A controller can force a job into the pending queue even if it's already running, but
876 * here is where we decide whether to actually execute it.
877 */
878 private void maybeRunPendingJobsH() {
879 synchronized (mJobs) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700880 if (mDeviceIdleMode) {
881 // If device is idle, we will not schedule jobs to run.
882 return;
883 }
Christopher Tate7060b042014-06-09 19:50:00 -0700884 Iterator<JobStatus> it = mPendingJobs.iterator();
Matthew Williams75fc5252014-09-02 16:17:53 -0700885 if (DEBUG) {
886 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
887 }
Christopher Tate7060b042014-06-09 19:50:00 -0700888 while (it.hasNext()) {
889 JobStatus nextPending = it.next();
890 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700891 for (int i=0; i<mActiveServices.size(); i++) {
892 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700893 final JobStatus running = jsc.getRunningJob();
894 if (running != null && running.matches(nextPending.getUid(),
895 nextPending.getJobId())) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700896 // Already running this job for this uId, skip.
Christopher Tate7060b042014-06-09 19:50:00 -0700897 availableContext = null;
898 break;
899 }
900 if (jsc.isAvailable()) {
901 availableContext = jsc;
902 }
903 }
904 if (availableContext != null) {
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800905 if (DEBUG) {
906 Slog.d(TAG, "About to run job "
907 + nextPending.getJob().getService().toString());
908 }
Christopher Tate7060b042014-06-09 19:50:00 -0700909 if (!availableContext.executeRunnableJob(nextPending)) {
910 if (DEBUG) {
911 Slog.d(TAG, "Error executing " + nextPending);
912 }
913 mJobs.remove(nextPending);
914 }
915 it.remove();
916 }
917 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800918 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700919 }
920 }
921 }
922
923 /**
924 * Binder stub trampoline implementation
925 */
926 final class JobSchedulerStub extends IJobScheduler.Stub {
927 /** Cache determination of whether a given app can persist jobs
928 * key is uid of the calling app; value is undetermined/true/false
929 */
930 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
931
932 // Enforce that only the app itself (or shared uid participant) can schedule a
933 // job that runs one of the app's services, as well as verifying that the
934 // named service properly requires the BIND_JOB_SERVICE permission
935 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700936 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700937 final ComponentName service = job.getService();
938 try {
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700939 ServiceInfo si = pm.getServiceInfo(service,
940 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -0700941 if (si == null) {
942 throw new IllegalArgumentException("No such service " + service);
943 }
Christopher Tate7060b042014-06-09 19:50:00 -0700944 if (si.applicationInfo.uid != uid) {
945 throw new IllegalArgumentException("uid " + uid +
946 " cannot schedule job in " + service.getPackageName());
947 }
948 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
949 throw new IllegalArgumentException("Scheduled service " + service
950 + " does not require android.permission.BIND_JOB_SERVICE permission");
951 }
Christopher Tate5568f542014-06-18 13:53:31 -0700952 } catch (RemoteException e) {
953 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700954 }
955 }
956
957 private boolean canPersistJobs(int pid, int uid) {
958 // If we get this far we're good to go; all we need to do now is check
959 // whether the app is allowed to persist its scheduled work.
960 final boolean canPersist;
961 synchronized (mPersistCache) {
962 Boolean cached = mPersistCache.get(uid);
963 if (cached != null) {
964 canPersist = cached.booleanValue();
965 } else {
966 // Persisting jobs is tantamount to running at boot, so we permit
967 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
968 // permission
969 int result = getContext().checkPermission(
970 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
971 canPersist = (result == PackageManager.PERMISSION_GRANTED);
972 mPersistCache.put(uid, canPersist);
973 }
974 }
975 return canPersist;
976 }
977
978 // IJobScheduler implementation
979 @Override
980 public int schedule(JobInfo job) throws RemoteException {
981 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700982 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -0700983 }
984 final int pid = Binder.getCallingPid();
985 final int uid = Binder.getCallingUid();
986
987 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700988 if (job.isPersisted()) {
989 if (!canPersistJobs(pid, uid)) {
990 throw new IllegalArgumentException("Error: requested job be persisted without"
991 + " holding RECEIVE_BOOT_COMPLETED permission.");
992 }
993 }
Christopher Tate7060b042014-06-09 19:50:00 -0700994
995 long ident = Binder.clearCallingIdentity();
996 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700997 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700998 } finally {
999 Binder.restoreCallingIdentity(ident);
1000 }
1001 }
1002
1003 @Override
1004 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1005 final int uid = Binder.getCallingUid();
1006
1007 long ident = Binder.clearCallingIdentity();
1008 try {
1009 return JobSchedulerService.this.getPendingJobs(uid);
1010 } finally {
1011 Binder.restoreCallingIdentity(ident);
1012 }
1013 }
1014
1015 @Override
1016 public void cancelAll() throws RemoteException {
1017 final int uid = Binder.getCallingUid();
1018
1019 long ident = Binder.clearCallingIdentity();
1020 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001021 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001022 } finally {
1023 Binder.restoreCallingIdentity(ident);
1024 }
1025 }
1026
1027 @Override
1028 public void cancel(int jobId) throws RemoteException {
1029 final int uid = Binder.getCallingUid();
1030
1031 long ident = Binder.clearCallingIdentity();
1032 try {
1033 JobSchedulerService.this.cancelJob(uid, jobId);
1034 } finally {
1035 Binder.restoreCallingIdentity(ident);
1036 }
1037 }
1038
1039 /**
1040 * "dumpsys" infrastructure
1041 */
1042 @Override
1043 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1044 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1045
1046 long identityToken = Binder.clearCallingIdentity();
1047 try {
1048 JobSchedulerService.this.dumpInternal(pw);
1049 } finally {
1050 Binder.restoreCallingIdentity(identityToken);
1051 }
1052 }
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001053 }
Christopher Tate7060b042014-06-09 19:50:00 -07001054
1055 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001056 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -07001057 synchronized (mJobs) {
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001058 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Christopher Tate7060b042014-06-09 19:50:00 -07001059 pw.println("Registered jobs:");
1060 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001061 ArraySet<JobStatus> jobs = mJobs.getJobs();
1062 for (int i=0; i<jobs.size(); i++) {
1063 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001064 job.dump(pw, " ");
1065 }
1066 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001067 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001068 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001069 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001070 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001071 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001072 }
1073 pw.println();
Christopher Tatef973a7b2014-08-29 12:54:08 -07001074 pw.println("Pending:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001075 for (int i=0; i<mPendingJobs.size(); i++) {
1076 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -07001077 }
1078 pw.println();
1079 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001080 for (int i=0; i<mActiveServices.size(); i++) {
1081 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001082 if (jsc.isAvailable()) {
1083 continue;
1084 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001085 final long timeout = jsc.getTimeoutElapsed();
1086 pw.print("Running for: ");
1087 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1088 pw.print("s timeout=");
1089 pw.print(timeout);
1090 pw.print(" fromnow=");
1091 pw.println(timeout-now);
1092 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -07001093 }
1094 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001095 pw.println();
1096 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001097 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001098 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001099 }
1100 pw.println();
1101 }
1102}