blob: c5e6e7c366c3f616e34bd4baaf5185ee36ecb4df [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) {
164 Slog.d(TAG, "Receieved: " + intent.getAction());
165 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700166 // If this is an outright uninstall rather than the first half of an
167 // app update sequence, cancel the jobs associated with the app.
168 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
169 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
170 if (DEBUG) {
171 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
172 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700173 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700174 }
Christopher Tate7060b042014-06-09 19:50:00 -0700175 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
176 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
177 if (DEBUG) {
178 Slog.d(TAG, "Removing jobs for user: " + userId);
179 }
180 cancelJobsForUser(userId);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700181 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())
182 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
183 updateIdleMode(mPowerManager != null
184 ? (mPowerManager.isDeviceIdleMode()
185 || mPowerManager.isLightDeviceIdleMode())
186 : false);
Christopher Tate7060b042014-06-09 19:50:00 -0700187 }
188 }
189 };
190
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700191 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
192 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
193 }
194
195 @Override public void onUidGone(int uid) throws RemoteException {
196 }
197
198 @Override public void onUidActive(int uid) throws RemoteException {
199 }
200
201 @Override public void onUidIdle(int uid) throws RemoteException {
202 cancelJobsForUid(uid, false);
203 }
204 };
205
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700206 @Override
207 public void onStartUser(int userHandle) {
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700208 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
209 // Let's kick any outstanding jobs for this user.
210 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
211 }
212
213 @Override
214 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700215 // Let's kick any outstanding jobs for this user.
216 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
217 }
218
219 @Override
220 public void onStopUser(int userHandle) {
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700221 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700222 }
223
Christopher Tate7060b042014-06-09 19:50:00 -0700224 /**
225 * Entry point from client to schedule the provided job.
226 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
227 * @param job JobInfo object containing execution parameters
228 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700229 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
230 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700231 public int schedule(JobInfo job, int uId) {
232 JobStatus jobStatus = new JobStatus(job, uId);
Christopher Tate7060b042014-06-09 19:50:00 -0700233 cancelJob(uId, job.getId());
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700234 try {
235 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
236 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
237 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
238 + " -- package not allowed to start");
239 return JobScheduler.RESULT_FAILURE;
240 }
241 } catch (RemoteException e) {
242 }
Christopher Tate7060b042014-06-09 19:50:00 -0700243 startTrackingJob(jobStatus);
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700244 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700245 return JobScheduler.RESULT_SUCCESS;
246 }
247
248 public List<JobInfo> getPendingJobs(int uid) {
249 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
250 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700251 ArraySet<JobStatus> jobs = mJobs.getJobs();
252 for (int i=0; i<jobs.size(); i++) {
253 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700254 if (job.getUid() == uid) {
255 outList.add(job.getJob());
256 }
257 }
258 }
259 return outList;
260 }
261
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700262 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700263 List<JobStatus> jobsForUser;
Christopher Tate7060b042014-06-09 19:50:00 -0700264 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700265 jobsForUser = mJobs.getJobsByUser(userHandle);
266 }
267 for (int i=0; i<jobsForUser.size(); i++) {
268 JobStatus toRemove = jobsForUser.get(i);
269 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700270 }
271 }
272
273 /**
274 * Entry point from client to cancel all jobs originating from their uid.
275 * This will remove the job from the master list, and cancel the job if it was staged for
276 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700277 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700278 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
279 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700280 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700281 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700282 List<JobStatus> jobsForUid;
Christopher Tate7060b042014-06-09 19:50:00 -0700283 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700284 jobsForUid = mJobs.getJobsByUid(uid);
285 }
286 for (int i=0; i<jobsForUid.size(); i++) {
287 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700288 if (!forceAll) {
289 String packageName = toRemove.getServiceComponent().getPackageName();
290 try {
291 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
292 != ActivityManager.APP_START_MODE_DISABLED) {
293 continue;
294 }
295 } catch (RemoteException e) {
296 }
297 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700298 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700299 }
300 }
301
302 /**
303 * Entry point from client to cancel the job corresponding to the jobId provided.
304 * This will remove the job from the master list, and cancel the job if it was staged for
305 * execution or being executed.
306 * @param uid Uid of the calling client.
307 * @param jobId Id of the job, provided at schedule-time.
308 */
309 public void cancelJob(int uid, int jobId) {
310 JobStatus toCancel;
311 synchronized (mJobs) {
312 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700313 }
314 if (toCancel != null) {
315 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700316 }
317 }
318
Matthew Williams48a30db2014-09-23 13:39:36 -0700319 private void cancelJobImpl(JobStatus cancelled) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700320 if (DEBUG) {
321 Slog.d(TAG, "Cancelling: " + cancelled);
322 }
Christopher Tate7060b042014-06-09 19:50:00 -0700323 stopTrackingJob(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700324 synchronized (mJobs) {
325 // Remove from pending queue.
326 mPendingJobs.remove(cancelled);
327 // Cancel if running.
328 stopJobOnServiceContextLocked(cancelled);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800329 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700330 }
Christopher Tate7060b042014-06-09 19:50:00 -0700331 }
332
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700333 void updateIdleMode(boolean enabled) {
334 boolean changed = false;
335 boolean rocking;
336 synchronized (mJobs) {
337 if (mDeviceIdleMode != enabled) {
338 changed = true;
339 }
340 rocking = mReadyToRock;
341 }
342 if (changed) {
343 if (rocking) {
344 for (int i=0; i<mControllers.size(); i++) {
345 mControllers.get(i).deviceIdleModeChanged(enabled);
346 }
347 }
348 synchronized (mJobs) {
349 mDeviceIdleMode = enabled;
350 if (enabled) {
351 // When becoming idle, make sure no jobs are actively running.
352 for (int i=0; i<mActiveServices.size(); i++) {
353 JobServiceContext jsc = mActiveServices.get(i);
354 final JobStatus executing = jsc.getRunningJob();
355 if (executing != null) {
356 jsc.cancelExecutingJob();
357 }
358 }
359 } else {
360 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800361 if (rocking) {
362 if (mLocalDeviceIdleController != null) {
363 if (!mReportedActive) {
364 mReportedActive = true;
365 mLocalDeviceIdleController.setJobsActive(true);
366 }
367 }
368 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700369 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
370 }
371 }
372 }
373 }
374
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800375 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000376 // active is true if pending queue contains jobs OR some job is running.
377 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800378 if (mPendingJobs.size() <= 0) {
379 for (int i=0; i<mActiveServices.size(); i++) {
380 JobServiceContext jsc = mActiveServices.get(i);
381 if (!jsc.isAvailable()) {
382 active = true;
383 break;
384 }
385 }
386 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000387
388 if (mReportedActive != active) {
389 mReportedActive = active;
390 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800391 mLocalDeviceIdleController.setJobsActive(active);
392 }
393 }
394 }
395
Christopher Tate7060b042014-06-09 19:50:00 -0700396 /**
397 * Initializes the system service.
398 * <p>
399 * Subclasses must define a single argument constructor that accepts the context
400 * and passes it to super.
401 * </p>
402 *
403 * @param context The system server context.
404 */
405 public JobSchedulerService(Context context) {
406 super(context);
407 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700408 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700409 mControllers.add(ConnectivityController.get(this));
410 mControllers.add(TimeController.get(this));
411 mControllers.add(IdleController.get(this));
412 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800413 mControllers.add(AppIdleController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700414
415 mHandler = new JobHandler(context.getMainLooper());
416 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700417 mJobs = JobStore.initAndGet(this);
418 }
419
420 @Override
421 public void onStart() {
422 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
423 }
424
425 @Override
426 public void onBootPhase(int phase) {
427 if (PHASE_SYSTEM_SERVICES_READY == phase) {
428 // Register br for package removals and user removals.
429 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
430 filter.addDataScheme("package");
431 getContext().registerReceiverAsUser(
432 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
433 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700434 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700435 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700436 getContext().registerReceiverAsUser(
437 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700438 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700439 try {
440 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
441 ActivityManager.UID_OBSERVER_IDLE);
442 } catch (RemoteException e) {
443 // ignored; both services live in system_server
444 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700445 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
446 synchronized (mJobs) {
447 // Let's go!
448 mReadyToRock = true;
449 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
450 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800451 mLocalDeviceIdleController
452 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700453 // Create the "runners".
454 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
455 mActiveServices.add(
456 new JobServiceContext(this, mBatteryStats,
457 getContext().getMainLooper()));
458 }
459 // Attach jobs to their controllers.
460 ArraySet<JobStatus> jobs = mJobs.getJobs();
461 for (int i=0; i<jobs.size(); i++) {
462 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700463 for (int controller=0; controller<mControllers.size(); controller++) {
Dianne Hackborn2bf51f42015-03-24 14:17:12 -0700464 mControllers.get(controller).deviceIdleModeChanged(mDeviceIdleMode);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700465 mControllers.get(controller).maybeStartTrackingJob(job);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700466 }
467 }
468 // GO GO GO!
469 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
470 }
Christopher Tate7060b042014-06-09 19:50:00 -0700471 }
472 }
473
474 /**
475 * Called when we have a job status object that we need to insert in our
476 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
477 * about.
478 */
479 private void startTrackingJob(JobStatus jobStatus) {
480 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700481 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700482 synchronized (mJobs) {
483 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700484 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700485 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700486 if (rocking) {
487 for (int i=0; i<mControllers.size(); i++) {
488 StateController controller = mControllers.get(i);
489 if (update) {
490 controller.maybeStopTrackingJob(jobStatus);
491 }
492 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700493 }
Christopher Tate7060b042014-06-09 19:50:00 -0700494 }
495 }
496
497 /**
498 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
499 * object removed.
500 */
501 private boolean stopTrackingJob(JobStatus jobStatus) {
502 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700503 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700504 synchronized (mJobs) {
505 // Remove from store as well as controllers.
506 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700507 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700508 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700509 if (removed && rocking) {
510 for (int i=0; i<mControllers.size(); i++) {
511 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700512 controller.maybeStopTrackingJob(jobStatus);
513 }
514 }
515 return removed;
516 }
517
518 private boolean stopJobOnServiceContextLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700519 for (int i=0; i<mActiveServices.size(); i++) {
520 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700521 final JobStatus executing = jsc.getRunningJob();
522 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
523 jsc.cancelExecutingJob();
524 return true;
525 }
526 }
527 return false;
528 }
529
530 /**
531 * @param job JobStatus we are querying against.
532 * @return Whether or not the job represented by the status object is currently being run or
533 * is pending.
534 */
535 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700536 for (int i=0; i<mActiveServices.size(); i++) {
537 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700538 final JobStatus running = serviceContext.getRunningJob();
539 if (running != null && running.matches(job.getUid(), job.getJobId())) {
540 return true;
541 }
542 }
543 return false;
544 }
545
546 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700547 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
548 * specify an override deadline on a failed job (the failed job will run even though it's not
549 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
550 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
551 *
Christopher Tate7060b042014-06-09 19:50:00 -0700552 * @param failureToReschedule Provided job status that we will reschedule.
553 * @return A newly instantiated JobStatus with the same constraints as the last job except
554 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700555 *
556 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700557 */
558 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
559 final long elapsedNowMillis = SystemClock.elapsedRealtime();
560 final JobInfo job = failureToReschedule.getJob();
561
562 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700563 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
564 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700565
566 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700567 case JobInfo.BACKOFF_POLICY_LINEAR:
568 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700569 break;
570 default:
571 if (DEBUG) {
572 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
573 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700574 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
575 delayMillis =
576 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700577 break;
578 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700579 delayMillis =
580 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
581 return new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
582 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Christopher Tate7060b042014-06-09 19:50:00 -0700583 }
584
585 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700586 * Called after a periodic has executed so we can reschedule it. We take the last execution
587 * time of the job to be the time of completion (i.e. the time at which this function is
588 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700589 * This could be inaccurate b/c the job can run for as long as
590 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
591 * to underscheduling at least, rather than if we had taken the last execution time to be the
592 * start of the execution.
593 * @return A new job representing the execution criteria for this instantiation of the
594 * recurring job.
595 */
596 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
597 final long elapsedNow = SystemClock.elapsedRealtime();
598 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700599 long runEarly = 0L;
600
601 // If this periodic was rescheduled it won't have a deadline.
602 if (periodicToReschedule.hasDeadlineConstraint()) {
603 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
604 }
Christopher Tate7060b042014-06-09 19:50:00 -0700605 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
606 long period = periodicToReschedule.getJob().getIntervalMillis();
607 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
608
609 if (DEBUG) {
610 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
611 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
612 }
613 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
614 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
615 }
616
617 // JobCompletedListener implementations.
618
619 /**
620 * A job just finished executing. We fetch the
621 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
622 * whether we want to reschedule we readd it to the controllers.
623 * @param jobStatus Completed job.
624 * @param needsReschedule Whether the implementing class should reschedule this job.
625 */
626 @Override
627 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
628 if (DEBUG) {
629 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
630 }
631 if (!stopTrackingJob(jobStatus)) {
632 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700633 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700634 }
635 return;
636 }
637 if (needsReschedule) {
638 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
639 startTrackingJob(rescheduled);
640 } else if (jobStatus.getJob().isPeriodic()) {
641 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
642 startTrackingJob(rescheduledPeriodic);
643 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000644 reportActive();
645 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700646 }
647
648 // StateChangedListener implementations.
649
650 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700651 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
652 * some controller's state has changed, so as to run through the list of jobs and start/stop
653 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700654 */
655 @Override
656 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700657 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700658 }
659
660 @Override
661 public void onRunJobNow(JobStatus jobStatus) {
662 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
663 }
664
Christopher Tate7060b042014-06-09 19:50:00 -0700665 private class JobHandler extends Handler {
666
667 public JobHandler(Looper looper) {
668 super(looper);
669 }
670
671 @Override
672 public void handleMessage(Message message) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700673 synchronized (mJobs) {
674 if (!mReadyToRock) {
675 return;
676 }
677 }
Christopher Tate7060b042014-06-09 19:50:00 -0700678 switch (message.what) {
679 case MSG_JOB_EXPIRED:
680 synchronized (mJobs) {
681 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700682 // runNow can be null, which is a controller's way of indicating that its
683 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700684 if (runNow != null && !mPendingJobs.contains(runNow)
685 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700686 mPendingJobs.add(runNow);
687 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700688 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700689 }
Christopher Tate7060b042014-06-09 19:50:00 -0700690 break;
691 case MSG_CHECK_JOB:
Matthew Williams48a30db2014-09-23 13:39:36 -0700692 synchronized (mJobs) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000693 if (mReportedActive) {
694 // if jobs are currently being run, queue all ready jobs for execution.
695 queueReadyJobsForExecutionLockedH();
696 } else {
697 // Check the list of jobs and run some of them if we feel inclined.
698 maybeQueueReadyJobsForExecutionLockedH();
699 }
700 }
701 break;
702 case MSG_CHECK_JOB_GREEDY:
703 synchronized (mJobs) {
704 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700705 }
Christopher Tate7060b042014-06-09 19:50:00 -0700706 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700707 case MSG_STOP_JOB:
708 cancelJobImpl((JobStatus)message.obj);
709 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700710 }
711 maybeRunPendingJobsH();
712 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
713 removeMessages(MSG_CHECK_JOB);
714 }
715
716 /**
717 * Run through list of jobs and execute all possible - at least one is expired so we do
718 * as many as we can.
719 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700720 private void queueReadyJobsForExecutionLockedH() {
721 ArraySet<JobStatus> jobs = mJobs.getJobs();
722 if (DEBUG) {
723 Slog.d(TAG, "queuing all ready jobs for execution:");
724 }
725 for (int i=0; i<jobs.size(); i++) {
726 JobStatus job = jobs.valueAt(i);
727 if (isReadyToBeExecutedLocked(job)) {
728 if (DEBUG) {
729 Slog.d(TAG, " queued " + job.toShortString());
Christopher Tate7060b042014-06-09 19:50:00 -0700730 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700731 mPendingJobs.add(job);
732 } else if (isReadyToBeCancelledLocked(job)) {
733 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700734 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700735 }
736 if (DEBUG) {
737 final int queuedJobs = mPendingJobs.size();
738 if (queuedJobs == 0) {
739 Slog.d(TAG, "No jobs pending.");
740 } else {
741 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700742 }
Christopher Tate7060b042014-06-09 19:50:00 -0700743 }
744 }
745
746 /**
747 * The state of at least one job has changed. Here is where we could enforce various
748 * policies on when we want to execute jobs.
749 * Right now the policy is such:
750 * If >1 of the ready jobs is idle mode we send all of them off
751 * if more than 2 network connectivity jobs are ready we send them all off.
752 * If more than 4 jobs total are ready we send them all off.
753 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
754 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700755 private void maybeQueueReadyJobsForExecutionLockedH() {
756 int chargingCount = 0;
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700757 int idleCount = 0;
Matthew Williams48a30db2014-09-23 13:39:36 -0700758 int backoffCount = 0;
759 int connectivityCount = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700760 List<JobStatus> runnableJobs = null;
Matthew Williams48a30db2014-09-23 13:39:36 -0700761 ArraySet<JobStatus> jobs = mJobs.getJobs();
762 for (int i=0; i<jobs.size(); i++) {
763 JobStatus job = jobs.valueAt(i);
764 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700765 try {
766 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
767 job.getJob().getService().getPackageName())
768 == ActivityManager.APP_START_MODE_DISABLED) {
769 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
770 + job.getJob().toString() + " -- package not allowed to start");
771 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
772 continue;
773 }
774 } catch (RemoteException e) {
775 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700776 if (job.getNumFailures() > 0) {
777 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700778 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700779 if (job.hasIdleConstraint()) {
780 idleCount++;
781 }
782 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
783 connectivityCount++;
784 }
785 if (job.hasChargingConstraint()) {
786 chargingCount++;
787 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700788 if (runnableJobs == null) {
789 runnableJobs = new ArrayList<>();
790 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700791 runnableJobs.add(job);
792 } else if (isReadyToBeCancelledLocked(job)) {
793 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700794 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700795 }
796 if (backoffCount > 0 ||
797 idleCount >= MIN_IDLE_COUNT ||
798 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
799 chargingCount >= MIN_CHARGING_COUNT ||
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700801 if (DEBUG) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700802 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
Christopher Tate7060b042014-06-09 19:50:00 -0700803 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700804 for (int i=0; i<runnableJobs.size(); i++) {
805 mPendingJobs.add(runnableJobs.get(i));
806 }
807 } else {
808 if (DEBUG) {
809 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
810 }
811 }
812 if (DEBUG) {
813 Slog.d(TAG, "idle=" + idleCount + " connectivity=" +
814 connectivityCount + " charging=" + chargingCount + " tot=" +
815 runnableJobs.size());
Christopher Tate7060b042014-06-09 19:50:00 -0700816 }
817 }
818
819 /**
820 * Criteria for moving a job into the pending queue:
821 * - It's ready.
822 * - It's not pending.
823 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700824 * - The user that requested the job is running.
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700825 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -0700826 */
827 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700828 final boolean jobReady = job.isReady();
829 final boolean jobPending = mPendingJobs.contains(job);
830 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700831
832 final int userId = job.getUserId();
833 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
834 final boolean componentPresent;
835 try {
836 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
837 job.getServiceComponent(), PackageManager.MATCH_ENCRYPTION_DEFAULT,
838 userId) != null);
839 } catch (RemoteException e) {
840 throw e.rethrowAsRuntimeException();
841 }
842
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700843 if (DEBUG) {
844 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
845 + " ready=" + jobReady + " pending=" + jobPending
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700846 + " active=" + jobActive + " userStarted=" + userStarted
847 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700848 }
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700849 return userStarted && componentPresent && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700850 }
851
852 /**
853 * Criteria for cancelling an active job:
854 * - It's not ready
855 * - It's running on a JSC.
856 */
857 private boolean isReadyToBeCancelledLocked(JobStatus job) {
858 return !job.isReady() && isCurrentlyActiveLocked(job);
859 }
860
861 /**
862 * Reconcile jobs in the pending queue against available execution contexts.
863 * A controller can force a job into the pending queue even if it's already running, but
864 * here is where we decide whether to actually execute it.
865 */
866 private void maybeRunPendingJobsH() {
867 synchronized (mJobs) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700868 if (mDeviceIdleMode) {
869 // If device is idle, we will not schedule jobs to run.
870 return;
871 }
Christopher Tate7060b042014-06-09 19:50:00 -0700872 Iterator<JobStatus> it = mPendingJobs.iterator();
Matthew Williams75fc5252014-09-02 16:17:53 -0700873 if (DEBUG) {
874 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
875 }
Christopher Tate7060b042014-06-09 19:50:00 -0700876 while (it.hasNext()) {
877 JobStatus nextPending = it.next();
878 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700879 for (int i=0; i<mActiveServices.size(); i++) {
880 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700881 final JobStatus running = jsc.getRunningJob();
882 if (running != null && running.matches(nextPending.getUid(),
883 nextPending.getJobId())) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700884 // Already running this job for this uId, skip.
Christopher Tate7060b042014-06-09 19:50:00 -0700885 availableContext = null;
886 break;
887 }
888 if (jsc.isAvailable()) {
889 availableContext = jsc;
890 }
891 }
892 if (availableContext != null) {
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800893 if (DEBUG) {
894 Slog.d(TAG, "About to run job "
895 + nextPending.getJob().getService().toString());
896 }
Christopher Tate7060b042014-06-09 19:50:00 -0700897 if (!availableContext.executeRunnableJob(nextPending)) {
898 if (DEBUG) {
899 Slog.d(TAG, "Error executing " + nextPending);
900 }
901 mJobs.remove(nextPending);
902 }
903 it.remove();
904 }
905 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800906 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700907 }
908 }
909 }
910
911 /**
912 * Binder stub trampoline implementation
913 */
914 final class JobSchedulerStub extends IJobScheduler.Stub {
915 /** Cache determination of whether a given app can persist jobs
916 * key is uid of the calling app; value is undetermined/true/false
917 */
918 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
919
920 // Enforce that only the app itself (or shared uid participant) can schedule a
921 // job that runs one of the app's services, as well as verifying that the
922 // named service properly requires the BIND_JOB_SERVICE permission
923 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700924 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700925 final ComponentName service = job.getService();
926 try {
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700927 ServiceInfo si = pm.getServiceInfo(service, PackageManager.MATCH_ENCRYPTION_DEFAULT,
928 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -0700929 if (si == null) {
930 throw new IllegalArgumentException("No such service " + service);
931 }
Christopher Tate7060b042014-06-09 19:50:00 -0700932 if (si.applicationInfo.uid != uid) {
933 throw new IllegalArgumentException("uid " + uid +
934 " cannot schedule job in " + service.getPackageName());
935 }
936 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
937 throw new IllegalArgumentException("Scheduled service " + service
938 + " does not require android.permission.BIND_JOB_SERVICE permission");
939 }
Christopher Tate5568f542014-06-18 13:53:31 -0700940 } catch (RemoteException e) {
941 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700942 }
943 }
944
945 private boolean canPersistJobs(int pid, int uid) {
946 // If we get this far we're good to go; all we need to do now is check
947 // whether the app is allowed to persist its scheduled work.
948 final boolean canPersist;
949 synchronized (mPersistCache) {
950 Boolean cached = mPersistCache.get(uid);
951 if (cached != null) {
952 canPersist = cached.booleanValue();
953 } else {
954 // Persisting jobs is tantamount to running at boot, so we permit
955 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
956 // permission
957 int result = getContext().checkPermission(
958 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
959 canPersist = (result == PackageManager.PERMISSION_GRANTED);
960 mPersistCache.put(uid, canPersist);
961 }
962 }
963 return canPersist;
964 }
965
966 // IJobScheduler implementation
967 @Override
968 public int schedule(JobInfo job) throws RemoteException {
969 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700970 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -0700971 }
972 final int pid = Binder.getCallingPid();
973 final int uid = Binder.getCallingUid();
974
975 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700976 if (job.isPersisted()) {
977 if (!canPersistJobs(pid, uid)) {
978 throw new IllegalArgumentException("Error: requested job be persisted without"
979 + " holding RECEIVE_BOOT_COMPLETED permission.");
980 }
981 }
Christopher Tate7060b042014-06-09 19:50:00 -0700982
983 long ident = Binder.clearCallingIdentity();
984 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700985 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700986 } finally {
987 Binder.restoreCallingIdentity(ident);
988 }
989 }
990
991 @Override
992 public List<JobInfo> getAllPendingJobs() throws RemoteException {
993 final int uid = Binder.getCallingUid();
994
995 long ident = Binder.clearCallingIdentity();
996 try {
997 return JobSchedulerService.this.getPendingJobs(uid);
998 } finally {
999 Binder.restoreCallingIdentity(ident);
1000 }
1001 }
1002
1003 @Override
1004 public void cancelAll() throws RemoteException {
1005 final int uid = Binder.getCallingUid();
1006
1007 long ident = Binder.clearCallingIdentity();
1008 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001009 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001010 } finally {
1011 Binder.restoreCallingIdentity(ident);
1012 }
1013 }
1014
1015 @Override
1016 public void cancel(int jobId) throws RemoteException {
1017 final int uid = Binder.getCallingUid();
1018
1019 long ident = Binder.clearCallingIdentity();
1020 try {
1021 JobSchedulerService.this.cancelJob(uid, jobId);
1022 } finally {
1023 Binder.restoreCallingIdentity(ident);
1024 }
1025 }
1026
1027 /**
1028 * "dumpsys" infrastructure
1029 */
1030 @Override
1031 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1032 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1033
1034 long identityToken = Binder.clearCallingIdentity();
1035 try {
1036 JobSchedulerService.this.dumpInternal(pw);
1037 } finally {
1038 Binder.restoreCallingIdentity(identityToken);
1039 }
1040 }
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001041 }
Christopher Tate7060b042014-06-09 19:50:00 -07001042
1043 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001044 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -07001045 synchronized (mJobs) {
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001046 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Christopher Tate7060b042014-06-09 19:50:00 -07001047 pw.println("Registered jobs:");
1048 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001049 ArraySet<JobStatus> jobs = mJobs.getJobs();
1050 for (int i=0; i<jobs.size(); i++) {
1051 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001052 job.dump(pw, " ");
1053 }
1054 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001055 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001056 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001057 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001058 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001059 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001060 }
1061 pw.println();
Christopher Tatef973a7b2014-08-29 12:54:08 -07001062 pw.println("Pending:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001063 for (int i=0; i<mPendingJobs.size(); i++) {
1064 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -07001065 }
1066 pw.println();
1067 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001068 for (int i=0; i<mActiveServices.size(); i++) {
1069 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001070 if (jsc.isAvailable()) {
1071 continue;
1072 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001073 final long timeout = jsc.getTimeoutElapsed();
1074 pw.print("Running for: ");
1075 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1076 pw.print("s timeout=");
1077 pw.print(timeout);
1078 pw.print(" fromnow=");
1079 pw.println(timeout-now);
1080 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -07001081 }
1082 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001083 pw.println();
1084 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001085 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001086 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001087 }
1088 pw.println();
1089 }
1090}