blob: 30154d716f7fc93756cbe973bdba5c18cf8aa0b4 [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;
Matthew Williamsbe0c4172014-08-06 18:14:16 -070077 static final String TAG = "JobSchedulerService";
Christopher Tate7060b042014-06-09 19:50:00 -070078 /** 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 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -070091 * 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 /**
Christopher Tate7060b042014-06-09 19:50:00 -070096 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
97 * things early.
98 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070099 static final int MIN_CONNECTIVITY_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700100 /**
101 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
102 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700103 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700104 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700105 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700106
107 /**
108 * Track Services that have currently active or pending jobs. The index is provided by
109 * {@link JobStatus#getServiceToken()}
110 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700111 final List<JobServiceContext> mActiveServices = new ArrayList<JobServiceContext>();
Christopher Tate7060b042014-06-09 19:50:00 -0700112 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700113 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700114 /**
115 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
116 * when ready to execute them.
117 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700118 final ArrayList<JobStatus> mPendingJobs = new ArrayList<JobStatus>();
Christopher Tate7060b042014-06-09 19:50:00 -0700119
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700120 final ArrayList<Integer> mStartedUsers = new ArrayList();
121
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700122 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
Christopher Tate7060b042014-06-09 19:50:00 -0700132 /**
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
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700156 @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
Christopher Tate7060b042014-06-09 19:50:00 -0700168 /**
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.
Christopher Tate7060b042014-06-09 19:50:00 -0700173 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
174 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700175 public int schedule(JobInfo job, int uId) {
176 JobStatus jobStatus = new JobStatus(job, uId);
Christopher Tate7060b042014-06-09 19:50:00 -0700177 cancelJob(uId, job.getId());
178 startTrackingJob(jobStatus);
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700179 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700180 return JobScheduler.RESULT_SUCCESS;
181 }
182
183 public List<JobInfo> getPendingJobs(int uid) {
184 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
185 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700186 ArraySet<JobStatus> jobs = mJobs.getJobs();
187 for (int i=0; i<jobs.size(); i++) {
188 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700189 if (job.getUid() == uid) {
190 outList.add(job.getJob());
191 }
192 }
193 }
194 return outList;
195 }
196
197 private void cancelJobsForUser(int userHandle) {
198 synchronized (mJobs) {
199 List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700200 for (int i=0; i<jobsForUser.size(); i++) {
201 JobStatus toRemove = jobsForUser.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700202 cancelJobLocked(toRemove);
203 }
204 }
205 }
206
207 /**
208 * Entry point from client to cancel all jobs originating from their uid.
209 * This will remove the job from the master list, and cancel the job if it was staged for
210 * execution or being executed.
211 * @param uid To check against for removal of a job.
212 */
213 public void cancelJobsForUid(int uid) {
214 // Remove from master list.
215 synchronized (mJobs) {
216 List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700217 for (int i=0; i<jobsForUid.size(); i++) {
218 JobStatus toRemove = jobsForUid.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700219 cancelJobLocked(toRemove);
220 }
221 }
222 }
223
224 /**
225 * Entry point from client to cancel the job corresponding to the jobId provided.
226 * This will remove the job from the master list, and cancel the job if it was staged for
227 * execution or being executed.
228 * @param uid Uid of the calling client.
229 * @param jobId Id of the job, provided at schedule-time.
230 */
231 public void cancelJob(int uid, int jobId) {
232 JobStatus toCancel;
233 synchronized (mJobs) {
234 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
235 if (toCancel != null) {
236 cancelJobLocked(toCancel);
237 }
238 }
239 }
240
241 private void cancelJobLocked(JobStatus cancelled) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700242 if (DEBUG) {
243 Slog.d(TAG, "Cancelling: " + cancelled);
244 }
Christopher Tate7060b042014-06-09 19:50:00 -0700245 // Remove from store.
246 stopTrackingJob(cancelled);
247 // Remove from pending queue.
248 mPendingJobs.remove(cancelled);
249 // Cancel if running.
250 stopJobOnServiceContextLocked(cancelled);
251 }
252
253 /**
254 * Initializes the system service.
255 * <p>
256 * Subclasses must define a single argument constructor that accepts the context
257 * and passes it to super.
258 * </p>
259 *
260 * @param context The system server context.
261 */
262 public JobSchedulerService(Context context) {
263 super(context);
264 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700265 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700266 mControllers.add(ConnectivityController.get(this));
267 mControllers.add(TimeController.get(this));
268 mControllers.add(IdleController.get(this));
269 mControllers.add(BatteryController.get(this));
270
271 mHandler = new JobHandler(context.getMainLooper());
272 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700273 mJobs = JobStore.initAndGet(this);
274 }
275
276 @Override
277 public void onStart() {
278 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
279 }
280
281 @Override
282 public void onBootPhase(int phase) {
283 if (PHASE_SYSTEM_SERVICES_READY == phase) {
284 // Register br for package removals and user removals.
285 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
286 filter.addDataScheme("package");
287 getContext().registerReceiverAsUser(
288 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
289 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
290 getContext().registerReceiverAsUser(
291 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700292 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
293 synchronized (mJobs) {
294 // Let's go!
295 mReadyToRock = true;
296 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
297 BatteryStats.SERVICE_NAME));
298 // Create the "runners".
299 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
300 mActiveServices.add(
301 new JobServiceContext(this, mBatteryStats,
302 getContext().getMainLooper()));
303 }
304 // Attach jobs to their controllers.
305 ArraySet<JobStatus> jobs = mJobs.getJobs();
306 for (int i=0; i<jobs.size(); i++) {
307 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700308 for (int controller=0; controller<mControllers.size(); controller++) {
309 mControllers.get(controller).maybeStartTrackingJob(job);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700310 }
311 }
312 // GO GO GO!
313 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
314 }
Christopher Tate7060b042014-06-09 19:50:00 -0700315 }
316 }
317
318 /**
319 * Called when we have a job status object that we need to insert in our
320 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
321 * about.
322 */
323 private void startTrackingJob(JobStatus jobStatus) {
324 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700325 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700326 synchronized (mJobs) {
327 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700328 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700329 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700330 if (rocking) {
331 for (int i=0; i<mControllers.size(); i++) {
332 StateController controller = mControllers.get(i);
333 if (update) {
334 controller.maybeStopTrackingJob(jobStatus);
335 }
336 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700337 }
Christopher Tate7060b042014-06-09 19:50:00 -0700338 }
339 }
340
341 /**
342 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
343 * object removed.
344 */
345 private boolean stopTrackingJob(JobStatus jobStatus) {
346 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700347 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700348 synchronized (mJobs) {
349 // Remove from store as well as controllers.
350 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700351 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700352 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700353 if (removed && rocking) {
354 for (int i=0; i<mControllers.size(); i++) {
355 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700356 controller.maybeStopTrackingJob(jobStatus);
357 }
358 }
359 return removed;
360 }
361
362 private boolean stopJobOnServiceContextLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700363 for (int i=0; i<mActiveServices.size(); i++) {
364 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700365 final JobStatus executing = jsc.getRunningJob();
366 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
367 jsc.cancelExecutingJob();
368 return true;
369 }
370 }
371 return false;
372 }
373
374 /**
375 * @param job JobStatus we are querying against.
376 * @return Whether or not the job represented by the status object is currently being run or
377 * is pending.
378 */
379 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700380 for (int i=0; i<mActiveServices.size(); i++) {
381 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700382 final JobStatus running = serviceContext.getRunningJob();
383 if (running != null && running.matches(job.getUid(), job.getJobId())) {
384 return true;
385 }
386 }
387 return false;
388 }
389
390 /**
391 * A job is rescheduled with exponential back-off if the client requests this from their
392 * execution logic.
393 * A caveat is for idle-mode jobs, for which the idle-mode constraint will usurp the
394 * timeliness of the reschedule. For an idle-mode job, no deadline is given.
395 * @param failureToReschedule Provided job status that we will reschedule.
396 * @return A newly instantiated JobStatus with the same constraints as the last job except
397 * with adjusted timing constraints.
398 */
399 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
400 final long elapsedNowMillis = SystemClock.elapsedRealtime();
401 final JobInfo job = failureToReschedule.getJob();
402
403 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700404 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
405 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700406
407 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700408 case JobInfo.BACKOFF_POLICY_LINEAR:
409 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700410 break;
411 default:
412 if (DEBUG) {
413 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
414 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700415 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
416 delayMillis =
417 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700418 break;
419 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700420 delayMillis =
421 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
422 return new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
423 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Christopher Tate7060b042014-06-09 19:50:00 -0700424 }
425
426 /**
427 * Called after a periodic has executed so we can to re-add it. We take the last execution time
428 * of the job to be the time of completion (i.e. the time at which this function is called).
429 * This could be inaccurate b/c the job can run for as long as
430 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
431 * to underscheduling at least, rather than if we had taken the last execution time to be the
432 * start of the execution.
433 * @return A new job representing the execution criteria for this instantiation of the
434 * recurring job.
435 */
436 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
437 final long elapsedNow = SystemClock.elapsedRealtime();
438 // Compute how much of the period is remaining.
439 long runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0);
440 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
441 long period = periodicToReschedule.getJob().getIntervalMillis();
442 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
443
444 if (DEBUG) {
445 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
446 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
447 }
448 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
449 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
450 }
451
452 // JobCompletedListener implementations.
453
454 /**
455 * A job just finished executing. We fetch the
456 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
457 * whether we want to reschedule we readd it to the controllers.
458 * @param jobStatus Completed job.
459 * @param needsReschedule Whether the implementing class should reschedule this job.
460 */
461 @Override
462 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
463 if (DEBUG) {
464 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
465 }
466 if (!stopTrackingJob(jobStatus)) {
467 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700468 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700469 }
470 return;
471 }
472 if (needsReschedule) {
473 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
474 startTrackingJob(rescheduled);
475 } else if (jobStatus.getJob().isPeriodic()) {
476 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
477 startTrackingJob(rescheduledPeriodic);
478 }
479 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
480 }
481
482 // StateChangedListener implementations.
483
484 /**
485 * Off-board work to our handler thread as quickly as possible, b/c this call is probably being
486 * made on the main thread.
487 * For now this takes the job and if it's ready to run it will run it. In future we might not
488 * provide the job, so that the StateChangedListener has to run through its list of jobs to
489 * see which are ready. This will further decouple the controllers from the execution logic.
490 */
491 @Override
492 public void onControllerStateChanged() {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700493 synchronized (mJobs) {
494 if (mReadyToRock) {
495 // Post a message to to run through the list of jobs and start/stop any that
496 // are eligible.
497 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
498 }
499 }
Christopher Tate7060b042014-06-09 19:50:00 -0700500 }
501
502 @Override
503 public void onRunJobNow(JobStatus jobStatus) {
504 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
505 }
506
Christopher Tate7060b042014-06-09 19:50:00 -0700507 private class JobHandler extends Handler {
508
509 public JobHandler(Looper looper) {
510 super(looper);
511 }
512
513 @Override
514 public void handleMessage(Message message) {
515 switch (message.what) {
516 case MSG_JOB_EXPIRED:
517 synchronized (mJobs) {
518 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700519 // runNow can be null, which is a controller's way of indicating that its
520 // state is such that all ready jobs should be run immediately.
521 if (runNow != null && !mPendingJobs.contains(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700522 mPendingJobs.add(runNow);
523 }
524 }
525 queueReadyJobsForExecutionH();
526 break;
527 case MSG_CHECK_JOB:
528 // Check the list of jobs and run some of them if we feel inclined.
529 maybeQueueReadyJobsForExecutionH();
530 break;
531 }
532 maybeRunPendingJobsH();
533 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
534 removeMessages(MSG_CHECK_JOB);
535 }
536
537 /**
538 * Run through list of jobs and execute all possible - at least one is expired so we do
539 * as many as we can.
540 */
541 private void queueReadyJobsForExecutionH() {
542 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700543 ArraySet<JobStatus> jobs = mJobs.getJobs();
Matthew Williams75fc5252014-09-02 16:17:53 -0700544 if (DEBUG) {
545 Slog.d(TAG, "queuing all ready jobs for execution:");
546 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700547 for (int i=0; i<jobs.size(); i++) {
548 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700549 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -0700550 if (DEBUG) {
551 Slog.d(TAG, " queued " + job.toShortString());
552 }
Christopher Tate7060b042014-06-09 19:50:00 -0700553 mPendingJobs.add(job);
554 } else if (isReadyToBeCancelledLocked(job)) {
555 stopJobOnServiceContextLocked(job);
556 }
557 }
Matthew Williams75fc5252014-09-02 16:17:53 -0700558 if (DEBUG) {
559 final int queuedJobs = mPendingJobs.size();
560 if (queuedJobs == 0) {
561 Slog.d(TAG, "No jobs pending.");
562 } else {
563 Slog.d(TAG, queuedJobs + " jobs queued.");
564 }
565 }
Christopher Tate7060b042014-06-09 19:50:00 -0700566 }
567 }
568
569 /**
570 * The state of at least one job has changed. Here is where we could enforce various
571 * policies on when we want to execute jobs.
572 * Right now the policy is such:
573 * If >1 of the ready jobs is idle mode we send all of them off
574 * if more than 2 network connectivity jobs are ready we send them all off.
575 * If more than 4 jobs total are ready we send them all off.
576 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
577 */
578 private void maybeQueueReadyJobsForExecutionH() {
579 synchronized (mJobs) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700580 int chargingCount = 0;
581 int idleCount = 0;
Christopher Tate7060b042014-06-09 19:50:00 -0700582 int backoffCount = 0;
583 int connectivityCount = 0;
584 List<JobStatus> runnableJobs = new ArrayList<JobStatus>();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700585 ArraySet<JobStatus> jobs = mJobs.getJobs();
586 for (int i=0; i<jobs.size(); i++) {
587 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700588 if (isReadyToBeExecutedLocked(job)) {
589 if (job.getNumFailures() > 0) {
590 backoffCount++;
591 }
592 if (job.hasIdleConstraint()) {
593 idleCount++;
594 }
595 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
596 connectivityCount++;
597 }
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700598 if (job.hasChargingConstraint()) {
599 chargingCount++;
600 }
Christopher Tate7060b042014-06-09 19:50:00 -0700601 runnableJobs.add(job);
602 } else if (isReadyToBeCancelledLocked(job)) {
603 stopJobOnServiceContextLocked(job);
604 }
605 }
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700606 if (backoffCount > 0 ||
607 idleCount >= MIN_IDLE_COUNT ||
Christopher Tate7060b042014-06-09 19:50:00 -0700608 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700609 chargingCount >= MIN_CHARGING_COUNT ||
Christopher Tate7060b042014-06-09 19:50:00 -0700610 runnableJobs.size() >= MIN_READY_JOBS_COUNT) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700611 if (DEBUG) {
612 Slog.d(TAG, "maybeQueueReadyJobsForExecutionH: Running jobs.");
613 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700614 for (int i=0; i<runnableJobs.size(); i++) {
615 mPendingJobs.add(runnableJobs.get(i));
Christopher Tate7060b042014-06-09 19:50:00 -0700616 }
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700617 } else {
618 if (DEBUG) {
619 Slog.d(TAG, "maybeQueueReadyJobsForExecutionH: Not running anything.");
620 }
621 }
622 if (DEBUG) {
623 Slog.d(TAG, "idle=" + idleCount + " connectivity=" +
624 connectivityCount + " charging=" + chargingCount + " tot=" +
625 runnableJobs.size());
Christopher Tate7060b042014-06-09 19:50:00 -0700626 }
627 }
628 }
629
630 /**
631 * Criteria for moving a job into the pending queue:
632 * - It's ready.
633 * - It's not pending.
634 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700635 * - The user that requested the job is running.
Christopher Tate7060b042014-06-09 19:50:00 -0700636 */
637 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700638 final boolean jobReady = job.isReady();
639 final boolean jobPending = mPendingJobs.contains(job);
640 final boolean jobActive = isCurrentlyActiveLocked(job);
641 final boolean userRunning = mStartedUsers.contains(job.getUserId());
642
643 if (DEBUG) {
644 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
645 + " ready=" + jobReady + " pending=" + jobPending
646 + " active=" + jobActive + " userRunning=" + userRunning);
647 }
648 return userRunning && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700649 }
650
651 /**
652 * Criteria for cancelling an active job:
653 * - It's not ready
654 * - It's running on a JSC.
655 */
656 private boolean isReadyToBeCancelledLocked(JobStatus job) {
657 return !job.isReady() && isCurrentlyActiveLocked(job);
658 }
659
660 /**
661 * Reconcile jobs in the pending queue against available execution contexts.
662 * A controller can force a job into the pending queue even if it's already running, but
663 * here is where we decide whether to actually execute it.
664 */
665 private void maybeRunPendingJobsH() {
666 synchronized (mJobs) {
667 Iterator<JobStatus> it = mPendingJobs.iterator();
Matthew Williams75fc5252014-09-02 16:17:53 -0700668 if (DEBUG) {
669 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
670 }
Christopher Tate7060b042014-06-09 19:50:00 -0700671 while (it.hasNext()) {
672 JobStatus nextPending = it.next();
673 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700674 for (int i=0; i<mActiveServices.size(); i++) {
675 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700676 final JobStatus running = jsc.getRunningJob();
677 if (running != null && running.matches(nextPending.getUid(),
678 nextPending.getJobId())) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700679 // Already running this job for this uId, skip.
Christopher Tate7060b042014-06-09 19:50:00 -0700680 availableContext = null;
681 break;
682 }
683 if (jsc.isAvailable()) {
684 availableContext = jsc;
685 }
686 }
687 if (availableContext != null) {
688 if (!availableContext.executeRunnableJob(nextPending)) {
689 if (DEBUG) {
690 Slog.d(TAG, "Error executing " + nextPending);
691 }
692 mJobs.remove(nextPending);
693 }
694 it.remove();
695 }
696 }
697 }
698 }
699 }
700
701 /**
702 * Binder stub trampoline implementation
703 */
704 final class JobSchedulerStub extends IJobScheduler.Stub {
705 /** Cache determination of whether a given app can persist jobs
706 * key is uid of the calling app; value is undetermined/true/false
707 */
708 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
709
710 // Enforce that only the app itself (or shared uid participant) can schedule a
711 // job that runs one of the app's services, as well as verifying that the
712 // named service properly requires the BIND_JOB_SERVICE permission
713 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700714 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700715 final ComponentName service = job.getService();
716 try {
Christopher Tate5568f542014-06-18 13:53:31 -0700717 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid));
718 if (si == null) {
719 throw new IllegalArgumentException("No such service " + service);
720 }
Christopher Tate7060b042014-06-09 19:50:00 -0700721 if (si.applicationInfo.uid != uid) {
722 throw new IllegalArgumentException("uid " + uid +
723 " cannot schedule job in " + service.getPackageName());
724 }
725 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
726 throw new IllegalArgumentException("Scheduled service " + service
727 + " does not require android.permission.BIND_JOB_SERVICE permission");
728 }
Christopher Tate5568f542014-06-18 13:53:31 -0700729 } catch (RemoteException e) {
730 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700731 }
732 }
733
734 private boolean canPersistJobs(int pid, int uid) {
735 // If we get this far we're good to go; all we need to do now is check
736 // whether the app is allowed to persist its scheduled work.
737 final boolean canPersist;
738 synchronized (mPersistCache) {
739 Boolean cached = mPersistCache.get(uid);
740 if (cached != null) {
741 canPersist = cached.booleanValue();
742 } else {
743 // Persisting jobs is tantamount to running at boot, so we permit
744 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
745 // permission
746 int result = getContext().checkPermission(
747 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
748 canPersist = (result == PackageManager.PERMISSION_GRANTED);
749 mPersistCache.put(uid, canPersist);
750 }
751 }
752 return canPersist;
753 }
754
755 // IJobScheduler implementation
756 @Override
757 public int schedule(JobInfo job) throws RemoteException {
758 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700759 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -0700760 }
761 final int pid = Binder.getCallingPid();
762 final int uid = Binder.getCallingUid();
763
764 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700765 if (job.isPersisted()) {
766 if (!canPersistJobs(pid, uid)) {
767 throw new IllegalArgumentException("Error: requested job be persisted without"
768 + " holding RECEIVE_BOOT_COMPLETED permission.");
769 }
770 }
Christopher Tate7060b042014-06-09 19:50:00 -0700771
772 long ident = Binder.clearCallingIdentity();
773 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700774 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700775 } finally {
776 Binder.restoreCallingIdentity(ident);
777 }
778 }
779
780 @Override
781 public List<JobInfo> getAllPendingJobs() throws RemoteException {
782 final int uid = Binder.getCallingUid();
783
784 long ident = Binder.clearCallingIdentity();
785 try {
786 return JobSchedulerService.this.getPendingJobs(uid);
787 } finally {
788 Binder.restoreCallingIdentity(ident);
789 }
790 }
791
792 @Override
793 public void cancelAll() throws RemoteException {
794 final int uid = Binder.getCallingUid();
795
796 long ident = Binder.clearCallingIdentity();
797 try {
798 JobSchedulerService.this.cancelJobsForUid(uid);
799 } finally {
800 Binder.restoreCallingIdentity(ident);
801 }
802 }
803
804 @Override
805 public void cancel(int jobId) throws RemoteException {
806 final int uid = Binder.getCallingUid();
807
808 long ident = Binder.clearCallingIdentity();
809 try {
810 JobSchedulerService.this.cancelJob(uid, jobId);
811 } finally {
812 Binder.restoreCallingIdentity(ident);
813 }
814 }
815
816 /**
817 * "dumpsys" infrastructure
818 */
819 @Override
820 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
821 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
822
823 long identityToken = Binder.clearCallingIdentity();
824 try {
825 JobSchedulerService.this.dumpInternal(pw);
826 } finally {
827 Binder.restoreCallingIdentity(identityToken);
828 }
829 }
830 };
831
832 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -0700833 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -0700834 synchronized (mJobs) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700835 pw.print("Started users: ");
836 for (int i=0; i<mStartedUsers.size(); i++) {
837 pw.print("u" + mStartedUsers.get(i) + " ");
838 }
839 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -0700840 pw.println("Registered jobs:");
841 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700842 ArraySet<JobStatus> jobs = mJobs.getJobs();
843 for (int i=0; i<jobs.size(); i++) {
844 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700845 job.dump(pw, " ");
846 }
847 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -0700848 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -0700849 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700850 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -0700851 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700852 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -0700853 }
854 pw.println();
Christopher Tatef973a7b2014-08-29 12:54:08 -0700855 pw.println("Pending:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700856 for (int i=0; i<mPendingJobs.size(); i++) {
857 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -0700858 }
859 pw.println();
860 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700861 for (int i=0; i<mActiveServices.size(); i++) {
862 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700863 if (jsc.isAvailable()) {
864 continue;
865 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -0700866 final long timeout = jsc.getTimeoutElapsed();
867 pw.print("Running for: ");
868 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
869 pw.print("s timeout=");
870 pw.print(timeout);
871 pw.print(" fromnow=");
872 pw.println(timeout-now);
873 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -0700874 }
875 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700876 pw.println();
877 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Christopher Tate7060b042014-06-09 19:50:00 -0700878 }
879 pw.println();
880 }
881}