blob: 4eabe3684e4f70bbccb5b8a50d7aeed41a3fda3e [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 }
Christopher Tate7060b042014-06-09 19:50:00 -0700616 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
617 long period = periodicToReschedule.getJob().getIntervalMillis();
618 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
619
620 if (DEBUG) {
621 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
622 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
623 }
624 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
625 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
626 }
627
628 // JobCompletedListener implementations.
629
630 /**
631 * A job just finished executing. We fetch the
632 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
633 * whether we want to reschedule we readd it to the controllers.
634 * @param jobStatus Completed job.
635 * @param needsReschedule Whether the implementing class should reschedule this job.
636 */
637 @Override
638 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
639 if (DEBUG) {
640 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
641 }
642 if (!stopTrackingJob(jobStatus)) {
643 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700644 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700645 }
646 return;
647 }
648 if (needsReschedule) {
649 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
650 startTrackingJob(rescheduled);
651 } else if (jobStatus.getJob().isPeriodic()) {
652 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
653 startTrackingJob(rescheduledPeriodic);
654 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000655 reportActive();
656 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700657 }
658
659 // StateChangedListener implementations.
660
661 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700662 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
663 * some controller's state has changed, so as to run through the list of jobs and start/stop
664 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700665 */
666 @Override
667 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700668 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700669 }
670
671 @Override
672 public void onRunJobNow(JobStatus jobStatus) {
673 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
674 }
675
Christopher Tate7060b042014-06-09 19:50:00 -0700676 private class JobHandler extends Handler {
677
678 public JobHandler(Looper looper) {
679 super(looper);
680 }
681
682 @Override
683 public void handleMessage(Message message) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700684 synchronized (mJobs) {
685 if (!mReadyToRock) {
686 return;
687 }
688 }
Christopher Tate7060b042014-06-09 19:50:00 -0700689 switch (message.what) {
690 case MSG_JOB_EXPIRED:
691 synchronized (mJobs) {
692 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700693 // runNow can be null, which is a controller's way of indicating that its
694 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700695 if (runNow != null && !mPendingJobs.contains(runNow)
696 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700697 mPendingJobs.add(runNow);
698 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700699 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700700 }
Christopher Tate7060b042014-06-09 19:50:00 -0700701 break;
702 case MSG_CHECK_JOB:
Matthew Williams48a30db2014-09-23 13:39:36 -0700703 synchronized (mJobs) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000704 if (mReportedActive) {
705 // if jobs are currently being run, queue all ready jobs for execution.
706 queueReadyJobsForExecutionLockedH();
707 } else {
708 // Check the list of jobs and run some of them if we feel inclined.
709 maybeQueueReadyJobsForExecutionLockedH();
710 }
711 }
712 break;
713 case MSG_CHECK_JOB_GREEDY:
714 synchronized (mJobs) {
715 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700716 }
Christopher Tate7060b042014-06-09 19:50:00 -0700717 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700718 case MSG_STOP_JOB:
719 cancelJobImpl((JobStatus)message.obj);
720 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700721 }
722 maybeRunPendingJobsH();
723 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
724 removeMessages(MSG_CHECK_JOB);
725 }
726
727 /**
728 * Run through list of jobs and execute all possible - at least one is expired so we do
729 * as many as we can.
730 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700731 private void queueReadyJobsForExecutionLockedH() {
732 ArraySet<JobStatus> jobs = mJobs.getJobs();
733 if (DEBUG) {
734 Slog.d(TAG, "queuing all ready jobs for execution:");
735 }
736 for (int i=0; i<jobs.size(); i++) {
737 JobStatus job = jobs.valueAt(i);
738 if (isReadyToBeExecutedLocked(job)) {
739 if (DEBUG) {
740 Slog.d(TAG, " queued " + job.toShortString());
Christopher Tate7060b042014-06-09 19:50:00 -0700741 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700742 mPendingJobs.add(job);
743 } else if (isReadyToBeCancelledLocked(job)) {
744 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700745 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700746 }
747 if (DEBUG) {
748 final int queuedJobs = mPendingJobs.size();
749 if (queuedJobs == 0) {
750 Slog.d(TAG, "No jobs pending.");
751 } else {
752 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700753 }
Christopher Tate7060b042014-06-09 19:50:00 -0700754 }
755 }
756
757 /**
758 * The state of at least one job has changed. Here is where we could enforce various
759 * policies on when we want to execute jobs.
760 * Right now the policy is such:
761 * If >1 of the ready jobs is idle mode we send all of them off
762 * if more than 2 network connectivity jobs are ready we send them all off.
763 * If more than 4 jobs total are ready we send them all off.
764 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
765 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700766 private void maybeQueueReadyJobsForExecutionLockedH() {
767 int chargingCount = 0;
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700768 int idleCount = 0;
Matthew Williams48a30db2014-09-23 13:39:36 -0700769 int backoffCount = 0;
770 int connectivityCount = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700771 List<JobStatus> runnableJobs = null;
Matthew Williams48a30db2014-09-23 13:39:36 -0700772 ArraySet<JobStatus> jobs = mJobs.getJobs();
773 for (int i=0; i<jobs.size(); i++) {
774 JobStatus job = jobs.valueAt(i);
775 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700776 try {
777 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
778 job.getJob().getService().getPackageName())
779 == ActivityManager.APP_START_MODE_DISABLED) {
780 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
781 + job.getJob().toString() + " -- package not allowed to start");
782 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
783 continue;
784 }
785 } catch (RemoteException e) {
786 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700787 if (job.getNumFailures() > 0) {
788 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700789 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700790 if (job.hasIdleConstraint()) {
791 idleCount++;
792 }
793 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
794 connectivityCount++;
795 }
796 if (job.hasChargingConstraint()) {
797 chargingCount++;
798 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700799 if (runnableJobs == null) {
800 runnableJobs = new ArrayList<>();
801 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700802 runnableJobs.add(job);
803 } else if (isReadyToBeCancelledLocked(job)) {
804 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700805 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700806 }
807 if (backoffCount > 0 ||
808 idleCount >= MIN_IDLE_COUNT ||
809 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
810 chargingCount >= MIN_CHARGING_COUNT ||
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700811 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700812 if (DEBUG) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700813 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
Christopher Tate7060b042014-06-09 19:50:00 -0700814 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700815 for (int i=0; i<runnableJobs.size(); i++) {
816 mPendingJobs.add(runnableJobs.get(i));
817 }
818 } else {
819 if (DEBUG) {
820 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
821 }
822 }
823 if (DEBUG) {
824 Slog.d(TAG, "idle=" + idleCount + " connectivity=" +
825 connectivityCount + " charging=" + chargingCount + " tot=" +
826 runnableJobs.size());
Christopher Tate7060b042014-06-09 19:50:00 -0700827 }
828 }
829
830 /**
831 * Criteria for moving a job into the pending queue:
832 * - It's ready.
833 * - It's not pending.
834 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700835 * - The user that requested the job is running.
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700836 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -0700837 */
838 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700839 final boolean jobReady = job.isReady();
840 final boolean jobPending = mPendingJobs.contains(job);
841 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700842
843 final int userId = job.getUserId();
844 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
845 final boolean componentPresent;
846 try {
847 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700848 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700849 userId) != null);
850 } catch (RemoteException e) {
851 throw e.rethrowAsRuntimeException();
852 }
853
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700854 if (DEBUG) {
855 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
856 + " ready=" + jobReady + " pending=" + jobPending
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700857 + " active=" + jobActive + " userStarted=" + userStarted
858 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700859 }
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700860 return userStarted && componentPresent && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700861 }
862
863 /**
864 * Criteria for cancelling an active job:
865 * - It's not ready
866 * - It's running on a JSC.
867 */
868 private boolean isReadyToBeCancelledLocked(JobStatus job) {
869 return !job.isReady() && isCurrentlyActiveLocked(job);
870 }
871
872 /**
873 * Reconcile jobs in the pending queue against available execution contexts.
874 * A controller can force a job into the pending queue even if it's already running, but
875 * here is where we decide whether to actually execute it.
876 */
877 private void maybeRunPendingJobsH() {
878 synchronized (mJobs) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700879 if (mDeviceIdleMode) {
880 // If device is idle, we will not schedule jobs to run.
881 return;
882 }
Christopher Tate7060b042014-06-09 19:50:00 -0700883 Iterator<JobStatus> it = mPendingJobs.iterator();
Matthew Williams75fc5252014-09-02 16:17:53 -0700884 if (DEBUG) {
885 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
886 }
Christopher Tate7060b042014-06-09 19:50:00 -0700887 while (it.hasNext()) {
888 JobStatus nextPending = it.next();
889 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700890 for (int i=0; i<mActiveServices.size(); i++) {
891 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700892 final JobStatus running = jsc.getRunningJob();
893 if (running != null && running.matches(nextPending.getUid(),
894 nextPending.getJobId())) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700895 // Already running this job for this uId, skip.
Christopher Tate7060b042014-06-09 19:50:00 -0700896 availableContext = null;
897 break;
898 }
899 if (jsc.isAvailable()) {
900 availableContext = jsc;
901 }
902 }
903 if (availableContext != null) {
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800904 if (DEBUG) {
905 Slog.d(TAG, "About to run job "
906 + nextPending.getJob().getService().toString());
907 }
Christopher Tate7060b042014-06-09 19:50:00 -0700908 if (!availableContext.executeRunnableJob(nextPending)) {
909 if (DEBUG) {
910 Slog.d(TAG, "Error executing " + nextPending);
911 }
912 mJobs.remove(nextPending);
913 }
914 it.remove();
915 }
916 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800917 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700918 }
919 }
920 }
921
922 /**
923 * Binder stub trampoline implementation
924 */
925 final class JobSchedulerStub extends IJobScheduler.Stub {
926 /** Cache determination of whether a given app can persist jobs
927 * key is uid of the calling app; value is undetermined/true/false
928 */
929 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
930
931 // Enforce that only the app itself (or shared uid participant) can schedule a
932 // job that runs one of the app's services, as well as verifying that the
933 // named service properly requires the BIND_JOB_SERVICE permission
934 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700935 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700936 final ComponentName service = job.getService();
937 try {
Jeff Sharkey2f3e3532015-12-21 14:16:43 -0700938 ServiceInfo si = pm.getServiceInfo(service,
939 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -0700940 if (si == null) {
941 throw new IllegalArgumentException("No such service " + service);
942 }
Christopher Tate7060b042014-06-09 19:50:00 -0700943 if (si.applicationInfo.uid != uid) {
944 throw new IllegalArgumentException("uid " + uid +
945 " cannot schedule job in " + service.getPackageName());
946 }
947 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
948 throw new IllegalArgumentException("Scheduled service " + service
949 + " does not require android.permission.BIND_JOB_SERVICE permission");
950 }
Christopher Tate5568f542014-06-18 13:53:31 -0700951 } catch (RemoteException e) {
952 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700953 }
954 }
955
956 private boolean canPersistJobs(int pid, int uid) {
957 // If we get this far we're good to go; all we need to do now is check
958 // whether the app is allowed to persist its scheduled work.
959 final boolean canPersist;
960 synchronized (mPersistCache) {
961 Boolean cached = mPersistCache.get(uid);
962 if (cached != null) {
963 canPersist = cached.booleanValue();
964 } else {
965 // Persisting jobs is tantamount to running at boot, so we permit
966 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
967 // permission
968 int result = getContext().checkPermission(
969 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
970 canPersist = (result == PackageManager.PERMISSION_GRANTED);
971 mPersistCache.put(uid, canPersist);
972 }
973 }
974 return canPersist;
975 }
976
977 // IJobScheduler implementation
978 @Override
979 public int schedule(JobInfo job) throws RemoteException {
980 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700981 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -0700982 }
983 final int pid = Binder.getCallingPid();
984 final int uid = Binder.getCallingUid();
985
986 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700987 if (job.isPersisted()) {
988 if (!canPersistJobs(pid, uid)) {
989 throw new IllegalArgumentException("Error: requested job be persisted without"
990 + " holding RECEIVE_BOOT_COMPLETED permission.");
991 }
992 }
Christopher Tate7060b042014-06-09 19:50:00 -0700993
994 long ident = Binder.clearCallingIdentity();
995 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700996 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700997 } finally {
998 Binder.restoreCallingIdentity(ident);
999 }
1000 }
1001
1002 @Override
1003 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1004 final int uid = Binder.getCallingUid();
1005
1006 long ident = Binder.clearCallingIdentity();
1007 try {
1008 return JobSchedulerService.this.getPendingJobs(uid);
1009 } finally {
1010 Binder.restoreCallingIdentity(ident);
1011 }
1012 }
1013
1014 @Override
1015 public void cancelAll() throws RemoteException {
1016 final int uid = Binder.getCallingUid();
1017
1018 long ident = Binder.clearCallingIdentity();
1019 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001020 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001021 } finally {
1022 Binder.restoreCallingIdentity(ident);
1023 }
1024 }
1025
1026 @Override
1027 public void cancel(int jobId) throws RemoteException {
1028 final int uid = Binder.getCallingUid();
1029
1030 long ident = Binder.clearCallingIdentity();
1031 try {
1032 JobSchedulerService.this.cancelJob(uid, jobId);
1033 } finally {
1034 Binder.restoreCallingIdentity(ident);
1035 }
1036 }
1037
1038 /**
1039 * "dumpsys" infrastructure
1040 */
1041 @Override
1042 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1043 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1044
1045 long identityToken = Binder.clearCallingIdentity();
1046 try {
1047 JobSchedulerService.this.dumpInternal(pw);
1048 } finally {
1049 Binder.restoreCallingIdentity(identityToken);
1050 }
1051 }
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001052 }
Christopher Tate7060b042014-06-09 19:50:00 -07001053
1054 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001055 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -07001056 synchronized (mJobs) {
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001057 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Christopher Tate7060b042014-06-09 19:50:00 -07001058 pw.println("Registered jobs:");
1059 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001060 ArraySet<JobStatus> jobs = mJobs.getJobs();
1061 for (int i=0; i<jobs.size(); i++) {
1062 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001063 job.dump(pw, " ");
1064 }
1065 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001066 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001067 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001068 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001069 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001070 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001071 }
1072 pw.println();
Christopher Tatef973a7b2014-08-29 12:54:08 -07001073 pw.println("Pending:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001074 for (int i=0; i<mPendingJobs.size(); i++) {
1075 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -07001076 }
1077 pw.println();
1078 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001079 for (int i=0; i<mActiveServices.size(); i++) {
1080 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001081 if (jsc.isAvailable()) {
1082 continue;
1083 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001084 final long timeout = jsc.getTimeoutElapsed();
1085 pw.print("Running for: ");
1086 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1087 pw.print("s timeout=");
1088 pw.print(timeout);
1089 pw.print(" fromnow=");
1090 pw.println(timeout-now);
1091 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -07001092 }
1093 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001094 pw.println();
1095 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001096 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001097 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001098 }
1099 pw.println();
1100 }
1101}