blob: caae9f5116ee9aa2f52a740ca0995430e4a3c269 [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
72 implements StateChangedListener, JobCompletedListener, JobMapReadFinishedListener {
73 // 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;
77 static final String TAG = "JobManagerService";
78 /** 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 /**
91 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
92 * things early.
93 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070094 static final int MIN_CONNECTIVITY_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -070095 /**
96 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
97 * some work early.
98 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070099 static final int MIN_READY_JOBS_COUNT = 4;
Christopher Tate7060b042014-06-09 19:50:00 -0700100
101 /**
102 * Track Services that have currently active or pending jobs. The index is provided by
103 * {@link JobStatus#getServiceToken()}
104 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700105 final List<JobServiceContext> mActiveServices = new ArrayList<JobServiceContext>();
Christopher Tate7060b042014-06-09 19:50:00 -0700106 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700107 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700108 /**
109 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
110 * when ready to execute them.
111 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700112 final ArrayList<JobStatus> mPendingJobs = new ArrayList<JobStatus>();
Christopher Tate7060b042014-06-09 19:50:00 -0700113
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700114 final JobHandler mHandler;
115 final JobSchedulerStub mJobSchedulerStub;
116
117 IBatteryStats mBatteryStats;
118
119 /**
120 * Set to true once we are allowed to run third party apps.
121 */
122 boolean mReadyToRock;
123
Christopher Tate7060b042014-06-09 19:50:00 -0700124 /**
125 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
126 * still clean up. On reinstall the package will have a new uid.
127 */
128 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
129 @Override
130 public void onReceive(Context context, Intent intent) {
131 Slog.d(TAG, "Receieved: " + intent.getAction());
132 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
133 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
134 if (DEBUG) {
135 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
136 }
137 cancelJobsForUid(uidRemoved);
138 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
139 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
140 if (DEBUG) {
141 Slog.d(TAG, "Removing jobs for user: " + userId);
142 }
143 cancelJobsForUser(userId);
144 }
145 }
146 };
147
148 /**
149 * Entry point from client to schedule the provided job.
150 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
151 * @param job JobInfo object containing execution parameters
152 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700153 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
154 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700155 public int schedule(JobInfo job, int uId) {
156 JobStatus jobStatus = new JobStatus(job, uId);
Christopher Tate7060b042014-06-09 19:50:00 -0700157 cancelJob(uId, job.getId());
158 startTrackingJob(jobStatus);
159 return JobScheduler.RESULT_SUCCESS;
160 }
161
162 public List<JobInfo> getPendingJobs(int uid) {
163 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
164 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700165 ArraySet<JobStatus> jobs = mJobs.getJobs();
166 for (int i=0; i<jobs.size(); i++) {
167 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700168 if (job.getUid() == uid) {
169 outList.add(job.getJob());
170 }
171 }
172 }
173 return outList;
174 }
175
176 private void cancelJobsForUser(int userHandle) {
177 synchronized (mJobs) {
178 List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700179 for (int i=0; i<jobsForUser.size(); i++) {
180 JobStatus toRemove = jobsForUser.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700181 if (DEBUG) {
182 Slog.d(TAG, "Cancelling: " + toRemove);
183 }
184 cancelJobLocked(toRemove);
185 }
186 }
187 }
188
189 /**
190 * Entry point from client to cancel all jobs originating from their uid.
191 * This will remove the job from the master list, and cancel the job if it was staged for
192 * execution or being executed.
193 * @param uid To check against for removal of a job.
194 */
195 public void cancelJobsForUid(int uid) {
196 // Remove from master list.
197 synchronized (mJobs) {
198 List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700199 for (int i=0; i<jobsForUid.size(); i++) {
200 JobStatus toRemove = jobsForUid.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700201 if (DEBUG) {
202 Slog.d(TAG, "Cancelling: " + toRemove);
203 }
204 cancelJobLocked(toRemove);
205 }
206 }
207 }
208
209 /**
210 * Entry point from client to cancel the job corresponding to the jobId provided.
211 * This will remove the job from the master list, and cancel the job if it was staged for
212 * execution or being executed.
213 * @param uid Uid of the calling client.
214 * @param jobId Id of the job, provided at schedule-time.
215 */
216 public void cancelJob(int uid, int jobId) {
217 JobStatus toCancel;
218 synchronized (mJobs) {
219 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
220 if (toCancel != null) {
221 cancelJobLocked(toCancel);
222 }
223 }
224 }
225
226 private void cancelJobLocked(JobStatus cancelled) {
227 // Remove from store.
228 stopTrackingJob(cancelled);
229 // Remove from pending queue.
230 mPendingJobs.remove(cancelled);
231 // Cancel if running.
232 stopJobOnServiceContextLocked(cancelled);
233 }
234
235 /**
236 * Initializes the system service.
237 * <p>
238 * Subclasses must define a single argument constructor that accepts the context
239 * and passes it to super.
240 * </p>
241 *
242 * @param context The system server context.
243 */
244 public JobSchedulerService(Context context) {
245 super(context);
246 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700247 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700248 mControllers.add(ConnectivityController.get(this));
249 mControllers.add(TimeController.get(this));
250 mControllers.add(IdleController.get(this));
251 mControllers.add(BatteryController.get(this));
252
253 mHandler = new JobHandler(context.getMainLooper());
254 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700255 mJobs = JobStore.initAndGet(this);
256 }
257
258 @Override
259 public void onStart() {
260 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
261 }
262
263 @Override
264 public void onBootPhase(int phase) {
265 if (PHASE_SYSTEM_SERVICES_READY == phase) {
266 // Register br for package removals and user removals.
267 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
268 filter.addDataScheme("package");
269 getContext().registerReceiverAsUser(
270 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
271 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
272 getContext().registerReceiverAsUser(
273 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700274 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
275 synchronized (mJobs) {
276 // Let's go!
277 mReadyToRock = true;
278 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
279 BatteryStats.SERVICE_NAME));
280 // Create the "runners".
281 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
282 mActiveServices.add(
283 new JobServiceContext(this, mBatteryStats,
284 getContext().getMainLooper()));
285 }
286 // Attach jobs to their controllers.
287 ArraySet<JobStatus> jobs = mJobs.getJobs();
288 for (int i=0; i<jobs.size(); i++) {
289 JobStatus job = jobs.valueAt(i);
290 for (int j=0; j<mControllers.size(); j++) {
291 mControllers.get(i).maybeStartTrackingJob(job);
292 }
293 }
294 // GO GO GO!
295 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
296 }
Christopher Tate7060b042014-06-09 19:50:00 -0700297 }
298 }
299
300 /**
301 * Called when we have a job status object that we need to insert in our
302 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
303 * about.
304 */
305 private void startTrackingJob(JobStatus jobStatus) {
306 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700307 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700308 synchronized (mJobs) {
309 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700310 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700311 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700312 if (rocking) {
313 for (int i=0; i<mControllers.size(); i++) {
314 StateController controller = mControllers.get(i);
315 if (update) {
316 controller.maybeStopTrackingJob(jobStatus);
317 }
318 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700319 }
Christopher Tate7060b042014-06-09 19:50:00 -0700320 }
321 }
322
323 /**
324 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
325 * object removed.
326 */
327 private boolean stopTrackingJob(JobStatus jobStatus) {
328 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700329 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700330 synchronized (mJobs) {
331 // Remove from store as well as controllers.
332 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700333 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700334 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700335 if (removed && rocking) {
336 for (int i=0; i<mControllers.size(); i++) {
337 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700338 controller.maybeStopTrackingJob(jobStatus);
339 }
340 }
341 return removed;
342 }
343
344 private boolean stopJobOnServiceContextLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700345 for (int i=0; i<mActiveServices.size(); i++) {
346 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700347 final JobStatus executing = jsc.getRunningJob();
348 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
349 jsc.cancelExecutingJob();
350 return true;
351 }
352 }
353 return false;
354 }
355
356 /**
357 * @param job JobStatus we are querying against.
358 * @return Whether or not the job represented by the status object is currently being run or
359 * is pending.
360 */
361 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700362 for (int i=0; i<mActiveServices.size(); i++) {
363 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700364 final JobStatus running = serviceContext.getRunningJob();
365 if (running != null && running.matches(job.getUid(), job.getJobId())) {
366 return true;
367 }
368 }
369 return false;
370 }
371
372 /**
373 * A job is rescheduled with exponential back-off if the client requests this from their
374 * execution logic.
375 * A caveat is for idle-mode jobs, for which the idle-mode constraint will usurp the
376 * timeliness of the reschedule. For an idle-mode job, no deadline is given.
377 * @param failureToReschedule Provided job status that we will reschedule.
378 * @return A newly instantiated JobStatus with the same constraints as the last job except
379 * with adjusted timing constraints.
380 */
381 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
382 final long elapsedNowMillis = SystemClock.elapsedRealtime();
383 final JobInfo job = failureToReschedule.getJob();
384
385 final long initialBackoffMillis = job.getInitialBackoffMillis();
386 final int backoffAttempt = failureToReschedule.getNumFailures() + 1;
387 long newEarliestRuntimeElapsed = elapsedNowMillis;
388
389 switch (job.getBackoffPolicy()) {
390 case JobInfo.BackoffPolicy.LINEAR:
391 newEarliestRuntimeElapsed += initialBackoffMillis * backoffAttempt;
392 break;
393 default:
394 if (DEBUG) {
395 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
396 }
397 case JobInfo.BackoffPolicy.EXPONENTIAL:
398 newEarliestRuntimeElapsed +=
399 Math.pow(initialBackoffMillis * 0.001, backoffAttempt) * 1000;
400 break;
401 }
402 newEarliestRuntimeElapsed =
403 Math.min(newEarliestRuntimeElapsed, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
404 return new JobStatus(failureToReschedule, newEarliestRuntimeElapsed,
405 JobStatus.NO_LATEST_RUNTIME, backoffAttempt);
406 }
407
408 /**
409 * Called after a periodic has executed so we can to re-add it. We take the last execution time
410 * of the job to be the time of completion (i.e. the time at which this function is called).
411 * This could be inaccurate b/c the job can run for as long as
412 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
413 * to underscheduling at least, rather than if we had taken the last execution time to be the
414 * start of the execution.
415 * @return A new job representing the execution criteria for this instantiation of the
416 * recurring job.
417 */
418 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
419 final long elapsedNow = SystemClock.elapsedRealtime();
420 // Compute how much of the period is remaining.
421 long runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0);
422 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
423 long period = periodicToReschedule.getJob().getIntervalMillis();
424 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
425
426 if (DEBUG) {
427 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
428 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
429 }
430 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
431 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
432 }
433
434 // JobCompletedListener implementations.
435
436 /**
437 * A job just finished executing. We fetch the
438 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
439 * whether we want to reschedule we readd it to the controllers.
440 * @param jobStatus Completed job.
441 * @param needsReschedule Whether the implementing class should reschedule this job.
442 */
443 @Override
444 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
445 if (DEBUG) {
446 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
447 }
448 if (!stopTrackingJob(jobStatus)) {
449 if (DEBUG) {
450 Slog.e(TAG, "Error removing job: could not find job to remove. Was job " +
451 "removed while executing?");
452 }
453 return;
454 }
455 if (needsReschedule) {
456 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
457 startTrackingJob(rescheduled);
458 } else if (jobStatus.getJob().isPeriodic()) {
459 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
460 startTrackingJob(rescheduledPeriodic);
461 }
462 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
463 }
464
465 // StateChangedListener implementations.
466
467 /**
468 * Off-board work to our handler thread as quickly as possible, b/c this call is probably being
469 * made on the main thread.
470 * For now this takes the job and if it's ready to run it will run it. In future we might not
471 * provide the job, so that the StateChangedListener has to run through its list of jobs to
472 * see which are ready. This will further decouple the controllers from the execution logic.
473 */
474 @Override
475 public void onControllerStateChanged() {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700476 synchronized (mJobs) {
477 if (mReadyToRock) {
478 // Post a message to to run through the list of jobs and start/stop any that
479 // are eligible.
480 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
481 }
482 }
Christopher Tate7060b042014-06-09 19:50:00 -0700483 }
484
485 @Override
486 public void onRunJobNow(JobStatus jobStatus) {
487 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
488 }
489
490 /**
491 * Disk I/O is finished, take the list of jobs we read from disk and add them to our
492 * {@link JobStore}.
493 * This is run on the {@link com.android.server.IoThread} instance, which is a separate thread,
494 * and is called once at boot.
495 */
496 @Override
497 public void onJobMapReadFinished(List<JobStatus> jobs) {
498 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700499 for (int i=0; i<jobs.size(); i++) {
500 JobStatus js = jobs.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700501 if (mJobs.containsJobIdForUid(js.getJobId(), js.getUid())) {
502 // An app with BOOT_COMPLETED *might* have decided to reschedule their job, in
503 // the same amount of time it took us to read it from disk. If this is the case
504 // we leave it be.
505 continue;
506 }
507 startTrackingJob(js);
508 }
509 }
510 }
511
512 private class JobHandler extends Handler {
513
514 public JobHandler(Looper looper) {
515 super(looper);
516 }
517
518 @Override
519 public void handleMessage(Message message) {
520 switch (message.what) {
521 case MSG_JOB_EXPIRED:
522 synchronized (mJobs) {
523 JobStatus runNow = (JobStatus) message.obj;
524 if (!mPendingJobs.contains(runNow)) {
525 mPendingJobs.add(runNow);
526 }
527 }
528 queueReadyJobsForExecutionH();
529 break;
530 case MSG_CHECK_JOB:
531 // Check the list of jobs and run some of them if we feel inclined.
532 maybeQueueReadyJobsForExecutionH();
533 break;
534 }
535 maybeRunPendingJobsH();
536 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
537 removeMessages(MSG_CHECK_JOB);
538 }
539
540 /**
541 * Run through list of jobs and execute all possible - at least one is expired so we do
542 * as many as we can.
543 */
544 private void queueReadyJobsForExecutionH() {
545 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700546 ArraySet<JobStatus> jobs = mJobs.getJobs();
547 for (int i=0; i<jobs.size(); i++) {
548 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700549 if (isReadyToBeExecutedLocked(job)) {
550 mPendingJobs.add(job);
551 } else if (isReadyToBeCancelledLocked(job)) {
552 stopJobOnServiceContextLocked(job);
553 }
554 }
555 }
556 }
557
558 /**
559 * The state of at least one job has changed. Here is where we could enforce various
560 * policies on when we want to execute jobs.
561 * Right now the policy is such:
562 * If >1 of the ready jobs is idle mode we send all of them off
563 * if more than 2 network connectivity jobs are ready we send them all off.
564 * If more than 4 jobs total are ready we send them all off.
565 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
566 */
567 private void maybeQueueReadyJobsForExecutionH() {
568 synchronized (mJobs) {
569 int idleCount = 0;
570 int backoffCount = 0;
571 int connectivityCount = 0;
572 List<JobStatus> runnableJobs = new ArrayList<JobStatus>();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700573 ArraySet<JobStatus> jobs = mJobs.getJobs();
574 for (int i=0; i<jobs.size(); i++) {
575 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700576 if (isReadyToBeExecutedLocked(job)) {
577 if (job.getNumFailures() > 0) {
578 backoffCount++;
579 }
580 if (job.hasIdleConstraint()) {
581 idleCount++;
582 }
583 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
584 connectivityCount++;
585 }
586 runnableJobs.add(job);
587 } else if (isReadyToBeCancelledLocked(job)) {
588 stopJobOnServiceContextLocked(job);
589 }
590 }
591 if (backoffCount > 0 || idleCount >= MIN_IDLE_COUNT ||
592 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
593 runnableJobs.size() >= MIN_READY_JOBS_COUNT) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700594 for (int i=0; i<runnableJobs.size(); i++) {
595 mPendingJobs.add(runnableJobs.get(i));
Christopher Tate7060b042014-06-09 19:50:00 -0700596 }
597 }
598 }
599 }
600
601 /**
602 * Criteria for moving a job into the pending queue:
603 * - It's ready.
604 * - It's not pending.
605 * - It's not already running on a JSC.
606 */
607 private boolean isReadyToBeExecutedLocked(JobStatus job) {
608 return job.isReady() && !mPendingJobs.contains(job) && !isCurrentlyActiveLocked(job);
609 }
610
611 /**
612 * Criteria for cancelling an active job:
613 * - It's not ready
614 * - It's running on a JSC.
615 */
616 private boolean isReadyToBeCancelledLocked(JobStatus job) {
617 return !job.isReady() && isCurrentlyActiveLocked(job);
618 }
619
620 /**
621 * Reconcile jobs in the pending queue against available execution contexts.
622 * A controller can force a job into the pending queue even if it's already running, but
623 * here is where we decide whether to actually execute it.
624 */
625 private void maybeRunPendingJobsH() {
626 synchronized (mJobs) {
627 Iterator<JobStatus> it = mPendingJobs.iterator();
628 while (it.hasNext()) {
629 JobStatus nextPending = it.next();
630 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700631 for (int i=0; i<mActiveServices.size(); i++) {
632 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700633 final JobStatus running = jsc.getRunningJob();
634 if (running != null && running.matches(nextPending.getUid(),
635 nextPending.getJobId())) {
636 // Already running this tId for this uId, skip.
637 availableContext = null;
638 break;
639 }
640 if (jsc.isAvailable()) {
641 availableContext = jsc;
642 }
643 }
644 if (availableContext != null) {
645 if (!availableContext.executeRunnableJob(nextPending)) {
646 if (DEBUG) {
647 Slog.d(TAG, "Error executing " + nextPending);
648 }
649 mJobs.remove(nextPending);
650 }
651 it.remove();
652 }
653 }
654 }
655 }
656 }
657
658 /**
659 * Binder stub trampoline implementation
660 */
661 final class JobSchedulerStub extends IJobScheduler.Stub {
662 /** Cache determination of whether a given app can persist jobs
663 * key is uid of the calling app; value is undetermined/true/false
664 */
665 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
666
667 // Enforce that only the app itself (or shared uid participant) can schedule a
668 // job that runs one of the app's services, as well as verifying that the
669 // named service properly requires the BIND_JOB_SERVICE permission
670 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700671 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700672 final ComponentName service = job.getService();
673 try {
Christopher Tate5568f542014-06-18 13:53:31 -0700674 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid));
675 if (si == null) {
676 throw new IllegalArgumentException("No such service " + service);
677 }
Christopher Tate7060b042014-06-09 19:50:00 -0700678 if (si.applicationInfo.uid != uid) {
679 throw new IllegalArgumentException("uid " + uid +
680 " cannot schedule job in " + service.getPackageName());
681 }
682 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
683 throw new IllegalArgumentException("Scheduled service " + service
684 + " does not require android.permission.BIND_JOB_SERVICE permission");
685 }
Christopher Tate5568f542014-06-18 13:53:31 -0700686 } catch (RemoteException e) {
687 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700688 }
689 }
690
691 private boolean canPersistJobs(int pid, int uid) {
692 // If we get this far we're good to go; all we need to do now is check
693 // whether the app is allowed to persist its scheduled work.
694 final boolean canPersist;
695 synchronized (mPersistCache) {
696 Boolean cached = mPersistCache.get(uid);
697 if (cached != null) {
698 canPersist = cached.booleanValue();
699 } else {
700 // Persisting jobs is tantamount to running at boot, so we permit
701 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
702 // permission
703 int result = getContext().checkPermission(
704 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
705 canPersist = (result == PackageManager.PERMISSION_GRANTED);
706 mPersistCache.put(uid, canPersist);
707 }
708 }
709 return canPersist;
710 }
711
712 // IJobScheduler implementation
713 @Override
714 public int schedule(JobInfo job) throws RemoteException {
715 if (DEBUG) {
716 Slog.d(TAG, "Scheduling job: " + job);
717 }
718 final int pid = Binder.getCallingPid();
719 final int uid = Binder.getCallingUid();
720
721 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700722 if (job.isPersisted()) {
723 if (!canPersistJobs(pid, uid)) {
724 throw new IllegalArgumentException("Error: requested job be persisted without"
725 + " holding RECEIVE_BOOT_COMPLETED permission.");
726 }
727 }
Christopher Tate7060b042014-06-09 19:50:00 -0700728
729 long ident = Binder.clearCallingIdentity();
730 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700731 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700732 } finally {
733 Binder.restoreCallingIdentity(ident);
734 }
735 }
736
737 @Override
738 public List<JobInfo> getAllPendingJobs() throws RemoteException {
739 final int uid = Binder.getCallingUid();
740
741 long ident = Binder.clearCallingIdentity();
742 try {
743 return JobSchedulerService.this.getPendingJobs(uid);
744 } finally {
745 Binder.restoreCallingIdentity(ident);
746 }
747 }
748
749 @Override
750 public void cancelAll() throws RemoteException {
751 final int uid = Binder.getCallingUid();
752
753 long ident = Binder.clearCallingIdentity();
754 try {
755 JobSchedulerService.this.cancelJobsForUid(uid);
756 } finally {
757 Binder.restoreCallingIdentity(ident);
758 }
759 }
760
761 @Override
762 public void cancel(int jobId) throws RemoteException {
763 final int uid = Binder.getCallingUid();
764
765 long ident = Binder.clearCallingIdentity();
766 try {
767 JobSchedulerService.this.cancelJob(uid, jobId);
768 } finally {
769 Binder.restoreCallingIdentity(ident);
770 }
771 }
772
773 /**
774 * "dumpsys" infrastructure
775 */
776 @Override
777 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
778 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
779
780 long identityToken = Binder.clearCallingIdentity();
781 try {
782 JobSchedulerService.this.dumpInternal(pw);
783 } finally {
784 Binder.restoreCallingIdentity(identityToken);
785 }
786 }
787 };
788
789 void dumpInternal(PrintWriter pw) {
790 synchronized (mJobs) {
791 pw.println("Registered jobs:");
792 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700793 ArraySet<JobStatus> jobs = mJobs.getJobs();
794 for (int i=0; i<jobs.size(); i++) {
795 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700796 job.dump(pw, " ");
797 }
798 } else {
799 pw.println();
800 pw.println("No jobs scheduled.");
801 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700802 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -0700803 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700804 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -0700805 }
806 pw.println();
807 pw.println("Pending");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700808 for (int i=0; i<mPendingJobs.size(); i++) {
809 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -0700810 }
811 pw.println();
812 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700813 for (int i=0; i<mActiveServices.size(); i++) {
814 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700815 if (jsc.isAvailable()) {
816 continue;
817 } else {
818 pw.println(jsc.getRunningJob().hashCode() + " for: " +
819 (SystemClock.elapsedRealtime()
820 - jsc.getExecutionStartTimeElapsed())/1000 + "s " +
821 "timeout: " + jsc.getTimeoutElapsed());
822 }
823 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700824 pw.println();
825 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Christopher Tate7060b042014-06-09 19:50:00 -0700826 }
827 pw.println();
828 }
829}