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