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