blob: 587f596e420d60125301da933aced736df2a7722 [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) {
227 // Remove from store.
228 stopTrackingJob(cancelled);
229 // Remove from pending queue.
230 mPendingJobs.remove(cancelled);
231 // Cancel if running.
232 stopJobOnServiceContextLocked(cancelled);
233 }
234
235 /**
236 * Initializes the system service.
237 * <p>
238 * Subclasses must define a single argument constructor that accepts the context
239 * and passes it to super.
240 * </p>
241 *
242 * @param context The system server context.
243 */
244 public JobSchedulerService(Context context) {
245 super(context);
246 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700247 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700248 mControllers.add(ConnectivityController.get(this));
249 mControllers.add(TimeController.get(this));
250 mControllers.add(IdleController.get(this));
251 mControllers.add(BatteryController.get(this));
252
253 mHandler = new JobHandler(context.getMainLooper());
254 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700255 mJobs = JobStore.initAndGet(this);
256 }
257
258 @Override
259 public void onStart() {
260 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
261 }
262
263 @Override
264 public void onBootPhase(int phase) {
265 if (PHASE_SYSTEM_SERVICES_READY == phase) {
266 // Register br for package removals and user removals.
267 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
268 filter.addDataScheme("package");
269 getContext().registerReceiverAsUser(
270 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
271 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
272 getContext().registerReceiverAsUser(
273 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700274 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
275 synchronized (mJobs) {
276 // Let's go!
277 mReadyToRock = true;
278 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
279 BatteryStats.SERVICE_NAME));
280 // Create the "runners".
281 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
282 mActiveServices.add(
283 new JobServiceContext(this, mBatteryStats,
284 getContext().getMainLooper()));
285 }
286 // Attach jobs to their controllers.
287 ArraySet<JobStatus> jobs = mJobs.getJobs();
288 for (int i=0; i<jobs.size(); i++) {
289 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700290 for (int controller=0; controller<mControllers.size(); controller++) {
291 mControllers.get(controller).maybeStartTrackingJob(job);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700292 }
293 }
294 // GO GO GO!
295 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
296 }
Christopher Tate7060b042014-06-09 19:50:00 -0700297 }
298 }
299
300 /**
301 * Called when we have a job status object that we need to insert in our
302 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
303 * about.
304 */
305 private void startTrackingJob(JobStatus jobStatus) {
306 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700307 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700308 synchronized (mJobs) {
309 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700310 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700311 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700312 if (rocking) {
313 for (int i=0; i<mControllers.size(); i++) {
314 StateController controller = mControllers.get(i);
315 if (update) {
316 controller.maybeStopTrackingJob(jobStatus);
317 }
318 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700319 }
Christopher Tate7060b042014-06-09 19:50:00 -0700320 }
321 }
322
323 /**
324 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
325 * object removed.
326 */
327 private boolean stopTrackingJob(JobStatus jobStatus) {
328 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700329 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700330 synchronized (mJobs) {
331 // Remove from store as well as controllers.
332 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700333 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700334 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700335 if (removed && rocking) {
336 for (int i=0; i<mControllers.size(); i++) {
337 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700338 controller.maybeStopTrackingJob(jobStatus);
339 }
340 }
341 return removed;
342 }
343
344 private boolean stopJobOnServiceContextLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700345 for (int i=0; i<mActiveServices.size(); i++) {
346 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700347 final JobStatus executing = jsc.getRunningJob();
348 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
349 jsc.cancelExecutingJob();
350 return true;
351 }
352 }
353 return false;
354 }
355
356 /**
357 * @param job JobStatus we are querying against.
358 * @return Whether or not the job represented by the status object is currently being run or
359 * is pending.
360 */
361 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700362 for (int i=0; i<mActiveServices.size(); i++) {
363 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700364 final JobStatus running = serviceContext.getRunningJob();
365 if (running != null && running.matches(job.getUid(), job.getJobId())) {
366 return true;
367 }
368 }
369 return false;
370 }
371
372 /**
373 * A job is rescheduled with exponential back-off if the client requests this from their
374 * execution logic.
375 * A caveat is for idle-mode jobs, for which the idle-mode constraint will usurp the
376 * timeliness of the reschedule. For an idle-mode job, no deadline is given.
377 * @param failureToReschedule Provided job status that we will reschedule.
378 * @return A newly instantiated JobStatus with the same constraints as the last job except
379 * with adjusted timing constraints.
380 */
381 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
382 final long elapsedNowMillis = SystemClock.elapsedRealtime();
383 final JobInfo job = failureToReschedule.getJob();
384
385 final long initialBackoffMillis = job.getInitialBackoffMillis();
386 final int backoffAttempt = failureToReschedule.getNumFailures() + 1;
387 long newEarliestRuntimeElapsed = elapsedNowMillis;
388
389 switch (job.getBackoffPolicy()) {
390 case JobInfo.BackoffPolicy.LINEAR:
391 newEarliestRuntimeElapsed += initialBackoffMillis * backoffAttempt;
392 break;
393 default:
394 if (DEBUG) {
395 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
396 }
397 case JobInfo.BackoffPolicy.EXPONENTIAL:
398 newEarliestRuntimeElapsed +=
399 Math.pow(initialBackoffMillis * 0.001, backoffAttempt) * 1000;
400 break;
401 }
402 newEarliestRuntimeElapsed =
403 Math.min(newEarliestRuntimeElapsed, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
404 return new JobStatus(failureToReschedule, newEarliestRuntimeElapsed,
405 JobStatus.NO_LATEST_RUNTIME, backoffAttempt);
406 }
407
408 /**
409 * Called after a periodic has executed so we can to re-add it. We take the last execution time
410 * of the job to be the time of completion (i.e. the time at which this function is called).
411 * This could be inaccurate b/c the job can run for as long as
412 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
413 * to underscheduling at least, rather than if we had taken the last execution time to be the
414 * start of the execution.
415 * @return A new job representing the execution criteria for this instantiation of the
416 * recurring job.
417 */
418 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
419 final long elapsedNow = SystemClock.elapsedRealtime();
420 // Compute how much of the period is remaining.
421 long runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0);
422 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
423 long period = periodicToReschedule.getJob().getIntervalMillis();
424 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
425
426 if (DEBUG) {
427 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
428 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
429 }
430 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
431 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
432 }
433
434 // JobCompletedListener implementations.
435
436 /**
437 * A job just finished executing. We fetch the
438 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
439 * whether we want to reschedule we readd it to the controllers.
440 * @param jobStatus Completed job.
441 * @param needsReschedule Whether the implementing class should reschedule this job.
442 */
443 @Override
444 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
445 if (DEBUG) {
446 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
447 }
448 if (!stopTrackingJob(jobStatus)) {
449 if (DEBUG) {
450 Slog.e(TAG, "Error removing job: could not find job to remove. Was job " +
451 "removed while executing?");
452 }
453 return;
454 }
455 if (needsReschedule) {
456 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
457 startTrackingJob(rescheduled);
458 } else if (jobStatus.getJob().isPeriodic()) {
459 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
460 startTrackingJob(rescheduledPeriodic);
461 }
462 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
463 }
464
465 // StateChangedListener implementations.
466
467 /**
468 * Off-board work to our handler thread as quickly as possible, b/c this call is probably being
469 * made on the main thread.
470 * For now this takes the job and if it's ready to run it will run it. In future we might not
471 * provide the job, so that the StateChangedListener has to run through its list of jobs to
472 * see which are ready. This will further decouple the controllers from the execution logic.
473 */
474 @Override
475 public void onControllerStateChanged() {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700476 synchronized (mJobs) {
477 if (mReadyToRock) {
478 // Post a message to to run through the list of jobs and start/stop any that
479 // are eligible.
480 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
481 }
482 }
Christopher Tate7060b042014-06-09 19:50:00 -0700483 }
484
485 @Override
486 public void onRunJobNow(JobStatus jobStatus) {
487 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
488 }
489
Christopher Tate7060b042014-06-09 19:50:00 -0700490 private class JobHandler extends Handler {
491
492 public JobHandler(Looper looper) {
493 super(looper);
494 }
495
496 @Override
497 public void handleMessage(Message message) {
498 switch (message.what) {
499 case MSG_JOB_EXPIRED:
500 synchronized (mJobs) {
501 JobStatus runNow = (JobStatus) message.obj;
502 if (!mPendingJobs.contains(runNow)) {
503 mPendingJobs.add(runNow);
504 }
505 }
506 queueReadyJobsForExecutionH();
507 break;
508 case MSG_CHECK_JOB:
509 // Check the list of jobs and run some of them if we feel inclined.
510 maybeQueueReadyJobsForExecutionH();
511 break;
512 }
513 maybeRunPendingJobsH();
514 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
515 removeMessages(MSG_CHECK_JOB);
516 }
517
518 /**
519 * Run through list of jobs and execute all possible - at least one is expired so we do
520 * as many as we can.
521 */
522 private void queueReadyJobsForExecutionH() {
523 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700524 ArraySet<JobStatus> jobs = mJobs.getJobs();
525 for (int i=0; i<jobs.size(); i++) {
526 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700527 if (isReadyToBeExecutedLocked(job)) {
528 mPendingJobs.add(job);
529 } else if (isReadyToBeCancelledLocked(job)) {
530 stopJobOnServiceContextLocked(job);
531 }
532 }
533 }
534 }
535
536 /**
537 * The state of at least one job has changed. Here is where we could enforce various
538 * policies on when we want to execute jobs.
539 * Right now the policy is such:
540 * If >1 of the ready jobs is idle mode we send all of them off
541 * if more than 2 network connectivity jobs are ready we send them all off.
542 * If more than 4 jobs total are ready we send them all off.
543 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
544 */
545 private void maybeQueueReadyJobsForExecutionH() {
546 synchronized (mJobs) {
547 int idleCount = 0;
548 int backoffCount = 0;
549 int connectivityCount = 0;
550 List<JobStatus> runnableJobs = new ArrayList<JobStatus>();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700551 ArraySet<JobStatus> jobs = mJobs.getJobs();
552 for (int i=0; i<jobs.size(); i++) {
553 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700554 if (isReadyToBeExecutedLocked(job)) {
555 if (job.getNumFailures() > 0) {
556 backoffCount++;
557 }
558 if (job.hasIdleConstraint()) {
559 idleCount++;
560 }
561 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
562 connectivityCount++;
563 }
564 runnableJobs.add(job);
565 } else if (isReadyToBeCancelledLocked(job)) {
566 stopJobOnServiceContextLocked(job);
567 }
568 }
569 if (backoffCount > 0 || idleCount >= MIN_IDLE_COUNT ||
570 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
571 runnableJobs.size() >= MIN_READY_JOBS_COUNT) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700572 for (int i=0; i<runnableJobs.size(); i++) {
573 mPendingJobs.add(runnableJobs.get(i));
Christopher Tate7060b042014-06-09 19:50:00 -0700574 }
575 }
576 }
577 }
578
579 /**
580 * Criteria for moving a job into the pending queue:
581 * - It's ready.
582 * - It's not pending.
583 * - It's not already running on a JSC.
584 */
585 private boolean isReadyToBeExecutedLocked(JobStatus job) {
586 return job.isReady() && !mPendingJobs.contains(job) && !isCurrentlyActiveLocked(job);
587 }
588
589 /**
590 * Criteria for cancelling an active job:
591 * - It's not ready
592 * - It's running on a JSC.
593 */
594 private boolean isReadyToBeCancelledLocked(JobStatus job) {
595 return !job.isReady() && isCurrentlyActiveLocked(job);
596 }
597
598 /**
599 * Reconcile jobs in the pending queue against available execution contexts.
600 * A controller can force a job into the pending queue even if it's already running, but
601 * here is where we decide whether to actually execute it.
602 */
603 private void maybeRunPendingJobsH() {
604 synchronized (mJobs) {
605 Iterator<JobStatus> it = mPendingJobs.iterator();
606 while (it.hasNext()) {
607 JobStatus nextPending = it.next();
608 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700609 for (int i=0; i<mActiveServices.size(); i++) {
610 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700611 final JobStatus running = jsc.getRunningJob();
612 if (running != null && running.matches(nextPending.getUid(),
613 nextPending.getJobId())) {
614 // Already running this tId for this uId, skip.
615 availableContext = null;
616 break;
617 }
618 if (jsc.isAvailable()) {
619 availableContext = jsc;
620 }
621 }
622 if (availableContext != null) {
623 if (!availableContext.executeRunnableJob(nextPending)) {
624 if (DEBUG) {
625 Slog.d(TAG, "Error executing " + nextPending);
626 }
627 mJobs.remove(nextPending);
628 }
629 it.remove();
630 }
631 }
632 }
633 }
634 }
635
636 /**
637 * Binder stub trampoline implementation
638 */
639 final class JobSchedulerStub extends IJobScheduler.Stub {
640 /** Cache determination of whether a given app can persist jobs
641 * key is uid of the calling app; value is undetermined/true/false
642 */
643 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
644
645 // Enforce that only the app itself (or shared uid participant) can schedule a
646 // job that runs one of the app's services, as well as verifying that the
647 // named service properly requires the BIND_JOB_SERVICE permission
648 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700649 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700650 final ComponentName service = job.getService();
651 try {
Christopher Tate5568f542014-06-18 13:53:31 -0700652 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid));
653 if (si == null) {
654 throw new IllegalArgumentException("No such service " + service);
655 }
Christopher Tate7060b042014-06-09 19:50:00 -0700656 if (si.applicationInfo.uid != uid) {
657 throw new IllegalArgumentException("uid " + uid +
658 " cannot schedule job in " + service.getPackageName());
659 }
660 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
661 throw new IllegalArgumentException("Scheduled service " + service
662 + " does not require android.permission.BIND_JOB_SERVICE permission");
663 }
Christopher Tate5568f542014-06-18 13:53:31 -0700664 } catch (RemoteException e) {
665 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700666 }
667 }
668
669 private boolean canPersistJobs(int pid, int uid) {
670 // If we get this far we're good to go; all we need to do now is check
671 // whether the app is allowed to persist its scheduled work.
672 final boolean canPersist;
673 synchronized (mPersistCache) {
674 Boolean cached = mPersistCache.get(uid);
675 if (cached != null) {
676 canPersist = cached.booleanValue();
677 } else {
678 // Persisting jobs is tantamount to running at boot, so we permit
679 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
680 // permission
681 int result = getContext().checkPermission(
682 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
683 canPersist = (result == PackageManager.PERMISSION_GRANTED);
684 mPersistCache.put(uid, canPersist);
685 }
686 }
687 return canPersist;
688 }
689
690 // IJobScheduler implementation
691 @Override
692 public int schedule(JobInfo job) throws RemoteException {
693 if (DEBUG) {
694 Slog.d(TAG, "Scheduling job: " + job);
695 }
696 final int pid = Binder.getCallingPid();
697 final int uid = Binder.getCallingUid();
698
699 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700700 if (job.isPersisted()) {
701 if (!canPersistJobs(pid, uid)) {
702 throw new IllegalArgumentException("Error: requested job be persisted without"
703 + " holding RECEIVE_BOOT_COMPLETED permission.");
704 }
705 }
Christopher Tate7060b042014-06-09 19:50:00 -0700706
707 long ident = Binder.clearCallingIdentity();
708 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700709 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700710 } finally {
711 Binder.restoreCallingIdentity(ident);
712 }
713 }
714
715 @Override
716 public List<JobInfo> getAllPendingJobs() throws RemoteException {
717 final int uid = Binder.getCallingUid();
718
719 long ident = Binder.clearCallingIdentity();
720 try {
721 return JobSchedulerService.this.getPendingJobs(uid);
722 } finally {
723 Binder.restoreCallingIdentity(ident);
724 }
725 }
726
727 @Override
728 public void cancelAll() throws RemoteException {
729 final int uid = Binder.getCallingUid();
730
731 long ident = Binder.clearCallingIdentity();
732 try {
733 JobSchedulerService.this.cancelJobsForUid(uid);
734 } finally {
735 Binder.restoreCallingIdentity(ident);
736 }
737 }
738
739 @Override
740 public void cancel(int jobId) throws RemoteException {
741 final int uid = Binder.getCallingUid();
742
743 long ident = Binder.clearCallingIdentity();
744 try {
745 JobSchedulerService.this.cancelJob(uid, jobId);
746 } finally {
747 Binder.restoreCallingIdentity(ident);
748 }
749 }
750
751 /**
752 * "dumpsys" infrastructure
753 */
754 @Override
755 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
756 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
757
758 long identityToken = Binder.clearCallingIdentity();
759 try {
760 JobSchedulerService.this.dumpInternal(pw);
761 } finally {
762 Binder.restoreCallingIdentity(identityToken);
763 }
764 }
765 };
766
767 void dumpInternal(PrintWriter pw) {
768 synchronized (mJobs) {
769 pw.println("Registered jobs:");
770 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700771 ArraySet<JobStatus> jobs = mJobs.getJobs();
772 for (int i=0; i<jobs.size(); i++) {
773 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700774 job.dump(pw, " ");
775 }
776 } else {
777 pw.println();
778 pw.println("No jobs scheduled.");
779 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700780 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -0700781 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700782 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -0700783 }
784 pw.println();
785 pw.println("Pending");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700786 for (int i=0; i<mPendingJobs.size(); i++) {
787 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -0700788 }
789 pw.println();
790 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700791 for (int i=0; i<mActiveServices.size(); i++) {
792 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700793 if (jsc.isAvailable()) {
794 continue;
795 } else {
796 pw.println(jsc.getRunningJob().hashCode() + " for: " +
797 (SystemClock.elapsedRealtime()
798 - jsc.getExecutionStartTimeElapsed())/1000 + "s " +
799 "timeout: " + jsc.getTimeoutElapsed());
800 }
801 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700802 pw.println();
803 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Christopher Tate7060b042014-06-09 19:50:00 -0700804 }
805 pw.println();
806 }
807}