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