blob: 0e9a9cc5da51bbd03c9572cda846632c31b2f1d5 [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
25import android.app.job.JobInfo;
26import android.app.job.JobScheduler;
27import android.app.job.JobService;
28import android.app.job.IJobScheduler;
29import android.content.BroadcastReceiver;
30import android.content.ComponentName;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
35import android.content.pm.PackageManager.NameNotFoundException;
36import android.content.pm.ServiceInfo;
37import android.os.Binder;
38import android.os.Handler;
39import android.os.Looper;
40import android.os.Message;
41import android.os.RemoteException;
42import android.os.SystemClock;
43import android.os.UserHandle;
44import android.util.Slog;
45import android.util.SparseArray;
46
47import com.android.server.job.controllers.BatteryController;
48import com.android.server.job.controllers.ConnectivityController;
49import com.android.server.job.controllers.IdleController;
50import com.android.server.job.controllers.JobStatus;
51import com.android.server.job.controllers.StateController;
52import com.android.server.job.controllers.TimeController;
53
54import java.util.LinkedList;
55
56/**
57 * Responsible for taking jobs representing work to be performed by a client app, and determining
58 * based on the criteria specified when that job should be run against the client application's
59 * endpoint.
60 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
61 * about constraints, or the state of active jobs. It receives callbacks from the various
62 * controllers and completed jobs and operates accordingly.
63 *
64 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
65 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
66 * @hide
67 */
68public class JobSchedulerService extends com.android.server.SystemService
69 implements StateChangedListener, JobCompletedListener, JobMapReadFinishedListener {
70 // TODO: Switch this off for final version.
71 static final boolean DEBUG = true;
72 /** The number of concurrent jobs we run at one time. */
73 private static final int MAX_JOB_CONTEXTS_COUNT = 3;
74 static final String TAG = "JobManagerService";
75 /** Master list of jobs. */
76 private final JobStore mJobs;
77
78 static final int MSG_JOB_EXPIRED = 0;
79 static final int MSG_CHECK_JOB = 1;
80
81 // Policy constants
82 /**
83 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
84 * early.
85 */
86 private static final int MIN_IDLE_COUNT = 1;
87 /**
88 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
89 * things early.
90 */
91 private static final int MIN_CONNECTIVITY_COUNT = 2;
92 /**
93 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
94 * some work early.
95 */
96 private static final int MIN_READY_JOBS_COUNT = 4;
97
98 /**
99 * Track Services that have currently active or pending jobs. The index is provided by
100 * {@link JobStatus#getServiceToken()}
101 */
102 private final List<JobServiceContext> mActiveServices = new LinkedList<JobServiceContext>();
103 /** List of controllers that will notify this service of updates to jobs. */
104 private List<StateController> mControllers;
105 /**
106 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
107 * when ready to execute them.
108 */
109 private final LinkedList<JobStatus> mPendingJobs = new LinkedList<JobStatus>();
110
111 private final JobHandler mHandler;
112 private final JobSchedulerStub mJobSchedulerStub;
113 /**
114 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
115 * still clean up. On reinstall the package will have a new uid.
116 */
117 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
118 @Override
119 public void onReceive(Context context, Intent intent) {
120 Slog.d(TAG, "Receieved: " + intent.getAction());
121 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
122 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
123 if (DEBUG) {
124 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
125 }
126 cancelJobsForUid(uidRemoved);
127 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
128 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
129 if (DEBUG) {
130 Slog.d(TAG, "Removing jobs for user: " + userId);
131 }
132 cancelJobsForUser(userId);
133 }
134 }
135 };
136
137 /**
138 * Entry point from client to schedule the provided job.
139 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
140 * @param job JobInfo object containing execution parameters
141 * @param uId The package identifier of the application this job is for.
142 * @param canPersistJob Whether or not the client has the appropriate permissions for
143 * persisting this job.
144 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
145 */
146 public int schedule(JobInfo job, int uId, boolean canPersistJob) {
147 JobStatus jobStatus = new JobStatus(job, uId, canPersistJob);
148 cancelJob(uId, job.getId());
149 startTrackingJob(jobStatus);
150 return JobScheduler.RESULT_SUCCESS;
151 }
152
153 public List<JobInfo> getPendingJobs(int uid) {
154 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
155 synchronized (mJobs) {
156 for (JobStatus job : mJobs.getJobs()) {
157 if (job.getUid() == uid) {
158 outList.add(job.getJob());
159 }
160 }
161 }
162 return outList;
163 }
164
165 private void cancelJobsForUser(int userHandle) {
166 synchronized (mJobs) {
167 List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
168 for (JobStatus toRemove : jobsForUser) {
169 if (DEBUG) {
170 Slog.d(TAG, "Cancelling: " + toRemove);
171 }
172 cancelJobLocked(toRemove);
173 }
174 }
175 }
176
177 /**
178 * Entry point from client to cancel all jobs originating from their uid.
179 * This will remove the job from the master list, and cancel the job if it was staged for
180 * execution or being executed.
181 * @param uid To check against for removal of a job.
182 */
183 public void cancelJobsForUid(int uid) {
184 // Remove from master list.
185 synchronized (mJobs) {
186 List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
187 for (JobStatus toRemove : jobsForUid) {
188 if (DEBUG) {
189 Slog.d(TAG, "Cancelling: " + toRemove);
190 }
191 cancelJobLocked(toRemove);
192 }
193 }
194 }
195
196 /**
197 * Entry point from client to cancel the job corresponding to the jobId provided.
198 * This will remove the job from the master list, and cancel the job if it was staged for
199 * execution or being executed.
200 * @param uid Uid of the calling client.
201 * @param jobId Id of the job, provided at schedule-time.
202 */
203 public void cancelJob(int uid, int jobId) {
204 JobStatus toCancel;
205 synchronized (mJobs) {
206 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
207 if (toCancel != null) {
208 cancelJobLocked(toCancel);
209 }
210 }
211 }
212
213 private void cancelJobLocked(JobStatus cancelled) {
214 // Remove from store.
215 stopTrackingJob(cancelled);
216 // Remove from pending queue.
217 mPendingJobs.remove(cancelled);
218 // Cancel if running.
219 stopJobOnServiceContextLocked(cancelled);
220 }
221
222 /**
223 * Initializes the system service.
224 * <p>
225 * Subclasses must define a single argument constructor that accepts the context
226 * and passes it to super.
227 * </p>
228 *
229 * @param context The system server context.
230 */
231 public JobSchedulerService(Context context) {
232 super(context);
233 // Create the controllers.
234 mControllers = new LinkedList<StateController>();
235 mControllers.add(ConnectivityController.get(this));
236 mControllers.add(TimeController.get(this));
237 mControllers.add(IdleController.get(this));
238 mControllers.add(BatteryController.get(this));
239
240 mHandler = new JobHandler(context.getMainLooper());
241 mJobSchedulerStub = new JobSchedulerStub();
242 // Create the "runners".
243 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
244 mActiveServices.add(
245 new JobServiceContext(this, context.getMainLooper()));
246 }
247 mJobs = JobStore.initAndGet(this);
248 }
249
250 @Override
251 public void onStart() {
252 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
253 }
254
255 @Override
256 public void onBootPhase(int phase) {
257 if (PHASE_SYSTEM_SERVICES_READY == phase) {
258 // Register br for package removals and user removals.
259 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
260 filter.addDataScheme("package");
261 getContext().registerReceiverAsUser(
262 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
263 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
264 getContext().registerReceiverAsUser(
265 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
266 }
267 }
268
269 /**
270 * Called when we have a job status object that we need to insert in our
271 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
272 * about.
273 */
274 private void startTrackingJob(JobStatus jobStatus) {
275 boolean update;
276 synchronized (mJobs) {
277 update = mJobs.add(jobStatus);
278 }
279 for (StateController controller : mControllers) {
280 if (update) {
281 controller.maybeStopTrackingJob(jobStatus);
282 }
283 controller.maybeStartTrackingJob(jobStatus);
284 }
285 }
286
287 /**
288 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
289 * object removed.
290 */
291 private boolean stopTrackingJob(JobStatus jobStatus) {
292 boolean removed;
293 synchronized (mJobs) {
294 // Remove from store as well as controllers.
295 removed = mJobs.remove(jobStatus);
296 }
297 if (removed) {
298 for (StateController controller : mControllers) {
299 controller.maybeStopTrackingJob(jobStatus);
300 }
301 }
302 return removed;
303 }
304
305 private boolean stopJobOnServiceContextLocked(JobStatus job) {
306 for (JobServiceContext jsc : mActiveServices) {
307 final JobStatus executing = jsc.getRunningJob();
308 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
309 jsc.cancelExecutingJob();
310 return true;
311 }
312 }
313 return false;
314 }
315
316 /**
317 * @param job JobStatus we are querying against.
318 * @return Whether or not the job represented by the status object is currently being run or
319 * is pending.
320 */
321 private boolean isCurrentlyActiveLocked(JobStatus job) {
322 for (JobServiceContext serviceContext : mActiveServices) {
323 final JobStatus running = serviceContext.getRunningJob();
324 if (running != null && running.matches(job.getUid(), job.getJobId())) {
325 return true;
326 }
327 }
328 return false;
329 }
330
331 /**
332 * A job is rescheduled with exponential back-off if the client requests this from their
333 * execution logic.
334 * A caveat is for idle-mode jobs, for which the idle-mode constraint will usurp the
335 * timeliness of the reschedule. For an idle-mode job, no deadline is given.
336 * @param failureToReschedule Provided job status that we will reschedule.
337 * @return A newly instantiated JobStatus with the same constraints as the last job except
338 * with adjusted timing constraints.
339 */
340 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
341 final long elapsedNowMillis = SystemClock.elapsedRealtime();
342 final JobInfo job = failureToReschedule.getJob();
343
344 final long initialBackoffMillis = job.getInitialBackoffMillis();
345 final int backoffAttempt = failureToReschedule.getNumFailures() + 1;
346 long newEarliestRuntimeElapsed = elapsedNowMillis;
347
348 switch (job.getBackoffPolicy()) {
349 case JobInfo.BackoffPolicy.LINEAR:
350 newEarliestRuntimeElapsed += initialBackoffMillis * backoffAttempt;
351 break;
352 default:
353 if (DEBUG) {
354 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
355 }
356 case JobInfo.BackoffPolicy.EXPONENTIAL:
357 newEarliestRuntimeElapsed +=
358 Math.pow(initialBackoffMillis * 0.001, backoffAttempt) * 1000;
359 break;
360 }
361 newEarliestRuntimeElapsed =
362 Math.min(newEarliestRuntimeElapsed, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
363 return new JobStatus(failureToReschedule, newEarliestRuntimeElapsed,
364 JobStatus.NO_LATEST_RUNTIME, backoffAttempt);
365 }
366
367 /**
368 * Called after a periodic has executed so we can to re-add it. We take the last execution time
369 * of the job to be the time of completion (i.e. the time at which this function is called).
370 * This could be inaccurate b/c the job can run for as long as
371 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
372 * to underscheduling at least, rather than if we had taken the last execution time to be the
373 * start of the execution.
374 * @return A new job representing the execution criteria for this instantiation of the
375 * recurring job.
376 */
377 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
378 final long elapsedNow = SystemClock.elapsedRealtime();
379 // Compute how much of the period is remaining.
380 long runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0);
381 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
382 long period = periodicToReschedule.getJob().getIntervalMillis();
383 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
384
385 if (DEBUG) {
386 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
387 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
388 }
389 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
390 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
391 }
392
393 // JobCompletedListener implementations.
394
395 /**
396 * A job just finished executing. We fetch the
397 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
398 * whether we want to reschedule we readd it to the controllers.
399 * @param jobStatus Completed job.
400 * @param needsReschedule Whether the implementing class should reschedule this job.
401 */
402 @Override
403 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
404 if (DEBUG) {
405 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
406 }
407 if (!stopTrackingJob(jobStatus)) {
408 if (DEBUG) {
409 Slog.e(TAG, "Error removing job: could not find job to remove. Was job " +
410 "removed while executing?");
411 }
412 return;
413 }
414 if (needsReschedule) {
415 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
416 startTrackingJob(rescheduled);
417 } else if (jobStatus.getJob().isPeriodic()) {
418 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
419 startTrackingJob(rescheduledPeriodic);
420 }
421 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
422 }
423
424 // StateChangedListener implementations.
425
426 /**
427 * Off-board work to our handler thread as quickly as possible, b/c this call is probably being
428 * made on the main thread.
429 * For now this takes the job and if it's ready to run it will run it. In future we might not
430 * provide the job, so that the StateChangedListener has to run through its list of jobs to
431 * see which are ready. This will further decouple the controllers from the execution logic.
432 */
433 @Override
434 public void onControllerStateChanged() {
435 // Post a message to to run through the list of jobs and start/stop any that are eligible.
436 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
437 }
438
439 @Override
440 public void onRunJobNow(JobStatus jobStatus) {
441 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
442 }
443
444 /**
445 * Disk I/O is finished, take the list of jobs we read from disk and add them to our
446 * {@link JobStore}.
447 * This is run on the {@link com.android.server.IoThread} instance, which is a separate thread,
448 * and is called once at boot.
449 */
450 @Override
451 public void onJobMapReadFinished(List<JobStatus> jobs) {
452 synchronized (mJobs) {
453 for (JobStatus js : jobs) {
454 if (mJobs.containsJobIdForUid(js.getJobId(), js.getUid())) {
455 // An app with BOOT_COMPLETED *might* have decided to reschedule their job, in
456 // the same amount of time it took us to read it from disk. If this is the case
457 // we leave it be.
458 continue;
459 }
460 startTrackingJob(js);
461 }
462 }
463 }
464
465 private class JobHandler extends Handler {
466
467 public JobHandler(Looper looper) {
468 super(looper);
469 }
470
471 @Override
472 public void handleMessage(Message message) {
473 switch (message.what) {
474 case MSG_JOB_EXPIRED:
475 synchronized (mJobs) {
476 JobStatus runNow = (JobStatus) message.obj;
477 if (!mPendingJobs.contains(runNow)) {
478 mPendingJobs.add(runNow);
479 }
480 }
481 queueReadyJobsForExecutionH();
482 break;
483 case MSG_CHECK_JOB:
484 // Check the list of jobs and run some of them if we feel inclined.
485 maybeQueueReadyJobsForExecutionH();
486 break;
487 }
488 maybeRunPendingJobsH();
489 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
490 removeMessages(MSG_CHECK_JOB);
491 }
492
493 /**
494 * Run through list of jobs and execute all possible - at least one is expired so we do
495 * as many as we can.
496 */
497 private void queueReadyJobsForExecutionH() {
498 synchronized (mJobs) {
499 for (JobStatus job : mJobs.getJobs()) {
500 if (isReadyToBeExecutedLocked(job)) {
501 mPendingJobs.add(job);
502 } else if (isReadyToBeCancelledLocked(job)) {
503 stopJobOnServiceContextLocked(job);
504 }
505 }
506 }
507 }
508
509 /**
510 * The state of at least one job has changed. Here is where we could enforce various
511 * policies on when we want to execute jobs.
512 * Right now the policy is such:
513 * If >1 of the ready jobs is idle mode we send all of them off
514 * if more than 2 network connectivity jobs are ready we send them all off.
515 * If more than 4 jobs total are ready we send them all off.
516 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
517 */
518 private void maybeQueueReadyJobsForExecutionH() {
519 synchronized (mJobs) {
520 int idleCount = 0;
521 int backoffCount = 0;
522 int connectivityCount = 0;
523 List<JobStatus> runnableJobs = new ArrayList<JobStatus>();
524 for (JobStatus job : mJobs.getJobs()) {
525 if (isReadyToBeExecutedLocked(job)) {
526 if (job.getNumFailures() > 0) {
527 backoffCount++;
528 }
529 if (job.hasIdleConstraint()) {
530 idleCount++;
531 }
532 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
533 connectivityCount++;
534 }
535 runnableJobs.add(job);
536 } else if (isReadyToBeCancelledLocked(job)) {
537 stopJobOnServiceContextLocked(job);
538 }
539 }
540 if (backoffCount > 0 || idleCount >= MIN_IDLE_COUNT ||
541 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
542 runnableJobs.size() >= MIN_READY_JOBS_COUNT) {
543 for (JobStatus job : runnableJobs) {
544 mPendingJobs.add(job);
545 }
546 }
547 }
548 }
549
550 /**
551 * Criteria for moving a job into the pending queue:
552 * - It's ready.
553 * - It's not pending.
554 * - It's not already running on a JSC.
555 */
556 private boolean isReadyToBeExecutedLocked(JobStatus job) {
557 return job.isReady() && !mPendingJobs.contains(job) && !isCurrentlyActiveLocked(job);
558 }
559
560 /**
561 * Criteria for cancelling an active job:
562 * - It's not ready
563 * - It's running on a JSC.
564 */
565 private boolean isReadyToBeCancelledLocked(JobStatus job) {
566 return !job.isReady() && isCurrentlyActiveLocked(job);
567 }
568
569 /**
570 * Reconcile jobs in the pending queue against available execution contexts.
571 * A controller can force a job into the pending queue even if it's already running, but
572 * here is where we decide whether to actually execute it.
573 */
574 private void maybeRunPendingJobsH() {
575 synchronized (mJobs) {
576 Iterator<JobStatus> it = mPendingJobs.iterator();
577 while (it.hasNext()) {
578 JobStatus nextPending = it.next();
579 JobServiceContext availableContext = null;
580 for (JobServiceContext jsc : mActiveServices) {
581 final JobStatus running = jsc.getRunningJob();
582 if (running != null && running.matches(nextPending.getUid(),
583 nextPending.getJobId())) {
584 // Already running this tId for this uId, skip.
585 availableContext = null;
586 break;
587 }
588 if (jsc.isAvailable()) {
589 availableContext = jsc;
590 }
591 }
592 if (availableContext != null) {
593 if (!availableContext.executeRunnableJob(nextPending)) {
594 if (DEBUG) {
595 Slog.d(TAG, "Error executing " + nextPending);
596 }
597 mJobs.remove(nextPending);
598 }
599 it.remove();
600 }
601 }
602 }
603 }
604 }
605
606 /**
607 * Binder stub trampoline implementation
608 */
609 final class JobSchedulerStub extends IJobScheduler.Stub {
610 /** Cache determination of whether a given app can persist jobs
611 * key is uid of the calling app; value is undetermined/true/false
612 */
613 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
614
615 // Enforce that only the app itself (or shared uid participant) can schedule a
616 // job that runs one of the app's services, as well as verifying that the
617 // named service properly requires the BIND_JOB_SERVICE permission
618 private void enforceValidJobRequest(int uid, JobInfo job) {
619 final PackageManager pm = getContext().getPackageManager();
620 final ComponentName service = job.getService();
621 try {
622 ServiceInfo si = pm.getServiceInfo(service, 0);
623 if (si.applicationInfo.uid != uid) {
624 throw new IllegalArgumentException("uid " + uid +
625 " cannot schedule job in " + service.getPackageName());
626 }
627 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
628 throw new IllegalArgumentException("Scheduled service " + service
629 + " does not require android.permission.BIND_JOB_SERVICE permission");
630 }
631 } catch (NameNotFoundException e) {
632 throw new IllegalArgumentException("No such service: " + service);
633 }
634 }
635
636 private boolean canPersistJobs(int pid, int uid) {
637 // If we get this far we're good to go; all we need to do now is check
638 // whether the app is allowed to persist its scheduled work.
639 final boolean canPersist;
640 synchronized (mPersistCache) {
641 Boolean cached = mPersistCache.get(uid);
642 if (cached != null) {
643 canPersist = cached.booleanValue();
644 } else {
645 // Persisting jobs is tantamount to running at boot, so we permit
646 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
647 // permission
648 int result = getContext().checkPermission(
649 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
650 canPersist = (result == PackageManager.PERMISSION_GRANTED);
651 mPersistCache.put(uid, canPersist);
652 }
653 }
654 return canPersist;
655 }
656
657 // IJobScheduler implementation
658 @Override
659 public int schedule(JobInfo job) throws RemoteException {
660 if (DEBUG) {
661 Slog.d(TAG, "Scheduling job: " + job);
662 }
663 final int pid = Binder.getCallingPid();
664 final int uid = Binder.getCallingUid();
665
666 enforceValidJobRequest(uid, job);
667 final boolean canPersist = canPersistJobs(pid, uid);
668
669 long ident = Binder.clearCallingIdentity();
670 try {
671 return JobSchedulerService.this.schedule(job, uid, canPersist);
672 } finally {
673 Binder.restoreCallingIdentity(ident);
674 }
675 }
676
677 @Override
678 public List<JobInfo> getAllPendingJobs() throws RemoteException {
679 final int uid = Binder.getCallingUid();
680
681 long ident = Binder.clearCallingIdentity();
682 try {
683 return JobSchedulerService.this.getPendingJobs(uid);
684 } finally {
685 Binder.restoreCallingIdentity(ident);
686 }
687 }
688
689 @Override
690 public void cancelAll() throws RemoteException {
691 final int uid = Binder.getCallingUid();
692
693 long ident = Binder.clearCallingIdentity();
694 try {
695 JobSchedulerService.this.cancelJobsForUid(uid);
696 } finally {
697 Binder.restoreCallingIdentity(ident);
698 }
699 }
700
701 @Override
702 public void cancel(int jobId) throws RemoteException {
703 final int uid = Binder.getCallingUid();
704
705 long ident = Binder.clearCallingIdentity();
706 try {
707 JobSchedulerService.this.cancelJob(uid, jobId);
708 } finally {
709 Binder.restoreCallingIdentity(ident);
710 }
711 }
712
713 /**
714 * "dumpsys" infrastructure
715 */
716 @Override
717 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
718 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
719
720 long identityToken = Binder.clearCallingIdentity();
721 try {
722 JobSchedulerService.this.dumpInternal(pw);
723 } finally {
724 Binder.restoreCallingIdentity(identityToken);
725 }
726 }
727 };
728
729 void dumpInternal(PrintWriter pw) {
730 synchronized (mJobs) {
731 pw.println("Registered jobs:");
732 if (mJobs.size() > 0) {
733 for (JobStatus job : mJobs.getJobs()) {
734 job.dump(pw, " ");
735 }
736 } else {
737 pw.println();
738 pw.println("No jobs scheduled.");
739 }
740 for (StateController controller : mControllers) {
741 pw.println();
742 controller.dumpControllerState(pw);
743 }
744 pw.println();
745 pw.println("Pending");
746 for (JobStatus jobStatus : mPendingJobs) {
747 pw.println(jobStatus.hashCode());
748 }
749 pw.println();
750 pw.println("Active jobs:");
751 for (JobServiceContext jsc : mActiveServices) {
752 if (jsc.isAvailable()) {
753 continue;
754 } else {
755 pw.println(jsc.getRunningJob().hashCode() + " for: " +
756 (SystemClock.elapsedRealtime()
757 - jsc.getExecutionStartTimeElapsed())/1000 + "s " +
758 "timeout: " + jsc.getTimeoutElapsed());
759 }
760 }
761 }
762 pw.println();
763 }
764}