blob: f456bcd4af7f09c0bf2864a4a29c7defe778f629 [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
19import java.io.FileDescriptor;
20import java.io.PrintWriter;
21import java.util.ArrayList;
22import java.util.Iterator;
23import java.util.List;
24
Christopher Tate5568f542014-06-18 13:53:31 -070025import android.app.AppGlobals;
Christopher Tate7060b042014-06-09 19:50:00 -070026import android.app.job.JobInfo;
27import android.app.job.JobScheduler;
28import android.app.job.JobService;
29import android.app.job.IJobScheduler;
30import android.content.BroadcastReceiver;
31import android.content.ComponentName;
32import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070035import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070036import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070037import android.content.pm.ServiceInfo;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070038import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070039import android.os.Binder;
40import android.os.Handler;
41import android.os.Looper;
42import android.os.Message;
43import android.os.RemoteException;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070044import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070045import android.os.SystemClock;
46import android.os.UserHandle;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070047import android.util.ArraySet;
Christopher Tate7060b042014-06-09 19:50:00 -070048import android.util.Slog;
49import android.util.SparseArray;
50
Dianne Hackbornfdb19562014-07-11 16:03:36 -070051import com.android.internal.app.IBatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070052import com.android.server.job.controllers.BatteryController;
53import com.android.server.job.controllers.ConnectivityController;
54import com.android.server.job.controllers.IdleController;
55import com.android.server.job.controllers.JobStatus;
56import com.android.server.job.controllers.StateController;
57import com.android.server.job.controllers.TimeController;
58
Christopher Tate7060b042014-06-09 19:50:00 -070059/**
60 * Responsible for taking jobs representing work to be performed by a client app, and determining
61 * based on the criteria specified when that job should be run against the client application's
62 * endpoint.
63 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
64 * about constraints, or the state of active jobs. It receives callbacks from the various
65 * controllers and completed jobs and operates accordingly.
66 *
67 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
68 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
69 * @hide
70 */
71public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070072 implements StateChangedListener, JobCompletedListener {
Christopher Tate7060b042014-06-09 19:50:00 -070073 // TODO: Switch this off for final version.
74 static final boolean DEBUG = true;
75 /** The number of concurrent jobs we run at one time. */
76 private static final int MAX_JOB_CONTEXTS_COUNT = 3;
Matthew Williamsbe0c4172014-08-06 18:14:16 -070077 static final String TAG = "JobSchedulerService";
Christopher Tate7060b042014-06-09 19:50:00 -070078 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070079 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -070080
81 static final int MSG_JOB_EXPIRED = 0;
82 static final int MSG_CHECK_JOB = 1;
83
84 // Policy constants
85 /**
86 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
87 * early.
88 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070089 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -070090 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -070091 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
92 * early.
93 */
94 static final int MIN_CHARGING_COUNT = 1;
95 /**
Christopher Tate7060b042014-06-09 19:50:00 -070096 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
97 * things early.
98 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070099 static final int MIN_CONNECTIVITY_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700100 /**
101 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
102 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700103 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700104 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700105 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700106
107 /**
108 * Track Services that have currently active or pending jobs. The index is provided by
109 * {@link JobStatus#getServiceToken()}
110 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700111 final List<JobServiceContext> mActiveServices = new ArrayList<JobServiceContext>();
Christopher Tate7060b042014-06-09 19:50:00 -0700112 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700113 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700114 /**
115 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
116 * when ready to execute them.
117 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700118 final ArrayList<JobStatus> mPendingJobs = new ArrayList<JobStatus>();
Christopher Tate7060b042014-06-09 19:50:00 -0700119
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700120 final ArrayList<Integer> mStartedUsers = new ArrayList();
121
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700122 final JobHandler mHandler;
123 final JobSchedulerStub mJobSchedulerStub;
124
125 IBatteryStats mBatteryStats;
126
127 /**
128 * Set to true once we are allowed to run third party apps.
129 */
130 boolean mReadyToRock;
131
Christopher Tate7060b042014-06-09 19:50:00 -0700132 /**
133 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
134 * still clean up. On reinstall the package will have a new uid.
135 */
136 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
137 @Override
138 public void onReceive(Context context, Intent intent) {
139 Slog.d(TAG, "Receieved: " + intent.getAction());
140 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
141 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
142 if (DEBUG) {
143 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
144 }
145 cancelJobsForUid(uidRemoved);
146 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
147 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
148 if (DEBUG) {
149 Slog.d(TAG, "Removing jobs for user: " + userId);
150 }
151 cancelJobsForUser(userId);
152 }
153 }
154 };
155
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700156 @Override
157 public void onStartUser(int userHandle) {
158 mStartedUsers.add(userHandle);
159 // Let's kick any outstanding jobs for this user.
160 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
161 }
162
163 @Override
164 public void onStopUser(int userHandle) {
165 mStartedUsers.remove(Integer.valueOf(userHandle));
166 }
167
Christopher Tate7060b042014-06-09 19:50:00 -0700168 /**
169 * Entry point from client to schedule the provided job.
170 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
171 * @param job JobInfo object containing execution parameters
172 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700173 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
174 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700175 public int schedule(JobInfo job, int uId) {
176 JobStatus jobStatus = new JobStatus(job, uId);
Christopher Tate7060b042014-06-09 19:50:00 -0700177 cancelJob(uId, job.getId());
178 startTrackingJob(jobStatus);
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700179 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700180 return JobScheduler.RESULT_SUCCESS;
181 }
182
183 public List<JobInfo> getPendingJobs(int uid) {
184 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
185 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700186 ArraySet<JobStatus> jobs = mJobs.getJobs();
187 for (int i=0; i<jobs.size(); i++) {
188 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700189 if (job.getUid() == uid) {
190 outList.add(job.getJob());
191 }
192 }
193 }
194 return outList;
195 }
196
197 private void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700198 List<JobStatus> jobsForUser;
Christopher Tate7060b042014-06-09 19:50:00 -0700199 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700200 jobsForUser = mJobs.getJobsByUser(userHandle);
201 }
202 for (int i=0; i<jobsForUser.size(); i++) {
203 JobStatus toRemove = jobsForUser.get(i);
204 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700205 }
206 }
207
208 /**
209 * Entry point from client to cancel all jobs originating from their uid.
210 * This will remove the job from the master list, and cancel the job if it was staged for
211 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700212 * @param uid Uid to check against for removal of a job.
Christopher Tate7060b042014-06-09 19:50:00 -0700213 */
214 public void cancelJobsForUid(int uid) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700215 List<JobStatus> jobsForUid;
Christopher Tate7060b042014-06-09 19:50:00 -0700216 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700217 jobsForUid = mJobs.getJobsByUid(uid);
218 }
219 for (int i=0; i<jobsForUid.size(); i++) {
220 JobStatus toRemove = jobsForUid.get(i);
221 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700222 }
223 }
224
225 /**
226 * Entry point from client to cancel the job corresponding to the jobId provided.
227 * This will remove the job from the master list, and cancel the job if it was staged for
228 * execution or being executed.
229 * @param uid Uid of the calling client.
230 * @param jobId Id of the job, provided at schedule-time.
231 */
232 public void cancelJob(int uid, int jobId) {
233 JobStatus toCancel;
234 synchronized (mJobs) {
235 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700236 }
237 if (toCancel != null) {
238 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700239 }
240 }
241
Matthew Williams48a30db2014-09-23 13:39:36 -0700242 private void cancelJobImpl(JobStatus cancelled) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700243 if (DEBUG) {
244 Slog.d(TAG, "Cancelling: " + cancelled);
245 }
Christopher Tate7060b042014-06-09 19:50:00 -0700246 stopTrackingJob(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700247 synchronized (mJobs) {
248 // Remove from pending queue.
249 mPendingJobs.remove(cancelled);
250 // Cancel if running.
251 stopJobOnServiceContextLocked(cancelled);
252 }
Christopher Tate7060b042014-06-09 19:50:00 -0700253 }
254
255 /**
256 * Initializes the system service.
257 * <p>
258 * Subclasses must define a single argument constructor that accepts the context
259 * and passes it to super.
260 * </p>
261 *
262 * @param context The system server context.
263 */
264 public JobSchedulerService(Context context) {
265 super(context);
266 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700267 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700268 mControllers.add(ConnectivityController.get(this));
269 mControllers.add(TimeController.get(this));
270 mControllers.add(IdleController.get(this));
271 mControllers.add(BatteryController.get(this));
272
273 mHandler = new JobHandler(context.getMainLooper());
274 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700275 mJobs = JobStore.initAndGet(this);
276 }
277
278 @Override
279 public void onStart() {
280 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
281 }
282
283 @Override
284 public void onBootPhase(int phase) {
285 if (PHASE_SYSTEM_SERVICES_READY == phase) {
286 // Register br for package removals and user removals.
287 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
288 filter.addDataScheme("package");
289 getContext().registerReceiverAsUser(
290 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
291 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
292 getContext().registerReceiverAsUser(
293 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700294 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
295 synchronized (mJobs) {
296 // Let's go!
297 mReadyToRock = true;
298 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
299 BatteryStats.SERVICE_NAME));
300 // Create the "runners".
301 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
302 mActiveServices.add(
303 new JobServiceContext(this, mBatteryStats,
304 getContext().getMainLooper()));
305 }
306 // Attach jobs to their controllers.
307 ArraySet<JobStatus> jobs = mJobs.getJobs();
308 for (int i=0; i<jobs.size(); i++) {
309 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700310 for (int controller=0; controller<mControllers.size(); controller++) {
311 mControllers.get(controller).maybeStartTrackingJob(job);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700312 }
313 }
314 // GO GO GO!
315 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
316 }
Christopher Tate7060b042014-06-09 19:50:00 -0700317 }
318 }
319
320 /**
321 * Called when we have a job status object that we need to insert in our
322 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
323 * about.
324 */
325 private void startTrackingJob(JobStatus jobStatus) {
326 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700327 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700328 synchronized (mJobs) {
329 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700330 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700331 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700332 if (rocking) {
333 for (int i=0; i<mControllers.size(); i++) {
334 StateController controller = mControllers.get(i);
335 if (update) {
336 controller.maybeStopTrackingJob(jobStatus);
337 }
338 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700339 }
Christopher Tate7060b042014-06-09 19:50:00 -0700340 }
341 }
342
343 /**
344 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
345 * object removed.
346 */
347 private boolean stopTrackingJob(JobStatus jobStatus) {
348 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700349 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700350 synchronized (mJobs) {
351 // Remove from store as well as controllers.
352 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700353 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700354 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700355 if (removed && rocking) {
356 for (int i=0; i<mControllers.size(); i++) {
357 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700358 controller.maybeStopTrackingJob(jobStatus);
359 }
360 }
361 return removed;
362 }
363
364 private boolean stopJobOnServiceContextLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700365 for (int i=0; i<mActiveServices.size(); i++) {
366 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700367 final JobStatus executing = jsc.getRunningJob();
368 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
369 jsc.cancelExecutingJob();
370 return true;
371 }
372 }
373 return false;
374 }
375
376 /**
377 * @param job JobStatus we are querying against.
378 * @return Whether or not the job represented by the status object is currently being run or
379 * is pending.
380 */
381 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700382 for (int i=0; i<mActiveServices.size(); i++) {
383 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700384 final JobStatus running = serviceContext.getRunningJob();
385 if (running != null && running.matches(job.getUid(), job.getJobId())) {
386 return true;
387 }
388 }
389 return false;
390 }
391
392 /**
393 * A job is rescheduled with exponential back-off if the client requests this from their
394 * execution logic.
395 * A caveat is for idle-mode jobs, for which the idle-mode constraint will usurp the
396 * timeliness of the reschedule. For an idle-mode job, no deadline is given.
397 * @param failureToReschedule Provided job status that we will reschedule.
398 * @return A newly instantiated JobStatus with the same constraints as the last job except
399 * with adjusted timing constraints.
400 */
401 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
402 final long elapsedNowMillis = SystemClock.elapsedRealtime();
403 final JobInfo job = failureToReschedule.getJob();
404
405 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700406 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
407 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700408
409 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700410 case JobInfo.BACKOFF_POLICY_LINEAR:
411 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700412 break;
413 default:
414 if (DEBUG) {
415 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
416 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700417 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
418 delayMillis =
419 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700420 break;
421 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700422 delayMillis =
423 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
424 return new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
425 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Christopher Tate7060b042014-06-09 19:50:00 -0700426 }
427
428 /**
429 * Called after a periodic has executed so we can to re-add it. We take the last execution time
430 * of the job to be the time of completion (i.e. the time at which this function is called).
431 * This could be inaccurate b/c the job can run for as long as
432 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
433 * to underscheduling at least, rather than if we had taken the last execution time to be the
434 * start of the execution.
435 * @return A new job representing the execution criteria for this instantiation of the
436 * recurring job.
437 */
438 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
439 final long elapsedNow = SystemClock.elapsedRealtime();
440 // Compute how much of the period is remaining.
441 long runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0);
442 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
443 long period = periodicToReschedule.getJob().getIntervalMillis();
444 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
445
446 if (DEBUG) {
447 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
448 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
449 }
450 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
451 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
452 }
453
454 // JobCompletedListener implementations.
455
456 /**
457 * A job just finished executing. We fetch the
458 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
459 * whether we want to reschedule we readd it to the controllers.
460 * @param jobStatus Completed job.
461 * @param needsReschedule Whether the implementing class should reschedule this job.
462 */
463 @Override
464 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
465 if (DEBUG) {
466 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
467 }
468 if (!stopTrackingJob(jobStatus)) {
469 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700470 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700471 }
472 return;
473 }
474 if (needsReschedule) {
475 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
476 startTrackingJob(rescheduled);
477 } else if (jobStatus.getJob().isPeriodic()) {
478 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
479 startTrackingJob(rescheduledPeriodic);
480 }
481 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
482 }
483
484 // StateChangedListener implementations.
485
486 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700487 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
488 * some controller's state has changed, so as to run through the list of jobs and start/stop
489 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700490 */
491 @Override
492 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700493 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700494 }
495
496 @Override
497 public void onRunJobNow(JobStatus jobStatus) {
498 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
499 }
500
Christopher Tate7060b042014-06-09 19:50:00 -0700501 private class JobHandler extends Handler {
502
503 public JobHandler(Looper looper) {
504 super(looper);
505 }
506
507 @Override
508 public void handleMessage(Message message) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700509 synchronized (mJobs) {
510 if (!mReadyToRock) {
511 return;
512 }
513 }
Christopher Tate7060b042014-06-09 19:50:00 -0700514 switch (message.what) {
515 case MSG_JOB_EXPIRED:
516 synchronized (mJobs) {
517 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700518 // runNow can be null, which is a controller's way of indicating that its
519 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700520 if (runNow != null && !mPendingJobs.contains(runNow)
521 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700522 mPendingJobs.add(runNow);
523 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700524 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700525 }
Christopher Tate7060b042014-06-09 19:50:00 -0700526 break;
527 case MSG_CHECK_JOB:
Matthew Williams48a30db2014-09-23 13:39:36 -0700528 synchronized (mJobs) {
529 // Check the list of jobs and run some of them if we feel inclined.
530 maybeQueueReadyJobsForExecutionLockedH();
531 }
Christopher Tate7060b042014-06-09 19:50:00 -0700532 break;
533 }
534 maybeRunPendingJobsH();
535 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
536 removeMessages(MSG_CHECK_JOB);
537 }
538
539 /**
540 * Run through list of jobs and execute all possible - at least one is expired so we do
541 * as many as we can.
542 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700543 private void queueReadyJobsForExecutionLockedH() {
544 ArraySet<JobStatus> jobs = mJobs.getJobs();
545 if (DEBUG) {
546 Slog.d(TAG, "queuing all ready jobs for execution:");
547 }
548 for (int i=0; i<jobs.size(); i++) {
549 JobStatus job = jobs.valueAt(i);
550 if (isReadyToBeExecutedLocked(job)) {
551 if (DEBUG) {
552 Slog.d(TAG, " queued " + job.toShortString());
Christopher Tate7060b042014-06-09 19:50:00 -0700553 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700554 mPendingJobs.add(job);
555 } else if (isReadyToBeCancelledLocked(job)) {
556 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700557 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700558 }
559 if (DEBUG) {
560 final int queuedJobs = mPendingJobs.size();
561 if (queuedJobs == 0) {
562 Slog.d(TAG, "No jobs pending.");
563 } else {
564 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700565 }
Christopher Tate7060b042014-06-09 19:50:00 -0700566 }
567 }
568
569 /**
570 * The state of at least one job has changed. Here is where we could enforce various
571 * policies on when we want to execute jobs.
572 * Right now the policy is such:
573 * If >1 of the ready jobs is idle mode we send all of them off
574 * if more than 2 network connectivity jobs are ready we send them all off.
575 * If more than 4 jobs total are ready we send them all off.
576 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
577 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700578 private void maybeQueueReadyJobsForExecutionLockedH() {
579 int chargingCount = 0;
580 int idleCount = 0;
581 int backoffCount = 0;
582 int connectivityCount = 0;
583 List<JobStatus> runnableJobs = new ArrayList<JobStatus>();
584 ArraySet<JobStatus> jobs = mJobs.getJobs();
585 for (int i=0; i<jobs.size(); i++) {
586 JobStatus job = jobs.valueAt(i);
587 if (isReadyToBeExecutedLocked(job)) {
588 if (job.getNumFailures() > 0) {
589 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700590 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700591 if (job.hasIdleConstraint()) {
592 idleCount++;
593 }
594 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
595 connectivityCount++;
596 }
597 if (job.hasChargingConstraint()) {
598 chargingCount++;
599 }
600 runnableJobs.add(job);
601 } else if (isReadyToBeCancelledLocked(job)) {
602 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700603 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700604 }
605 if (backoffCount > 0 ||
606 idleCount >= MIN_IDLE_COUNT ||
607 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
608 chargingCount >= MIN_CHARGING_COUNT ||
609 runnableJobs.size() >= MIN_READY_JOBS_COUNT) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700610 if (DEBUG) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700611 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
Christopher Tate7060b042014-06-09 19:50:00 -0700612 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700613 for (int i=0; i<runnableJobs.size(); i++) {
614 mPendingJobs.add(runnableJobs.get(i));
615 }
616 } else {
617 if (DEBUG) {
618 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
619 }
620 }
621 if (DEBUG) {
622 Slog.d(TAG, "idle=" + idleCount + " connectivity=" +
623 connectivityCount + " charging=" + chargingCount + " tot=" +
624 runnableJobs.size());
Christopher Tate7060b042014-06-09 19:50:00 -0700625 }
626 }
627
628 /**
629 * Criteria for moving a job into the pending queue:
630 * - It's ready.
631 * - It's not pending.
632 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700633 * - The user that requested the job is running.
Christopher Tate7060b042014-06-09 19:50:00 -0700634 */
635 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700636 final boolean jobReady = job.isReady();
637 final boolean jobPending = mPendingJobs.contains(job);
638 final boolean jobActive = isCurrentlyActiveLocked(job);
639 final boolean userRunning = mStartedUsers.contains(job.getUserId());
640
641 if (DEBUG) {
642 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
643 + " ready=" + jobReady + " pending=" + jobPending
644 + " active=" + jobActive + " userRunning=" + userRunning);
645 }
646 return userRunning && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700647 }
648
649 /**
650 * Criteria for cancelling an active job:
651 * - It's not ready
652 * - It's running on a JSC.
653 */
654 private boolean isReadyToBeCancelledLocked(JobStatus job) {
655 return !job.isReady() && isCurrentlyActiveLocked(job);
656 }
657
658 /**
659 * Reconcile jobs in the pending queue against available execution contexts.
660 * A controller can force a job into the pending queue even if it's already running, but
661 * here is where we decide whether to actually execute it.
662 */
663 private void maybeRunPendingJobsH() {
664 synchronized (mJobs) {
665 Iterator<JobStatus> it = mPendingJobs.iterator();
Matthew Williams75fc5252014-09-02 16:17:53 -0700666 if (DEBUG) {
667 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
668 }
Christopher Tate7060b042014-06-09 19:50:00 -0700669 while (it.hasNext()) {
670 JobStatus nextPending = it.next();
671 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700672 for (int i=0; i<mActiveServices.size(); i++) {
673 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700674 final JobStatus running = jsc.getRunningJob();
675 if (running != null && running.matches(nextPending.getUid(),
676 nextPending.getJobId())) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700677 // Already running this job for this uId, skip.
Christopher Tate7060b042014-06-09 19:50:00 -0700678 availableContext = null;
679 break;
680 }
681 if (jsc.isAvailable()) {
682 availableContext = jsc;
683 }
684 }
685 if (availableContext != null) {
686 if (!availableContext.executeRunnableJob(nextPending)) {
687 if (DEBUG) {
688 Slog.d(TAG, "Error executing " + nextPending);
689 }
690 mJobs.remove(nextPending);
691 }
692 it.remove();
693 }
694 }
695 }
696 }
697 }
698
699 /**
700 * Binder stub trampoline implementation
701 */
702 final class JobSchedulerStub extends IJobScheduler.Stub {
703 /** Cache determination of whether a given app can persist jobs
704 * key is uid of the calling app; value is undetermined/true/false
705 */
706 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
707
708 // Enforce that only the app itself (or shared uid participant) can schedule a
709 // job that runs one of the app's services, as well as verifying that the
710 // named service properly requires the BIND_JOB_SERVICE permission
711 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700712 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700713 final ComponentName service = job.getService();
714 try {
Christopher Tate5568f542014-06-18 13:53:31 -0700715 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid));
716 if (si == null) {
717 throw new IllegalArgumentException("No such service " + service);
718 }
Christopher Tate7060b042014-06-09 19:50:00 -0700719 if (si.applicationInfo.uid != uid) {
720 throw new IllegalArgumentException("uid " + uid +
721 " cannot schedule job in " + service.getPackageName());
722 }
723 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
724 throw new IllegalArgumentException("Scheduled service " + service
725 + " does not require android.permission.BIND_JOB_SERVICE permission");
726 }
Christopher Tate5568f542014-06-18 13:53:31 -0700727 } catch (RemoteException e) {
728 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700729 }
730 }
731
732 private boolean canPersistJobs(int pid, int uid) {
733 // If we get this far we're good to go; all we need to do now is check
734 // whether the app is allowed to persist its scheduled work.
735 final boolean canPersist;
736 synchronized (mPersistCache) {
737 Boolean cached = mPersistCache.get(uid);
738 if (cached != null) {
739 canPersist = cached.booleanValue();
740 } else {
741 // Persisting jobs is tantamount to running at boot, so we permit
742 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
743 // permission
744 int result = getContext().checkPermission(
745 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
746 canPersist = (result == PackageManager.PERMISSION_GRANTED);
747 mPersistCache.put(uid, canPersist);
748 }
749 }
750 return canPersist;
751 }
752
753 // IJobScheduler implementation
754 @Override
755 public int schedule(JobInfo job) throws RemoteException {
756 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700757 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -0700758 }
759 final int pid = Binder.getCallingPid();
760 final int uid = Binder.getCallingUid();
761
762 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700763 if (job.isPersisted()) {
764 if (!canPersistJobs(pid, uid)) {
765 throw new IllegalArgumentException("Error: requested job be persisted without"
766 + " holding RECEIVE_BOOT_COMPLETED permission.");
767 }
768 }
Christopher Tate7060b042014-06-09 19:50:00 -0700769
770 long ident = Binder.clearCallingIdentity();
771 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700772 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700773 } finally {
774 Binder.restoreCallingIdentity(ident);
775 }
776 }
777
778 @Override
779 public List<JobInfo> getAllPendingJobs() throws RemoteException {
780 final int uid = Binder.getCallingUid();
781
782 long ident = Binder.clearCallingIdentity();
783 try {
784 return JobSchedulerService.this.getPendingJobs(uid);
785 } finally {
786 Binder.restoreCallingIdentity(ident);
787 }
788 }
789
790 @Override
791 public void cancelAll() throws RemoteException {
792 final int uid = Binder.getCallingUid();
793
794 long ident = Binder.clearCallingIdentity();
795 try {
796 JobSchedulerService.this.cancelJobsForUid(uid);
797 } finally {
798 Binder.restoreCallingIdentity(ident);
799 }
800 }
801
802 @Override
803 public void cancel(int jobId) throws RemoteException {
804 final int uid = Binder.getCallingUid();
805
806 long ident = Binder.clearCallingIdentity();
807 try {
808 JobSchedulerService.this.cancelJob(uid, jobId);
809 } finally {
810 Binder.restoreCallingIdentity(ident);
811 }
812 }
813
814 /**
815 * "dumpsys" infrastructure
816 */
817 @Override
818 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
819 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
820
821 long identityToken = Binder.clearCallingIdentity();
822 try {
823 JobSchedulerService.this.dumpInternal(pw);
824 } finally {
825 Binder.restoreCallingIdentity(identityToken);
826 }
827 }
828 };
829
830 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -0700831 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -0700832 synchronized (mJobs) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700833 pw.print("Started users: ");
834 for (int i=0; i<mStartedUsers.size(); i++) {
835 pw.print("u" + mStartedUsers.get(i) + " ");
836 }
837 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -0700838 pw.println("Registered jobs:");
839 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700840 ArraySet<JobStatus> jobs = mJobs.getJobs();
841 for (int i=0; i<jobs.size(); i++) {
842 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700843 job.dump(pw, " ");
844 }
845 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -0700846 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -0700847 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700848 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -0700849 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700850 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -0700851 }
852 pw.println();
Christopher Tatef973a7b2014-08-29 12:54:08 -0700853 pw.println("Pending:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700854 for (int i=0; i<mPendingJobs.size(); i++) {
855 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -0700856 }
857 pw.println();
858 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700859 for (int i=0; i<mActiveServices.size(); i++) {
860 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700861 if (jsc.isAvailable()) {
862 continue;
863 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -0700864 final long timeout = jsc.getTimeoutElapsed();
865 pw.print("Running for: ");
866 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
867 pw.print("s timeout=");
868 pw.print(timeout);
869 pw.print(" fromnow=");
870 pw.println(timeout-now);
871 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -0700872 }
873 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700874 pw.println();
875 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Christopher Tate7060b042014-06-09 19:50:00 -0700876 }
877 pw.println();
878 }
879}