blob: 9ac90dca1d2ccd05731e4d001bde27b935a467e9 [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.job;
18
19import java.io.FileDescriptor;
20import java.io.PrintWriter;
21import java.util.ArrayList;
22import java.util.Iterator;
23import java.util.List;
24
Christopher Tate5568f542014-06-18 13:53:31 -070025import android.app.AppGlobals;
Christopher Tate7060b042014-06-09 19:50:00 -070026import 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;
Christopher Tate5568f542014-06-18 13:53:31 -070035import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070036import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070037import android.content.pm.ServiceInfo;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070038import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070039import android.os.Binder;
40import android.os.Handler;
41import android.os.Looper;
42import android.os.Message;
43import android.os.RemoteException;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070044import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070045import android.os.SystemClock;
46import android.os.UserHandle;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070047import android.util.ArraySet;
Christopher Tate7060b042014-06-09 19:50:00 -070048import android.util.Slog;
49import android.util.SparseArray;
50
Dianne Hackbornfdb19562014-07-11 16:03:36 -070051import com.android.internal.app.IBatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070052import 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
Christopher Tate7060b042014-06-09 19:50:00 -070059/**
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
Matthew Williams01ac45b2014-07-22 20:44:12 -070072 implements StateChangedListener, JobCompletedListener {
Christopher Tate7060b042014-06-09 19:50:00 -070073 // TODO: Switch this off for final version.
74 static final boolean DEBUG = true;
75 /** The number of concurrent jobs we run at one time. */
76 private static final int MAX_JOB_CONTEXTS_COUNT = 3;
77 static final String TAG = "JobManagerService";
78 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070079 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -070080
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 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070089 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -070090 /**
91 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
92 * things early.
93 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070094 static final int MIN_CONNECTIVITY_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -070095 /**
96 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
97 * some work early.
98 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070099 static final int MIN_READY_JOBS_COUNT = 4;
Christopher Tate7060b042014-06-09 19:50:00 -0700100
101 /**
102 * Track Services that have currently active or pending jobs. The index is provided by
103 * {@link JobStatus#getServiceToken()}
104 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700105 final List<JobServiceContext> mActiveServices = new ArrayList<JobServiceContext>();
Christopher Tate7060b042014-06-09 19:50:00 -0700106 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700107 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700108 /**
109 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
110 * when ready to execute them.
111 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700112 final ArrayList<JobStatus> mPendingJobs = new ArrayList<JobStatus>();
Christopher Tate7060b042014-06-09 19:50:00 -0700113
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700114 final JobHandler mHandler;
115 final JobSchedulerStub mJobSchedulerStub;
116
117 IBatteryStats mBatteryStats;
118
119 /**
120 * Set to true once we are allowed to run third party apps.
121 */
122 boolean mReadyToRock;
123
Christopher Tate7060b042014-06-09 19:50:00 -0700124 /**
125 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
126 * still clean up. On reinstall the package will have a new uid.
127 */
128 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
129 @Override
130 public void onReceive(Context context, Intent intent) {
131 Slog.d(TAG, "Receieved: " + intent.getAction());
132 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
133 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
134 if (DEBUG) {
135 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
136 }
137 cancelJobsForUid(uidRemoved);
138 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
139 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
140 if (DEBUG) {
141 Slog.d(TAG, "Removing jobs for user: " + userId);
142 }
143 cancelJobsForUser(userId);
144 }
145 }
146 };
147
148 /**
149 * Entry point from client to schedule the provided job.
150 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
151 * @param job JobInfo object containing execution parameters
152 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700153 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
154 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700155 public int schedule(JobInfo job, int uId) {
156 JobStatus jobStatus = new JobStatus(job, uId);
Christopher Tate7060b042014-06-09 19:50:00 -0700157 cancelJob(uId, job.getId());
158 startTrackingJob(jobStatus);
159 return JobScheduler.RESULT_SUCCESS;
160 }
161
162 public List<JobInfo> getPendingJobs(int uid) {
163 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
164 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700165 ArraySet<JobStatus> jobs = mJobs.getJobs();
166 for (int i=0; i<jobs.size(); i++) {
167 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700168 if (job.getUid() == uid) {
169 outList.add(job.getJob());
170 }
171 }
172 }
173 return outList;
174 }
175
176 private void cancelJobsForUser(int userHandle) {
177 synchronized (mJobs) {
178 List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700179 for (int i=0; i<jobsForUser.size(); i++) {
180 JobStatus toRemove = jobsForUser.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700181 if (DEBUG) {
182 Slog.d(TAG, "Cancelling: " + toRemove);
183 }
184 cancelJobLocked(toRemove);
185 }
186 }
187 }
188
189 /**
190 * Entry point from client to cancel all jobs originating from their uid.
191 * This will remove the job from the master list, and cancel the job if it was staged for
192 * execution or being executed.
193 * @param uid To check against for removal of a job.
194 */
195 public void cancelJobsForUid(int uid) {
196 // Remove from master list.
197 synchronized (mJobs) {
198 List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700199 for (int i=0; i<jobsForUid.size(); i++) {
200 JobStatus toRemove = jobsForUid.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700201 if (DEBUG) {
202 Slog.d(TAG, "Cancelling: " + toRemove);
203 }
204 cancelJobLocked(toRemove);
205 }
206 }
207 }
208
209 /**
210 * Entry point from client to cancel the job corresponding to the jobId provided.
211 * This will remove the job from the master list, and cancel the job if it was staged for
212 * execution or being executed.
213 * @param uid Uid of the calling client.
214 * @param jobId Id of the job, provided at schedule-time.
215 */
216 public void cancelJob(int uid, int jobId) {
217 JobStatus toCancel;
218 synchronized (mJobs) {
219 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
220 if (toCancel != null) {
221 cancelJobLocked(toCancel);
222 }
223 }
224 }
225
226 private void cancelJobLocked(JobStatus cancelled) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700227 if (DEBUG) {
228 Slog.d(TAG, "Cancelling: " + cancelled);
229 }
Christopher Tate7060b042014-06-09 19:50:00 -0700230 // Remove from store.
231 stopTrackingJob(cancelled);
232 // Remove from pending queue.
233 mPendingJobs.remove(cancelled);
234 // Cancel if running.
235 stopJobOnServiceContextLocked(cancelled);
236 }
237
238 /**
239 * Initializes the system service.
240 * <p>
241 * Subclasses must define a single argument constructor that accepts the context
242 * and passes it to super.
243 * </p>
244 *
245 * @param context The system server context.
246 */
247 public JobSchedulerService(Context context) {
248 super(context);
249 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700250 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700251 mControllers.add(ConnectivityController.get(this));
252 mControllers.add(TimeController.get(this));
253 mControllers.add(IdleController.get(this));
254 mControllers.add(BatteryController.get(this));
255
256 mHandler = new JobHandler(context.getMainLooper());
257 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700258 mJobs = JobStore.initAndGet(this);
259 }
260
261 @Override
262 public void onStart() {
263 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
264 }
265
266 @Override
267 public void onBootPhase(int phase) {
268 if (PHASE_SYSTEM_SERVICES_READY == phase) {
269 // Register br for package removals and user removals.
270 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
271 filter.addDataScheme("package");
272 getContext().registerReceiverAsUser(
273 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
274 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
275 getContext().registerReceiverAsUser(
276 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700277 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
278 synchronized (mJobs) {
279 // Let's go!
280 mReadyToRock = true;
281 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
282 BatteryStats.SERVICE_NAME));
283 // Create the "runners".
284 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
285 mActiveServices.add(
286 new JobServiceContext(this, mBatteryStats,
287 getContext().getMainLooper()));
288 }
289 // Attach jobs to their controllers.
290 ArraySet<JobStatus> jobs = mJobs.getJobs();
291 for (int i=0; i<jobs.size(); i++) {
292 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700293 for (int controller=0; controller<mControllers.size(); controller++) {
294 mControllers.get(controller).maybeStartTrackingJob(job);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700295 }
296 }
297 // GO GO GO!
298 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
299 }
Christopher Tate7060b042014-06-09 19:50:00 -0700300 }
301 }
302
303 /**
304 * Called when we have a job status object that we need to insert in our
305 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
306 * about.
307 */
308 private void startTrackingJob(JobStatus jobStatus) {
309 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700310 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700311 synchronized (mJobs) {
312 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700313 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700314 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700315 if (rocking) {
316 for (int i=0; i<mControllers.size(); i++) {
317 StateController controller = mControllers.get(i);
318 if (update) {
319 controller.maybeStopTrackingJob(jobStatus);
320 }
321 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700322 }
Christopher Tate7060b042014-06-09 19:50:00 -0700323 }
324 }
325
326 /**
327 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
328 * object removed.
329 */
330 private boolean stopTrackingJob(JobStatus jobStatus) {
331 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700332 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700333 synchronized (mJobs) {
334 // Remove from store as well as controllers.
335 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700336 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700337 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700338 if (removed && rocking) {
339 for (int i=0; i<mControllers.size(); i++) {
340 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700341 controller.maybeStopTrackingJob(jobStatus);
342 }
343 }
344 return removed;
345 }
346
347 private boolean stopJobOnServiceContextLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700348 for (int i=0; i<mActiveServices.size(); i++) {
349 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700350 final JobStatus executing = jsc.getRunningJob();
351 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
352 jsc.cancelExecutingJob();
353 return true;
354 }
355 }
356 return false;
357 }
358
359 /**
360 * @param job JobStatus we are querying against.
361 * @return Whether or not the job represented by the status object is currently being run or
362 * is pending.
363 */
364 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700365 for (int i=0; i<mActiveServices.size(); i++) {
366 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700367 final JobStatus running = serviceContext.getRunningJob();
368 if (running != null && running.matches(job.getUid(), job.getJobId())) {
369 return true;
370 }
371 }
372 return false;
373 }
374
375 /**
376 * A job is rescheduled with exponential back-off if the client requests this from their
377 * execution logic.
378 * A caveat is for idle-mode jobs, for which the idle-mode constraint will usurp the
379 * timeliness of the reschedule. For an idle-mode job, no deadline is given.
380 * @param failureToReschedule Provided job status that we will reschedule.
381 * @return A newly instantiated JobStatus with the same constraints as the last job except
382 * with adjusted timing constraints.
383 */
384 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
385 final long elapsedNowMillis = SystemClock.elapsedRealtime();
386 final JobInfo job = failureToReschedule.getJob();
387
388 final long initialBackoffMillis = job.getInitialBackoffMillis();
389 final int backoffAttempt = failureToReschedule.getNumFailures() + 1;
390 long newEarliestRuntimeElapsed = elapsedNowMillis;
391
392 switch (job.getBackoffPolicy()) {
393 case JobInfo.BackoffPolicy.LINEAR:
394 newEarliestRuntimeElapsed += initialBackoffMillis * backoffAttempt;
395 break;
396 default:
397 if (DEBUG) {
398 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
399 }
400 case JobInfo.BackoffPolicy.EXPONENTIAL:
401 newEarliestRuntimeElapsed +=
402 Math.pow(initialBackoffMillis * 0.001, backoffAttempt) * 1000;
403 break;
404 }
405 newEarliestRuntimeElapsed =
406 Math.min(newEarliestRuntimeElapsed, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
407 return new JobStatus(failureToReschedule, newEarliestRuntimeElapsed,
408 JobStatus.NO_LATEST_RUNTIME, backoffAttempt);
409 }
410
411 /**
412 * Called after a periodic has executed so we can to re-add it. We take the last execution time
413 * of the job to be the time of completion (i.e. the time at which this function is called).
414 * This could be inaccurate b/c the job can run for as long as
415 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
416 * to underscheduling at least, rather than if we had taken the last execution time to be the
417 * start of the execution.
418 * @return A new job representing the execution criteria for this instantiation of the
419 * recurring job.
420 */
421 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
422 final long elapsedNow = SystemClock.elapsedRealtime();
423 // Compute how much of the period is remaining.
424 long runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0);
425 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
426 long period = periodicToReschedule.getJob().getIntervalMillis();
427 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
428
429 if (DEBUG) {
430 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
431 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
432 }
433 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
434 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
435 }
436
437 // JobCompletedListener implementations.
438
439 /**
440 * A job just finished executing. We fetch the
441 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
442 * whether we want to reschedule we readd it to the controllers.
443 * @param jobStatus Completed job.
444 * @param needsReschedule Whether the implementing class should reschedule this job.
445 */
446 @Override
447 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
448 if (DEBUG) {
449 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
450 }
451 if (!stopTrackingJob(jobStatus)) {
452 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700453 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700454 }
455 return;
456 }
457 if (needsReschedule) {
458 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
459 startTrackingJob(rescheduled);
460 } else if (jobStatus.getJob().isPeriodic()) {
461 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
462 startTrackingJob(rescheduledPeriodic);
463 }
464 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
465 }
466
467 // StateChangedListener implementations.
468
469 /**
470 * Off-board work to our handler thread as quickly as possible, b/c this call is probably being
471 * made on the main thread.
472 * For now this takes the job and if it's ready to run it will run it. In future we might not
473 * provide the job, so that the StateChangedListener has to run through its list of jobs to
474 * see which are ready. This will further decouple the controllers from the execution logic.
475 */
476 @Override
477 public void onControllerStateChanged() {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700478 synchronized (mJobs) {
479 if (mReadyToRock) {
480 // Post a message to to run through the list of jobs and start/stop any that
481 // are eligible.
482 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
483 }
484 }
Christopher Tate7060b042014-06-09 19:50:00 -0700485 }
486
487 @Override
488 public void onRunJobNow(JobStatus jobStatus) {
489 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
490 }
491
Christopher Tate7060b042014-06-09 19:50:00 -0700492 private class JobHandler extends Handler {
493
494 public JobHandler(Looper looper) {
495 super(looper);
496 }
497
498 @Override
499 public void handleMessage(Message message) {
500 switch (message.what) {
501 case MSG_JOB_EXPIRED:
502 synchronized (mJobs) {
503 JobStatus runNow = (JobStatus) message.obj;
504 if (!mPendingJobs.contains(runNow)) {
505 mPendingJobs.add(runNow);
506 }
507 }
508 queueReadyJobsForExecutionH();
509 break;
510 case MSG_CHECK_JOB:
511 // Check the list of jobs and run some of them if we feel inclined.
512 maybeQueueReadyJobsForExecutionH();
513 break;
514 }
515 maybeRunPendingJobsH();
516 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
517 removeMessages(MSG_CHECK_JOB);
518 }
519
520 /**
521 * Run through list of jobs and execute all possible - at least one is expired so we do
522 * as many as we can.
523 */
524 private void queueReadyJobsForExecutionH() {
525 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700526 ArraySet<JobStatus> jobs = mJobs.getJobs();
527 for (int i=0; i<jobs.size(); i++) {
528 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700529 if (isReadyToBeExecutedLocked(job)) {
530 mPendingJobs.add(job);
531 } else if (isReadyToBeCancelledLocked(job)) {
532 stopJobOnServiceContextLocked(job);
533 }
534 }
535 }
536 }
537
538 /**
539 * The state of at least one job has changed. Here is where we could enforce various
540 * policies on when we want to execute jobs.
541 * Right now the policy is such:
542 * If >1 of the ready jobs is idle mode we send all of them off
543 * if more than 2 network connectivity jobs are ready we send them all off.
544 * If more than 4 jobs total are ready we send them all off.
545 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
546 */
547 private void maybeQueueReadyJobsForExecutionH() {
548 synchronized (mJobs) {
549 int idleCount = 0;
550 int backoffCount = 0;
551 int connectivityCount = 0;
552 List<JobStatus> runnableJobs = new ArrayList<JobStatus>();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700553 ArraySet<JobStatus> jobs = mJobs.getJobs();
554 for (int i=0; i<jobs.size(); i++) {
555 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700556 if (isReadyToBeExecutedLocked(job)) {
557 if (job.getNumFailures() > 0) {
558 backoffCount++;
559 }
560 if (job.hasIdleConstraint()) {
561 idleCount++;
562 }
563 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
564 connectivityCount++;
565 }
566 runnableJobs.add(job);
567 } else if (isReadyToBeCancelledLocked(job)) {
568 stopJobOnServiceContextLocked(job);
569 }
570 }
571 if (backoffCount > 0 || idleCount >= MIN_IDLE_COUNT ||
572 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
573 runnableJobs.size() >= MIN_READY_JOBS_COUNT) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700574 for (int i=0; i<runnableJobs.size(); i++) {
575 mPendingJobs.add(runnableJobs.get(i));
Christopher Tate7060b042014-06-09 19:50:00 -0700576 }
577 }
578 }
579 }
580
581 /**
582 * Criteria for moving a job into the pending queue:
583 * - It's ready.
584 * - It's not pending.
585 * - It's not already running on a JSC.
586 */
587 private boolean isReadyToBeExecutedLocked(JobStatus job) {
588 return job.isReady() && !mPendingJobs.contains(job) && !isCurrentlyActiveLocked(job);
589 }
590
591 /**
592 * Criteria for cancelling an active job:
593 * - It's not ready
594 * - It's running on a JSC.
595 */
596 private boolean isReadyToBeCancelledLocked(JobStatus job) {
597 return !job.isReady() && isCurrentlyActiveLocked(job);
598 }
599
600 /**
601 * Reconcile jobs in the pending queue against available execution contexts.
602 * A controller can force a job into the pending queue even if it's already running, but
603 * here is where we decide whether to actually execute it.
604 */
605 private void maybeRunPendingJobsH() {
606 synchronized (mJobs) {
607 Iterator<JobStatus> it = mPendingJobs.iterator();
608 while (it.hasNext()) {
609 JobStatus nextPending = it.next();
610 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700611 for (int i=0; i<mActiveServices.size(); i++) {
612 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700613 final JobStatus running = jsc.getRunningJob();
614 if (running != null && running.matches(nextPending.getUid(),
615 nextPending.getJobId())) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700616 // Already running this job for this uId, skip.
Christopher Tate7060b042014-06-09 19:50:00 -0700617 availableContext = null;
618 break;
619 }
620 if (jsc.isAvailable()) {
621 availableContext = jsc;
622 }
623 }
624 if (availableContext != null) {
625 if (!availableContext.executeRunnableJob(nextPending)) {
626 if (DEBUG) {
627 Slog.d(TAG, "Error executing " + nextPending);
628 }
629 mJobs.remove(nextPending);
630 }
631 it.remove();
632 }
633 }
634 }
635 }
636 }
637
638 /**
639 * Binder stub trampoline implementation
640 */
641 final class JobSchedulerStub extends IJobScheduler.Stub {
642 /** Cache determination of whether a given app can persist jobs
643 * key is uid of the calling app; value is undetermined/true/false
644 */
645 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
646
647 // Enforce that only the app itself (or shared uid participant) can schedule a
648 // job that runs one of the app's services, as well as verifying that the
649 // named service properly requires the BIND_JOB_SERVICE permission
650 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700651 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700652 final ComponentName service = job.getService();
653 try {
Christopher Tate5568f542014-06-18 13:53:31 -0700654 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid));
655 if (si == null) {
656 throw new IllegalArgumentException("No such service " + service);
657 }
Christopher Tate7060b042014-06-09 19:50:00 -0700658 if (si.applicationInfo.uid != uid) {
659 throw new IllegalArgumentException("uid " + uid +
660 " cannot schedule job in " + service.getPackageName());
661 }
662 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
663 throw new IllegalArgumentException("Scheduled service " + service
664 + " does not require android.permission.BIND_JOB_SERVICE permission");
665 }
Christopher Tate5568f542014-06-18 13:53:31 -0700666 } catch (RemoteException e) {
667 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700668 }
669 }
670
671 private boolean canPersistJobs(int pid, int uid) {
672 // If we get this far we're good to go; all we need to do now is check
673 // whether the app is allowed to persist its scheduled work.
674 final boolean canPersist;
675 synchronized (mPersistCache) {
676 Boolean cached = mPersistCache.get(uid);
677 if (cached != null) {
678 canPersist = cached.booleanValue();
679 } else {
680 // Persisting jobs is tantamount to running at boot, so we permit
681 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
682 // permission
683 int result = getContext().checkPermission(
684 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
685 canPersist = (result == PackageManager.PERMISSION_GRANTED);
686 mPersistCache.put(uid, canPersist);
687 }
688 }
689 return canPersist;
690 }
691
692 // IJobScheduler implementation
693 @Override
694 public int schedule(JobInfo job) throws RemoteException {
695 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700696 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -0700697 }
698 final int pid = Binder.getCallingPid();
699 final int uid = Binder.getCallingUid();
700
701 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700702 if (job.isPersisted()) {
703 if (!canPersistJobs(pid, uid)) {
704 throw new IllegalArgumentException("Error: requested job be persisted without"
705 + " holding RECEIVE_BOOT_COMPLETED permission.");
706 }
707 }
Christopher Tate7060b042014-06-09 19:50:00 -0700708
709 long ident = Binder.clearCallingIdentity();
710 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700711 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700712 } finally {
713 Binder.restoreCallingIdentity(ident);
714 }
715 }
716
717 @Override
718 public List<JobInfo> getAllPendingJobs() throws RemoteException {
719 final int uid = Binder.getCallingUid();
720
721 long ident = Binder.clearCallingIdentity();
722 try {
723 return JobSchedulerService.this.getPendingJobs(uid);
724 } finally {
725 Binder.restoreCallingIdentity(ident);
726 }
727 }
728
729 @Override
730 public void cancelAll() throws RemoteException {
731 final int uid = Binder.getCallingUid();
732
733 long ident = Binder.clearCallingIdentity();
734 try {
735 JobSchedulerService.this.cancelJobsForUid(uid);
736 } finally {
737 Binder.restoreCallingIdentity(ident);
738 }
739 }
740
741 @Override
742 public void cancel(int jobId) throws RemoteException {
743 final int uid = Binder.getCallingUid();
744
745 long ident = Binder.clearCallingIdentity();
746 try {
747 JobSchedulerService.this.cancelJob(uid, jobId);
748 } finally {
749 Binder.restoreCallingIdentity(ident);
750 }
751 }
752
753 /**
754 * "dumpsys" infrastructure
755 */
756 @Override
757 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
758 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
759
760 long identityToken = Binder.clearCallingIdentity();
761 try {
762 JobSchedulerService.this.dumpInternal(pw);
763 } finally {
764 Binder.restoreCallingIdentity(identityToken);
765 }
766 }
767 };
768
769 void dumpInternal(PrintWriter pw) {
770 synchronized (mJobs) {
771 pw.println("Registered jobs:");
772 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700773 ArraySet<JobStatus> jobs = mJobs.getJobs();
774 for (int i=0; i<jobs.size(); i++) {
775 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700776 job.dump(pw, " ");
777 }
778 } else {
779 pw.println();
780 pw.println("No jobs scheduled.");
781 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700782 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -0700783 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700784 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -0700785 }
786 pw.println();
787 pw.println("Pending");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700788 for (int i=0; i<mPendingJobs.size(); i++) {
789 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -0700790 }
791 pw.println();
792 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700793 for (int i=0; i<mActiveServices.size(); i++) {
794 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700795 if (jsc.isAvailable()) {
796 continue;
797 } else {
798 pw.println(jsc.getRunningJob().hashCode() + " for: " +
799 (SystemClock.elapsedRealtime()
800 - jsc.getExecutionStartTimeElapsed())/1000 + "s " +
801 "timeout: " + jsc.getTimeoutElapsed());
802 }
803 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700804 pw.println();
805 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Christopher Tate7060b042014-06-09 19:50:00 -0700806 }
807 pw.println();
808 }
809}