blob: 4d7df9cfba0e92a8ffd5db5ee3b011d71a1beec3 [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
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070025import android.app.ActivityManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070026import android.app.ActivityManagerNative;
Christopher Tate5568f542014-06-18 13:53:31 -070027import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.app.job.JobInfo;
30import android.app.job.JobScheduler;
31import android.app.job.JobService;
32import android.app.job.IJobScheduler;
33import android.content.BroadcastReceiver;
34import android.content.ComponentName;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070038import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070039import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070040import android.content.pm.ServiceInfo;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070041import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070042import android.os.Binder;
43import android.os.Handler;
44import android.os.Looper;
45import android.os.Message;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070046import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070047import android.os.RemoteException;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070048import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070049import android.os.SystemClock;
50import android.os.UserHandle;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070051import android.util.ArraySet;
Christopher Tate7060b042014-06-09 19:50:00 -070052import android.util.Slog;
53import android.util.SparseArray;
54
Dianne Hackbornfdb19562014-07-11 16:03:36 -070055import com.android.internal.app.IBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080056import com.android.server.DeviceIdleController;
57import com.android.server.LocalServices;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080058import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070059import com.android.server.job.controllers.BatteryController;
60import com.android.server.job.controllers.ConnectivityController;
61import com.android.server.job.controllers.IdleController;
62import com.android.server.job.controllers.JobStatus;
63import com.android.server.job.controllers.StateController;
64import com.android.server.job.controllers.TimeController;
65
Christopher Tate7060b042014-06-09 19:50:00 -070066/**
67 * Responsible for taking jobs representing work to be performed by a client app, and determining
68 * based on the criteria specified when that job should be run against the client application's
69 * endpoint.
70 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
71 * about constraints, or the state of active jobs. It receives callbacks from the various
72 * controllers and completed jobs and operates accordingly.
73 *
74 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
75 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
76 * @hide
77 */
78public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -070079 implements StateChangedListener, JobCompletedListener {
Matthew Williamsaa984312015-10-15 16:08:05 -070080 public static final boolean DEBUG = false;
Christopher Tate7060b042014-06-09 19:50:00 -070081 /** The number of concurrent jobs we run at one time. */
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070082 private static final int MAX_JOB_CONTEXTS_COUNT
83 = ActivityManager.isLowRamDeviceStatic() ? 1 : 3;
Matthew Williamsbe0c4172014-08-06 18:14:16 -070084 static final String TAG = "JobSchedulerService";
Christopher Tate7060b042014-06-09 19:50:00 -070085 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070086 final JobStore mJobs;
Christopher Tate7060b042014-06-09 19:50:00 -070087
88 static final int MSG_JOB_EXPIRED = 0;
89 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070090 static final int MSG_STOP_JOB = 2;
Christopher Tate7060b042014-06-09 19:50:00 -070091
92 // Policy constants
93 /**
94 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
95 * early.
96 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070097 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -070098 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -070099 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
100 * early.
101 */
102 static final int MIN_CHARGING_COUNT = 1;
103 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700104 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
105 * things early.
106 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700107 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700108 /**
109 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
110 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700111 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700112 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700113 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700114
115 /**
116 * Track Services that have currently active or pending jobs. The index is provided by
117 * {@link JobStatus#getServiceToken()}
118 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700119 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700120 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700121 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700122 /**
123 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
124 * when ready to execute them.
125 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700126 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700127
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700128 final ArrayList<Integer> mStartedUsers = new ArrayList<>();
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700129
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700130 final JobHandler mHandler;
131 final JobSchedulerStub mJobSchedulerStub;
132
133 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700134 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800135 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700136
137 /**
138 * Set to true once we are allowed to run third party apps.
139 */
140 boolean mReadyToRock;
141
Christopher Tate7060b042014-06-09 19:50:00 -0700142 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700143 * True when in device idle mode, so we don't want to schedule any jobs.
144 */
145 boolean mDeviceIdleMode;
146
147 /**
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800148 * What we last reported to DeviceIdleController about wheter we are active.
149 */
150 boolean mReportedActive;
151
152 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700153 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
154 * still clean up. On reinstall the package will have a new uid.
155 */
156 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
157 @Override
158 public void onReceive(Context context, Intent intent) {
159 Slog.d(TAG, "Receieved: " + intent.getAction());
160 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700161 // If this is an outright uninstall rather than the first half of an
162 // app update sequence, cancel the jobs associated with the app.
163 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
164 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
165 if (DEBUG) {
166 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
167 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700168 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700169 }
Christopher Tate7060b042014-06-09 19:50:00 -0700170 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
171 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
172 if (DEBUG) {
173 Slog.d(TAG, "Removing jobs for user: " + userId);
174 }
175 cancelJobsForUser(userId);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700176 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())
177 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
178 updateIdleMode(mPowerManager != null
179 ? (mPowerManager.isDeviceIdleMode()
180 || mPowerManager.isLightDeviceIdleMode())
181 : false);
Christopher Tate7060b042014-06-09 19:50:00 -0700182 }
183 }
184 };
185
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700186 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
187 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
188 }
189
190 @Override public void onUidGone(int uid) throws RemoteException {
191 }
192
193 @Override public void onUidActive(int uid) throws RemoteException {
194 }
195
196 @Override public void onUidIdle(int uid) throws RemoteException {
197 cancelJobsForUid(uid, false);
198 }
199 };
200
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700201 @Override
202 public void onStartUser(int userHandle) {
203 mStartedUsers.add(userHandle);
204 // Let's kick any outstanding jobs for this user.
205 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
206 }
207
208 @Override
209 public void onStopUser(int userHandle) {
210 mStartedUsers.remove(Integer.valueOf(userHandle));
211 }
212
Christopher Tate7060b042014-06-09 19:50:00 -0700213 /**
214 * Entry point from client to schedule the provided job.
215 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
216 * @param job JobInfo object containing execution parameters
217 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700218 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
219 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700220 public int schedule(JobInfo job, int uId) {
221 JobStatus jobStatus = new JobStatus(job, uId);
Christopher Tate7060b042014-06-09 19:50:00 -0700222 cancelJob(uId, job.getId());
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700223 try {
224 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
225 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
226 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
227 + " -- package not allowed to start");
228 return JobScheduler.RESULT_FAILURE;
229 }
230 } catch (RemoteException e) {
231 }
Christopher Tate7060b042014-06-09 19:50:00 -0700232 startTrackingJob(jobStatus);
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700233 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700234 return JobScheduler.RESULT_SUCCESS;
235 }
236
237 public List<JobInfo> getPendingJobs(int uid) {
238 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
239 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700240 ArraySet<JobStatus> jobs = mJobs.getJobs();
241 for (int i=0; i<jobs.size(); i++) {
242 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700243 if (job.getUid() == uid) {
244 outList.add(job.getJob());
245 }
246 }
247 }
248 return outList;
249 }
250
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700251 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700252 List<JobStatus> jobsForUser;
Christopher Tate7060b042014-06-09 19:50:00 -0700253 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700254 jobsForUser = mJobs.getJobsByUser(userHandle);
255 }
256 for (int i=0; i<jobsForUser.size(); i++) {
257 JobStatus toRemove = jobsForUser.get(i);
258 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700259 }
260 }
261
262 /**
263 * Entry point from client to cancel all jobs originating from their uid.
264 * This will remove the job from the master list, and cancel the job if it was staged for
265 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700266 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700267 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
268 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700269 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700270 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700271 List<JobStatus> jobsForUid;
Christopher Tate7060b042014-06-09 19:50:00 -0700272 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700273 jobsForUid = mJobs.getJobsByUid(uid);
274 }
275 for (int i=0; i<jobsForUid.size(); i++) {
276 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700277 if (!forceAll) {
278 String packageName = toRemove.getServiceComponent().getPackageName();
279 try {
280 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
281 != ActivityManager.APP_START_MODE_DISABLED) {
282 continue;
283 }
284 } catch (RemoteException e) {
285 }
286 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700287 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700288 }
289 }
290
291 /**
292 * Entry point from client to cancel the job corresponding to the jobId provided.
293 * This will remove the job from the master list, and cancel the job if it was staged for
294 * execution or being executed.
295 * @param uid Uid of the calling client.
296 * @param jobId Id of the job, provided at schedule-time.
297 */
298 public void cancelJob(int uid, int jobId) {
299 JobStatus toCancel;
300 synchronized (mJobs) {
301 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700302 }
303 if (toCancel != null) {
304 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700305 }
306 }
307
Matthew Williams48a30db2014-09-23 13:39:36 -0700308 private void cancelJobImpl(JobStatus cancelled) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700309 if (DEBUG) {
310 Slog.d(TAG, "Cancelling: " + cancelled);
311 }
Christopher Tate7060b042014-06-09 19:50:00 -0700312 stopTrackingJob(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700313 synchronized (mJobs) {
314 // Remove from pending queue.
315 mPendingJobs.remove(cancelled);
316 // Cancel if running.
317 stopJobOnServiceContextLocked(cancelled);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800318 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700319 }
Christopher Tate7060b042014-06-09 19:50:00 -0700320 }
321
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700322 void updateIdleMode(boolean enabled) {
323 boolean changed = false;
324 boolean rocking;
325 synchronized (mJobs) {
326 if (mDeviceIdleMode != enabled) {
327 changed = true;
328 }
329 rocking = mReadyToRock;
330 }
331 if (changed) {
332 if (rocking) {
333 for (int i=0; i<mControllers.size(); i++) {
334 mControllers.get(i).deviceIdleModeChanged(enabled);
335 }
336 }
337 synchronized (mJobs) {
338 mDeviceIdleMode = enabled;
339 if (enabled) {
340 // When becoming idle, make sure no jobs are actively running.
341 for (int i=0; i<mActiveServices.size(); i++) {
342 JobServiceContext jsc = mActiveServices.get(i);
343 final JobStatus executing = jsc.getRunningJob();
344 if (executing != null) {
345 jsc.cancelExecutingJob();
346 }
347 }
348 } else {
349 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800350 if (rocking) {
351 if (mLocalDeviceIdleController != null) {
352 if (!mReportedActive) {
353 mReportedActive = true;
354 mLocalDeviceIdleController.setJobsActive(true);
355 }
356 }
357 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700358 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
359 }
360 }
361 }
362 }
363
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800364 void reportActive() {
365 boolean active = false;
366 if (mPendingJobs.size() <= 0) {
367 for (int i=0; i<mActiveServices.size(); i++) {
368 JobServiceContext jsc = mActiveServices.get(i);
369 if (!jsc.isAvailable()) {
370 active = true;
371 break;
372 }
373 }
374 }
375 if (mLocalDeviceIdleController != null) {
376 if (mReportedActive != active) {
377 mReportedActive = active;
378 mLocalDeviceIdleController.setJobsActive(active);
379 }
380 }
381 }
382
Christopher Tate7060b042014-06-09 19:50:00 -0700383 /**
384 * Initializes the system service.
385 * <p>
386 * Subclasses must define a single argument constructor that accepts the context
387 * and passes it to super.
388 * </p>
389 *
390 * @param context The system server context.
391 */
392 public JobSchedulerService(Context context) {
393 super(context);
394 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700395 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700396 mControllers.add(ConnectivityController.get(this));
397 mControllers.add(TimeController.get(this));
398 mControllers.add(IdleController.get(this));
399 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800400 mControllers.add(AppIdleController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700401
402 mHandler = new JobHandler(context.getMainLooper());
403 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700404 mJobs = JobStore.initAndGet(this);
405 }
406
407 @Override
408 public void onStart() {
409 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
410 }
411
412 @Override
413 public void onBootPhase(int phase) {
414 if (PHASE_SYSTEM_SERVICES_READY == phase) {
415 // Register br for package removals and user removals.
416 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
417 filter.addDataScheme("package");
418 getContext().registerReceiverAsUser(
419 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
420 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700421 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700422 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700423 getContext().registerReceiverAsUser(
424 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700425 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700426 try {
427 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
428 ActivityManager.UID_OBSERVER_IDLE);
429 } catch (RemoteException e) {
430 // ignored; both services live in system_server
431 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700432 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
433 synchronized (mJobs) {
434 // Let's go!
435 mReadyToRock = true;
436 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
437 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800438 mLocalDeviceIdleController
439 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700440 // Create the "runners".
441 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
442 mActiveServices.add(
443 new JobServiceContext(this, mBatteryStats,
444 getContext().getMainLooper()));
445 }
446 // Attach jobs to their controllers.
447 ArraySet<JobStatus> jobs = mJobs.getJobs();
448 for (int i=0; i<jobs.size(); i++) {
449 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700450 for (int controller=0; controller<mControllers.size(); controller++) {
Dianne Hackborn2bf51f42015-03-24 14:17:12 -0700451 mControllers.get(controller).deviceIdleModeChanged(mDeviceIdleMode);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700452 mControllers.get(controller).maybeStartTrackingJob(job);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700453 }
454 }
455 // GO GO GO!
456 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
457 }
Christopher Tate7060b042014-06-09 19:50:00 -0700458 }
459 }
460
461 /**
462 * Called when we have a job status object that we need to insert in our
463 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
464 * about.
465 */
466 private void startTrackingJob(JobStatus jobStatus) {
467 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700468 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700469 synchronized (mJobs) {
470 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700471 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700472 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700473 if (rocking) {
474 for (int i=0; i<mControllers.size(); i++) {
475 StateController controller = mControllers.get(i);
476 if (update) {
477 controller.maybeStopTrackingJob(jobStatus);
478 }
479 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700480 }
Christopher Tate7060b042014-06-09 19:50:00 -0700481 }
482 }
483
484 /**
485 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
486 * object removed.
487 */
488 private boolean stopTrackingJob(JobStatus jobStatus) {
489 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700490 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700491 synchronized (mJobs) {
492 // Remove from store as well as controllers.
493 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700494 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700495 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700496 if (removed && rocking) {
497 for (int i=0; i<mControllers.size(); i++) {
498 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700499 controller.maybeStopTrackingJob(jobStatus);
500 }
501 }
502 return removed;
503 }
504
505 private boolean stopJobOnServiceContextLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700506 for (int i=0; i<mActiveServices.size(); i++) {
507 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700508 final JobStatus executing = jsc.getRunningJob();
509 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
510 jsc.cancelExecutingJob();
511 return true;
512 }
513 }
514 return false;
515 }
516
517 /**
518 * @param job JobStatus we are querying against.
519 * @return Whether or not the job represented by the status object is currently being run or
520 * is pending.
521 */
522 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700523 for (int i=0; i<mActiveServices.size(); i++) {
524 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700525 final JobStatus running = serviceContext.getRunningJob();
526 if (running != null && running.matches(job.getUid(), job.getJobId())) {
527 return true;
528 }
529 }
530 return false;
531 }
532
533 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700534 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
535 * specify an override deadline on a failed job (the failed job will run even though it's not
536 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
537 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
538 *
Christopher Tate7060b042014-06-09 19:50:00 -0700539 * @param failureToReschedule Provided job status that we will reschedule.
540 * @return A newly instantiated JobStatus with the same constraints as the last job except
541 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700542 *
543 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700544 */
545 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
546 final long elapsedNowMillis = SystemClock.elapsedRealtime();
547 final JobInfo job = failureToReschedule.getJob();
548
549 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700550 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
551 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700552
553 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700554 case JobInfo.BACKOFF_POLICY_LINEAR:
555 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700556 break;
557 default:
558 if (DEBUG) {
559 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
560 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700561 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
562 delayMillis =
563 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700564 break;
565 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700566 delayMillis =
567 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
568 return new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
569 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Christopher Tate7060b042014-06-09 19:50:00 -0700570 }
571
572 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700573 * Called after a periodic has executed so we can reschedule it. We take the last execution
574 * time of the job to be the time of completion (i.e. the time at which this function is
575 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700576 * This could be inaccurate b/c the job can run for as long as
577 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
578 * to underscheduling at least, rather than if we had taken the last execution time to be the
579 * start of the execution.
580 * @return A new job representing the execution criteria for this instantiation of the
581 * recurring job.
582 */
583 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
584 final long elapsedNow = SystemClock.elapsedRealtime();
585 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700586 long runEarly = 0L;
587
588 // If this periodic was rescheduled it won't have a deadline.
589 if (periodicToReschedule.hasDeadlineConstraint()) {
590 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
591 }
Christopher Tate7060b042014-06-09 19:50:00 -0700592 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
593 long period = periodicToReschedule.getJob().getIntervalMillis();
594 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
595
596 if (DEBUG) {
597 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
598 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
599 }
600 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
601 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
602 }
603
604 // JobCompletedListener implementations.
605
606 /**
607 * A job just finished executing. We fetch the
608 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
609 * whether we want to reschedule we readd it to the controllers.
610 * @param jobStatus Completed job.
611 * @param needsReschedule Whether the implementing class should reschedule this job.
612 */
613 @Override
614 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
615 if (DEBUG) {
616 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
617 }
618 if (!stopTrackingJob(jobStatus)) {
619 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700620 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700621 }
622 return;
623 }
624 if (needsReschedule) {
625 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
626 startTrackingJob(rescheduled);
627 } else if (jobStatus.getJob().isPeriodic()) {
628 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
629 startTrackingJob(rescheduledPeriodic);
630 }
631 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
632 }
633
634 // StateChangedListener implementations.
635
636 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700637 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
638 * some controller's state has changed, so as to run through the list of jobs and start/stop
639 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700640 */
641 @Override
642 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700643 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700644 }
645
646 @Override
647 public void onRunJobNow(JobStatus jobStatus) {
648 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
649 }
650
Christopher Tate7060b042014-06-09 19:50:00 -0700651 private class JobHandler extends Handler {
652
653 public JobHandler(Looper looper) {
654 super(looper);
655 }
656
657 @Override
658 public void handleMessage(Message message) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700659 synchronized (mJobs) {
660 if (!mReadyToRock) {
661 return;
662 }
663 }
Christopher Tate7060b042014-06-09 19:50:00 -0700664 switch (message.what) {
665 case MSG_JOB_EXPIRED:
666 synchronized (mJobs) {
667 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700668 // runNow can be null, which is a controller's way of indicating that its
669 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700670 if (runNow != null && !mPendingJobs.contains(runNow)
671 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700672 mPendingJobs.add(runNow);
673 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700674 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700675 }
Christopher Tate7060b042014-06-09 19:50:00 -0700676 break;
677 case MSG_CHECK_JOB:
Matthew Williams48a30db2014-09-23 13:39:36 -0700678 synchronized (mJobs) {
679 // Check the list of jobs and run some of them if we feel inclined.
680 maybeQueueReadyJobsForExecutionLockedH();
681 }
Christopher Tate7060b042014-06-09 19:50:00 -0700682 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700683 case MSG_STOP_JOB:
684 cancelJobImpl((JobStatus)message.obj);
685 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700686 }
687 maybeRunPendingJobsH();
688 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
689 removeMessages(MSG_CHECK_JOB);
690 }
691
692 /**
693 * Run through list of jobs and execute all possible - at least one is expired so we do
694 * as many as we can.
695 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700696 private void queueReadyJobsForExecutionLockedH() {
697 ArraySet<JobStatus> jobs = mJobs.getJobs();
698 if (DEBUG) {
699 Slog.d(TAG, "queuing all ready jobs for execution:");
700 }
701 for (int i=0; i<jobs.size(); i++) {
702 JobStatus job = jobs.valueAt(i);
703 if (isReadyToBeExecutedLocked(job)) {
704 if (DEBUG) {
705 Slog.d(TAG, " queued " + job.toShortString());
Christopher Tate7060b042014-06-09 19:50:00 -0700706 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700707 mPendingJobs.add(job);
708 } else if (isReadyToBeCancelledLocked(job)) {
709 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700710 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700711 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800712 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700713 if (DEBUG) {
714 final int queuedJobs = mPendingJobs.size();
715 if (queuedJobs == 0) {
716 Slog.d(TAG, "No jobs pending.");
717 } else {
718 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700719 }
Christopher Tate7060b042014-06-09 19:50:00 -0700720 }
721 }
722
723 /**
724 * The state of at least one job has changed. Here is where we could enforce various
725 * policies on when we want to execute jobs.
726 * Right now the policy is such:
727 * If >1 of the ready jobs is idle mode we send all of them off
728 * if more than 2 network connectivity jobs are ready we send them all off.
729 * If more than 4 jobs total are ready we send them all off.
730 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
731 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700732 private void maybeQueueReadyJobsForExecutionLockedH() {
733 int chargingCount = 0;
734 int idleCount = 0;
735 int backoffCount = 0;
736 int connectivityCount = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700737 List<JobStatus> runnableJobs = null;
Matthew Williams48a30db2014-09-23 13:39:36 -0700738 ArraySet<JobStatus> jobs = mJobs.getJobs();
739 for (int i=0; i<jobs.size(); i++) {
740 JobStatus job = jobs.valueAt(i);
741 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700742 try {
743 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
744 job.getJob().getService().getPackageName())
745 == ActivityManager.APP_START_MODE_DISABLED) {
746 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
747 + job.getJob().toString() + " -- package not allowed to start");
748 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
749 continue;
750 }
751 } catch (RemoteException e) {
752 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700753 if (job.getNumFailures() > 0) {
754 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700755 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700756 if (job.hasIdleConstraint()) {
757 idleCount++;
758 }
759 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
760 connectivityCount++;
761 }
762 if (job.hasChargingConstraint()) {
763 chargingCount++;
764 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700765 if (runnableJobs == null) {
766 runnableJobs = new ArrayList<>();
767 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700768 runnableJobs.add(job);
769 } else if (isReadyToBeCancelledLocked(job)) {
770 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700771 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700772 }
773 if (backoffCount > 0 ||
774 idleCount >= MIN_IDLE_COUNT ||
775 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
776 chargingCount >= MIN_CHARGING_COUNT ||
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700777 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700778 if (DEBUG) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700779 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
Christopher Tate7060b042014-06-09 19:50:00 -0700780 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700781 for (int i=0; i<runnableJobs.size(); i++) {
782 mPendingJobs.add(runnableJobs.get(i));
783 }
784 } else {
785 if (DEBUG) {
786 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
787 }
788 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800789 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700790 if (DEBUG) {
791 Slog.d(TAG, "idle=" + idleCount + " connectivity=" +
792 connectivityCount + " charging=" + chargingCount + " tot=" +
793 runnableJobs.size());
Christopher Tate7060b042014-06-09 19:50:00 -0700794 }
795 }
796
797 /**
798 * Criteria for moving a job into the pending queue:
799 * - It's ready.
800 * - It's not pending.
801 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700802 * - The user that requested the job is running.
Christopher Tate7060b042014-06-09 19:50:00 -0700803 */
804 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700805 final boolean jobReady = job.isReady();
806 final boolean jobPending = mPendingJobs.contains(job);
807 final boolean jobActive = isCurrentlyActiveLocked(job);
808 final boolean userRunning = mStartedUsers.contains(job.getUserId());
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700809 if (DEBUG) {
810 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
811 + " ready=" + jobReady + " pending=" + jobPending
812 + " active=" + jobActive + " userRunning=" + userRunning);
813 }
814 return userRunning && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700815 }
816
817 /**
818 * Criteria for cancelling an active job:
819 * - It's not ready
820 * - It's running on a JSC.
821 */
822 private boolean isReadyToBeCancelledLocked(JobStatus job) {
823 return !job.isReady() && isCurrentlyActiveLocked(job);
824 }
825
826 /**
827 * Reconcile jobs in the pending queue against available execution contexts.
828 * A controller can force a job into the pending queue even if it's already running, but
829 * here is where we decide whether to actually execute it.
830 */
831 private void maybeRunPendingJobsH() {
832 synchronized (mJobs) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700833 if (mDeviceIdleMode) {
834 // If device is idle, we will not schedule jobs to run.
835 return;
836 }
Christopher Tate7060b042014-06-09 19:50:00 -0700837 Iterator<JobStatus> it = mPendingJobs.iterator();
Matthew Williams75fc5252014-09-02 16:17:53 -0700838 if (DEBUG) {
839 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
840 }
Christopher Tate7060b042014-06-09 19:50:00 -0700841 while (it.hasNext()) {
842 JobStatus nextPending = it.next();
843 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700844 for (int i=0; i<mActiveServices.size(); i++) {
845 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700846 final JobStatus running = jsc.getRunningJob();
847 if (running != null && running.matches(nextPending.getUid(),
848 nextPending.getJobId())) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700849 // Already running this job for this uId, skip.
Christopher Tate7060b042014-06-09 19:50:00 -0700850 availableContext = null;
851 break;
852 }
853 if (jsc.isAvailable()) {
854 availableContext = jsc;
855 }
856 }
857 if (availableContext != null) {
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800858 if (DEBUG) {
859 Slog.d(TAG, "About to run job "
860 + nextPending.getJob().getService().toString());
861 }
Christopher Tate7060b042014-06-09 19:50:00 -0700862 if (!availableContext.executeRunnableJob(nextPending)) {
863 if (DEBUG) {
864 Slog.d(TAG, "Error executing " + nextPending);
865 }
866 mJobs.remove(nextPending);
867 }
868 it.remove();
869 }
870 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800871 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700872 }
873 }
874 }
875
876 /**
877 * Binder stub trampoline implementation
878 */
879 final class JobSchedulerStub extends IJobScheduler.Stub {
880 /** Cache determination of whether a given app can persist jobs
881 * key is uid of the calling app; value is undetermined/true/false
882 */
883 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
884
885 // Enforce that only the app itself (or shared uid participant) can schedule a
886 // job that runs one of the app's services, as well as verifying that the
887 // named service properly requires the BIND_JOB_SERVICE permission
888 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700889 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700890 final ComponentName service = job.getService();
891 try {
Christopher Tate5568f542014-06-18 13:53:31 -0700892 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid));
893 if (si == null) {
894 throw new IllegalArgumentException("No such service " + service);
895 }
Christopher Tate7060b042014-06-09 19:50:00 -0700896 if (si.applicationInfo.uid != uid) {
897 throw new IllegalArgumentException("uid " + uid +
898 " cannot schedule job in " + service.getPackageName());
899 }
900 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
901 throw new IllegalArgumentException("Scheduled service " + service
902 + " does not require android.permission.BIND_JOB_SERVICE permission");
903 }
Christopher Tate5568f542014-06-18 13:53:31 -0700904 } catch (RemoteException e) {
905 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700906 }
907 }
908
909 private boolean canPersistJobs(int pid, int uid) {
910 // If we get this far we're good to go; all we need to do now is check
911 // whether the app is allowed to persist its scheduled work.
912 final boolean canPersist;
913 synchronized (mPersistCache) {
914 Boolean cached = mPersistCache.get(uid);
915 if (cached != null) {
916 canPersist = cached.booleanValue();
917 } else {
918 // Persisting jobs is tantamount to running at boot, so we permit
919 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
920 // permission
921 int result = getContext().checkPermission(
922 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
923 canPersist = (result == PackageManager.PERMISSION_GRANTED);
924 mPersistCache.put(uid, canPersist);
925 }
926 }
927 return canPersist;
928 }
929
930 // IJobScheduler implementation
931 @Override
932 public int schedule(JobInfo job) throws RemoteException {
933 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700934 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -0700935 }
936 final int pid = Binder.getCallingPid();
937 final int uid = Binder.getCallingUid();
938
939 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700940 if (job.isPersisted()) {
941 if (!canPersistJobs(pid, uid)) {
942 throw new IllegalArgumentException("Error: requested job be persisted without"
943 + " holding RECEIVE_BOOT_COMPLETED permission.");
944 }
945 }
Christopher Tate7060b042014-06-09 19:50:00 -0700946
947 long ident = Binder.clearCallingIdentity();
948 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700949 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700950 } finally {
951 Binder.restoreCallingIdentity(ident);
952 }
953 }
954
955 @Override
956 public List<JobInfo> getAllPendingJobs() throws RemoteException {
957 final int uid = Binder.getCallingUid();
958
959 long ident = Binder.clearCallingIdentity();
960 try {
961 return JobSchedulerService.this.getPendingJobs(uid);
962 } finally {
963 Binder.restoreCallingIdentity(ident);
964 }
965 }
966
967 @Override
968 public void cancelAll() throws RemoteException {
969 final int uid = Binder.getCallingUid();
970
971 long ident = Binder.clearCallingIdentity();
972 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700973 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700974 } finally {
975 Binder.restoreCallingIdentity(ident);
976 }
977 }
978
979 @Override
980 public void cancel(int jobId) throws RemoteException {
981 final int uid = Binder.getCallingUid();
982
983 long ident = Binder.clearCallingIdentity();
984 try {
985 JobSchedulerService.this.cancelJob(uid, jobId);
986 } finally {
987 Binder.restoreCallingIdentity(ident);
988 }
989 }
990
991 /**
992 * "dumpsys" infrastructure
993 */
994 @Override
995 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
996 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
997
998 long identityToken = Binder.clearCallingIdentity();
999 try {
1000 JobSchedulerService.this.dumpInternal(pw);
1001 } finally {
1002 Binder.restoreCallingIdentity(identityToken);
1003 }
1004 }
1005 };
1006
1007 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001008 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -07001009 synchronized (mJobs) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001010 pw.print("Started users: ");
1011 for (int i=0; i<mStartedUsers.size(); i++) {
1012 pw.print("u" + mStartedUsers.get(i) + " ");
1013 }
1014 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07001015 pw.println("Registered jobs:");
1016 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001017 ArraySet<JobStatus> jobs = mJobs.getJobs();
1018 for (int i=0; i<jobs.size(); i++) {
1019 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001020 job.dump(pw, " ");
1021 }
1022 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001023 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001024 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001025 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001026 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001027 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001028 }
1029 pw.println();
Christopher Tatef973a7b2014-08-29 12:54:08 -07001030 pw.println("Pending:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001031 for (int i=0; i<mPendingJobs.size(); i++) {
1032 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -07001033 }
1034 pw.println();
1035 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001036 for (int i=0; i<mActiveServices.size(); i++) {
1037 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001038 if (jsc.isAvailable()) {
1039 continue;
1040 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001041 final long timeout = jsc.getTimeoutElapsed();
1042 pw.print("Running for: ");
1043 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1044 pw.print("s timeout=");
1045 pw.print(timeout);
1046 pw.print(" fromnow=");
1047 pw.println(timeout-now);
1048 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -07001049 }
1050 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001051 pw.println();
1052 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001053 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001054 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001055 }
1056 pw.println();
1057 }
1058}