JobSchedulerService.java revision 01ac45b6ff2334925c8d24b5278b44e5e30f5622
1/* 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 25import android.app.AppGlobals; 26import 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; 35import android.content.pm.IPackageManager; 36import android.content.pm.PackageManager; 37import android.content.pm.ServiceInfo; 38import android.os.BatteryStats; 39import android.os.Binder; 40import android.os.Handler; 41import android.os.Looper; 42import android.os.Message; 43import android.os.RemoteException; 44import android.os.ServiceManager; 45import android.os.SystemClock; 46import android.os.UserHandle; 47import android.util.ArraySet; 48import android.util.Slog; 49import android.util.SparseArray; 50 51import com.android.internal.app.IBatteryStats; 52import 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 59/** 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 { 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. */ 79 final JobStore mJobs; 80 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 */ 89 static final int MIN_IDLE_COUNT = 1; 90 /** 91 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule 92 * things early. 93 */ 94 static final int MIN_CONNECTIVITY_COUNT = 2; 95 /** 96 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running 97 * some work early. 98 */ 99 static final int MIN_READY_JOBS_COUNT = 4; 100 101 /** 102 * Track Services that have currently active or pending jobs. The index is provided by 103 * {@link JobStatus#getServiceToken()} 104 */ 105 final List<JobServiceContext> mActiveServices = new ArrayList<JobServiceContext>(); 106 /** List of controllers that will notify this service of updates to jobs. */ 107 List<StateController> mControllers; 108 /** 109 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list 110 * when ready to execute them. 111 */ 112 final ArrayList<JobStatus> mPendingJobs = new ArrayList<JobStatus>(); 113 114 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 124 /** 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. 153 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes. 154 */ 155 public int schedule(JobInfo job, int uId) { 156 JobStatus jobStatus = new JobStatus(job, uId); 157 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) { 165 ArraySet<JobStatus> jobs = mJobs.getJobs(); 166 for (int i=0; i<jobs.size(); i++) { 167 JobStatus job = jobs.valueAt(i); 168 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); 179 for (int i=0; i<jobsForUser.size(); i++) { 180 JobStatus toRemove = jobsForUser.get(i); 181 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); 199 for (int i=0; i<jobsForUid.size(); i++) { 200 JobStatus toRemove = jobsForUid.get(i); 201 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. 247 mControllers = new ArrayList<StateController>(); 248 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(); 255 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); 274 } 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 controller=0; controller<mControllers.size(); controller++) { 291 mControllers.get(controller).maybeStartTrackingJob(job); 292 } 293 } 294 // GO GO GO! 295 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget(); 296 } 297 } 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; 307 boolean rocking; 308 synchronized (mJobs) { 309 update = mJobs.add(jobStatus); 310 rocking = mReadyToRock; 311 } 312 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); 319 } 320 } 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; 329 boolean rocking; 330 synchronized (mJobs) { 331 // Remove from store as well as controllers. 332 removed = mJobs.remove(jobStatus); 333 rocking = mReadyToRock; 334 } 335 if (removed && rocking) { 336 for (int i=0; i<mControllers.size(); i++) { 337 StateController controller = mControllers.get(i); 338 controller.maybeStopTrackingJob(jobStatus); 339 } 340 } 341 return removed; 342 } 343 344 private boolean stopJobOnServiceContextLocked(JobStatus job) { 345 for (int i=0; i<mActiveServices.size(); i++) { 346 JobServiceContext jsc = mActiveServices.get(i); 347 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) { 362 for (int i=0; i<mActiveServices.size(); i++) { 363 JobServiceContext serviceContext = mActiveServices.get(i); 364 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() { 476 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 } 483 } 484 485 @Override 486 public void onRunJobNow(JobStatus jobStatus) { 487 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget(); 488 } 489 490 private class JobHandler extends Handler { 491 492 public JobHandler(Looper looper) { 493 super(looper); 494 } 495 496 @Override 497 public void handleMessage(Message message) { 498 switch (message.what) { 499 case MSG_JOB_EXPIRED: 500 synchronized (mJobs) { 501 JobStatus runNow = (JobStatus) message.obj; 502 if (!mPendingJobs.contains(runNow)) { 503 mPendingJobs.add(runNow); 504 } 505 } 506 queueReadyJobsForExecutionH(); 507 break; 508 case MSG_CHECK_JOB: 509 // Check the list of jobs and run some of them if we feel inclined. 510 maybeQueueReadyJobsForExecutionH(); 511 break; 512 } 513 maybeRunPendingJobsH(); 514 // Don't remove JOB_EXPIRED in case one came along while processing the queue. 515 removeMessages(MSG_CHECK_JOB); 516 } 517 518 /** 519 * Run through list of jobs and execute all possible - at least one is expired so we do 520 * as many as we can. 521 */ 522 private void queueReadyJobsForExecutionH() { 523 synchronized (mJobs) { 524 ArraySet<JobStatus> jobs = mJobs.getJobs(); 525 for (int i=0; i<jobs.size(); i++) { 526 JobStatus job = jobs.valueAt(i); 527 if (isReadyToBeExecutedLocked(job)) { 528 mPendingJobs.add(job); 529 } else if (isReadyToBeCancelledLocked(job)) { 530 stopJobOnServiceContextLocked(job); 531 } 532 } 533 } 534 } 535 536 /** 537 * The state of at least one job has changed. Here is where we could enforce various 538 * policies on when we want to execute jobs. 539 * Right now the policy is such: 540 * If >1 of the ready jobs is idle mode we send all of them off 541 * if more than 2 network connectivity jobs are ready we send them all off. 542 * If more than 4 jobs total are ready we send them all off. 543 * TODO: It would be nice to consolidate these sort of high-level policies somewhere. 544 */ 545 private void maybeQueueReadyJobsForExecutionH() { 546 synchronized (mJobs) { 547 int idleCount = 0; 548 int backoffCount = 0; 549 int connectivityCount = 0; 550 List<JobStatus> runnableJobs = new ArrayList<JobStatus>(); 551 ArraySet<JobStatus> jobs = mJobs.getJobs(); 552 for (int i=0; i<jobs.size(); i++) { 553 JobStatus job = jobs.valueAt(i); 554 if (isReadyToBeExecutedLocked(job)) { 555 if (job.getNumFailures() > 0) { 556 backoffCount++; 557 } 558 if (job.hasIdleConstraint()) { 559 idleCount++; 560 } 561 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) { 562 connectivityCount++; 563 } 564 runnableJobs.add(job); 565 } else if (isReadyToBeCancelledLocked(job)) { 566 stopJobOnServiceContextLocked(job); 567 } 568 } 569 if (backoffCount > 0 || idleCount >= MIN_IDLE_COUNT || 570 connectivityCount >= MIN_CONNECTIVITY_COUNT || 571 runnableJobs.size() >= MIN_READY_JOBS_COUNT) { 572 for (int i=0; i<runnableJobs.size(); i++) { 573 mPendingJobs.add(runnableJobs.get(i)); 574 } 575 } 576 } 577 } 578 579 /** 580 * Criteria for moving a job into the pending queue: 581 * - It's ready. 582 * - It's not pending. 583 * - It's not already running on a JSC. 584 */ 585 private boolean isReadyToBeExecutedLocked(JobStatus job) { 586 return job.isReady() && !mPendingJobs.contains(job) && !isCurrentlyActiveLocked(job); 587 } 588 589 /** 590 * Criteria for cancelling an active job: 591 * - It's not ready 592 * - It's running on a JSC. 593 */ 594 private boolean isReadyToBeCancelledLocked(JobStatus job) { 595 return !job.isReady() && isCurrentlyActiveLocked(job); 596 } 597 598 /** 599 * Reconcile jobs in the pending queue against available execution contexts. 600 * A controller can force a job into the pending queue even if it's already running, but 601 * here is where we decide whether to actually execute it. 602 */ 603 private void maybeRunPendingJobsH() { 604 synchronized (mJobs) { 605 Iterator<JobStatus> it = mPendingJobs.iterator(); 606 while (it.hasNext()) { 607 JobStatus nextPending = it.next(); 608 JobServiceContext availableContext = null; 609 for (int i=0; i<mActiveServices.size(); i++) { 610 JobServiceContext jsc = mActiveServices.get(i); 611 final JobStatus running = jsc.getRunningJob(); 612 if (running != null && running.matches(nextPending.getUid(), 613 nextPending.getJobId())) { 614 // Already running this tId for this uId, skip. 615 availableContext = null; 616 break; 617 } 618 if (jsc.isAvailable()) { 619 availableContext = jsc; 620 } 621 } 622 if (availableContext != null) { 623 if (!availableContext.executeRunnableJob(nextPending)) { 624 if (DEBUG) { 625 Slog.d(TAG, "Error executing " + nextPending); 626 } 627 mJobs.remove(nextPending); 628 } 629 it.remove(); 630 } 631 } 632 } 633 } 634 } 635 636 /** 637 * Binder stub trampoline implementation 638 */ 639 final class JobSchedulerStub extends IJobScheduler.Stub { 640 /** Cache determination of whether a given app can persist jobs 641 * key is uid of the calling app; value is undetermined/true/false 642 */ 643 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>(); 644 645 // Enforce that only the app itself (or shared uid participant) can schedule a 646 // job that runs one of the app's services, as well as verifying that the 647 // named service properly requires the BIND_JOB_SERVICE permission 648 private void enforceValidJobRequest(int uid, JobInfo job) { 649 final IPackageManager pm = AppGlobals.getPackageManager(); 650 final ComponentName service = job.getService(); 651 try { 652 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid)); 653 if (si == null) { 654 throw new IllegalArgumentException("No such service " + service); 655 } 656 if (si.applicationInfo.uid != uid) { 657 throw new IllegalArgumentException("uid " + uid + 658 " cannot schedule job in " + service.getPackageName()); 659 } 660 if (!JobService.PERMISSION_BIND.equals(si.permission)) { 661 throw new IllegalArgumentException("Scheduled service " + service 662 + " does not require android.permission.BIND_JOB_SERVICE permission"); 663 } 664 } catch (RemoteException e) { 665 // Can't happen; the Package Manager is in this same process 666 } 667 } 668 669 private boolean canPersistJobs(int pid, int uid) { 670 // If we get this far we're good to go; all we need to do now is check 671 // whether the app is allowed to persist its scheduled work. 672 final boolean canPersist; 673 synchronized (mPersistCache) { 674 Boolean cached = mPersistCache.get(uid); 675 if (cached != null) { 676 canPersist = cached.booleanValue(); 677 } else { 678 // Persisting jobs is tantamount to running at boot, so we permit 679 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED 680 // permission 681 int result = getContext().checkPermission( 682 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid); 683 canPersist = (result == PackageManager.PERMISSION_GRANTED); 684 mPersistCache.put(uid, canPersist); 685 } 686 } 687 return canPersist; 688 } 689 690 // IJobScheduler implementation 691 @Override 692 public int schedule(JobInfo job) throws RemoteException { 693 if (DEBUG) { 694 Slog.d(TAG, "Scheduling job: " + job); 695 } 696 final int pid = Binder.getCallingPid(); 697 final int uid = Binder.getCallingUid(); 698 699 enforceValidJobRequest(uid, job); 700 if (job.isPersisted()) { 701 if (!canPersistJobs(pid, uid)) { 702 throw new IllegalArgumentException("Error: requested job be persisted without" 703 + " holding RECEIVE_BOOT_COMPLETED permission."); 704 } 705 } 706 707 long ident = Binder.clearCallingIdentity(); 708 try { 709 return JobSchedulerService.this.schedule(job, uid); 710 } finally { 711 Binder.restoreCallingIdentity(ident); 712 } 713 } 714 715 @Override 716 public List<JobInfo> getAllPendingJobs() throws RemoteException { 717 final int uid = Binder.getCallingUid(); 718 719 long ident = Binder.clearCallingIdentity(); 720 try { 721 return JobSchedulerService.this.getPendingJobs(uid); 722 } finally { 723 Binder.restoreCallingIdentity(ident); 724 } 725 } 726 727 @Override 728 public void cancelAll() throws RemoteException { 729 final int uid = Binder.getCallingUid(); 730 731 long ident = Binder.clearCallingIdentity(); 732 try { 733 JobSchedulerService.this.cancelJobsForUid(uid); 734 } finally { 735 Binder.restoreCallingIdentity(ident); 736 } 737 } 738 739 @Override 740 public void cancel(int jobId) throws RemoteException { 741 final int uid = Binder.getCallingUid(); 742 743 long ident = Binder.clearCallingIdentity(); 744 try { 745 JobSchedulerService.this.cancelJob(uid, jobId); 746 } finally { 747 Binder.restoreCallingIdentity(ident); 748 } 749 } 750 751 /** 752 * "dumpsys" infrastructure 753 */ 754 @Override 755 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 756 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG); 757 758 long identityToken = Binder.clearCallingIdentity(); 759 try { 760 JobSchedulerService.this.dumpInternal(pw); 761 } finally { 762 Binder.restoreCallingIdentity(identityToken); 763 } 764 } 765 }; 766 767 void dumpInternal(PrintWriter pw) { 768 synchronized (mJobs) { 769 pw.println("Registered jobs:"); 770 if (mJobs.size() > 0) { 771 ArraySet<JobStatus> jobs = mJobs.getJobs(); 772 for (int i=0; i<jobs.size(); i++) { 773 JobStatus job = jobs.valueAt(i); 774 job.dump(pw, " "); 775 } 776 } else { 777 pw.println(); 778 pw.println("No jobs scheduled."); 779 } 780 for (int i=0; i<mControllers.size(); i++) { 781 pw.println(); 782 mControllers.get(i).dumpControllerState(pw); 783 } 784 pw.println(); 785 pw.println("Pending"); 786 for (int i=0; i<mPendingJobs.size(); i++) { 787 pw.println(mPendingJobs.get(i).hashCode()); 788 } 789 pw.println(); 790 pw.println("Active jobs:"); 791 for (int i=0; i<mActiveServices.size(); i++) { 792 JobServiceContext jsc = mActiveServices.get(i); 793 if (jsc.isAvailable()) { 794 continue; 795 } else { 796 pw.println(jsc.getRunningJob().hashCode() + " for: " + 797 (SystemClock.elapsedRealtime() 798 - jsc.getExecutionStartTimeElapsed())/1000 + "s " + 799 "timeout: " + jsc.getTimeoutElapsed()); 800 } 801 } 802 pw.println(); 803 pw.print("mReadyToRock="); pw.println(mReadyToRock); 804 } 805 pw.println(); 806 } 807} 808