blob: 309bec8884eeff667d0d353e14214655fb476df3 [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;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +000091 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -070092
93 // Policy constants
94 /**
95 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
96 * early.
97 */
Dianne Hackbornfdb19562014-07-11 16:03:36 -070098 static final int MIN_IDLE_COUNT = 1;
Christopher Tate7060b042014-06-09 19:50:00 -070099 /**
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700100 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule things
101 * early.
102 */
103 static final int MIN_CHARGING_COUNT = 1;
104 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700105 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
106 * things early.
107 */
Matthew Williamsaa984312015-10-15 16:08:05 -0700108 static final int MIN_CONNECTIVITY_COUNT = 1; // Run connectivity jobs as soon as ready.
Christopher Tate7060b042014-06-09 19:50:00 -0700109 /**
110 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy running
111 * some work early.
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700112 * This is correlated with the amount of batching we'll be able to do.
Christopher Tate7060b042014-06-09 19:50:00 -0700113 */
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700114 static final int MIN_READY_JOBS_COUNT = 2;
Christopher Tate7060b042014-06-09 19:50:00 -0700115
116 /**
117 * Track Services that have currently active or pending jobs. The index is provided by
118 * {@link JobStatus#getServiceToken()}
119 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700120 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700121 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700122 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700123 /**
124 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
125 * when ready to execute them.
126 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700127 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700128
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700129 final ArrayList<Integer> mStartedUsers = new ArrayList<>();
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700130
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700131 final JobHandler mHandler;
132 final JobSchedulerStub mJobSchedulerStub;
133
134 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700135 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800136 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700137
138 /**
139 * Set to true once we are allowed to run third party apps.
140 */
141 boolean mReadyToRock;
142
Christopher Tate7060b042014-06-09 19:50:00 -0700143 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700144 * True when in device idle mode, so we don't want to schedule any jobs.
145 */
146 boolean mDeviceIdleMode;
147
148 /**
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800149 * What we last reported to DeviceIdleController about wheter we are active.
150 */
151 boolean mReportedActive;
152
153 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700154 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
155 * still clean up. On reinstall the package will have a new uid.
156 */
157 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
158 @Override
159 public void onReceive(Context context, Intent intent) {
160 Slog.d(TAG, "Receieved: " + intent.getAction());
161 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700162 // If this is an outright uninstall rather than the first half of an
163 // app update sequence, cancel the jobs associated with the app.
164 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
165 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
166 if (DEBUG) {
167 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
168 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700169 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700170 }
Christopher Tate7060b042014-06-09 19:50:00 -0700171 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
172 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
173 if (DEBUG) {
174 Slog.d(TAG, "Removing jobs for user: " + userId);
175 }
176 cancelJobsForUser(userId);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700177 } else if (PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())
178 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
179 updateIdleMode(mPowerManager != null
180 ? (mPowerManager.isDeviceIdleMode()
181 || mPowerManager.isLightDeviceIdleMode())
182 : false);
Christopher Tate7060b042014-06-09 19:50:00 -0700183 }
184 }
185 };
186
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700187 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
188 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
189 }
190
191 @Override public void onUidGone(int uid) throws RemoteException {
192 }
193
194 @Override public void onUidActive(int uid) throws RemoteException {
195 }
196
197 @Override public void onUidIdle(int uid) throws RemoteException {
198 cancelJobsForUid(uid, false);
199 }
200 };
201
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700202 @Override
203 public void onStartUser(int userHandle) {
204 mStartedUsers.add(userHandle);
205 // Let's kick any outstanding jobs for this user.
206 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
207 }
208
209 @Override
210 public void onStopUser(int userHandle) {
211 mStartedUsers.remove(Integer.valueOf(userHandle));
212 }
213
Christopher Tate7060b042014-06-09 19:50:00 -0700214 /**
215 * Entry point from client to schedule the provided job.
216 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
217 * @param job JobInfo object containing execution parameters
218 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700219 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
220 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700221 public int schedule(JobInfo job, int uId) {
222 JobStatus jobStatus = new JobStatus(job, uId);
Christopher Tate7060b042014-06-09 19:50:00 -0700223 cancelJob(uId, job.getId());
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700224 try {
225 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
226 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
227 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
228 + " -- package not allowed to start");
229 return JobScheduler.RESULT_FAILURE;
230 }
231 } catch (RemoteException e) {
232 }
Christopher Tate7060b042014-06-09 19:50:00 -0700233 startTrackingJob(jobStatus);
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700234 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700235 return JobScheduler.RESULT_SUCCESS;
236 }
237
238 public List<JobInfo> getPendingJobs(int uid) {
239 ArrayList<JobInfo> outList = new ArrayList<JobInfo>();
240 synchronized (mJobs) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700241 ArraySet<JobStatus> jobs = mJobs.getJobs();
242 for (int i=0; i<jobs.size(); i++) {
243 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700244 if (job.getUid() == uid) {
245 outList.add(job.getJob());
246 }
247 }
248 }
249 return outList;
250 }
251
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700252 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700253 List<JobStatus> jobsForUser;
Christopher Tate7060b042014-06-09 19:50:00 -0700254 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700255 jobsForUser = mJobs.getJobsByUser(userHandle);
256 }
257 for (int i=0; i<jobsForUser.size(); i++) {
258 JobStatus toRemove = jobsForUser.get(i);
259 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700260 }
261 }
262
263 /**
264 * Entry point from client to cancel all jobs originating from their uid.
265 * This will remove the job from the master list, and cancel the job if it was staged for
266 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700267 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700268 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
269 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700270 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700271 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700272 List<JobStatus> jobsForUid;
Christopher Tate7060b042014-06-09 19:50:00 -0700273 synchronized (mJobs) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700274 jobsForUid = mJobs.getJobsByUid(uid);
275 }
276 for (int i=0; i<jobsForUid.size(); i++) {
277 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700278 if (!forceAll) {
279 String packageName = toRemove.getServiceComponent().getPackageName();
280 try {
281 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
282 != ActivityManager.APP_START_MODE_DISABLED) {
283 continue;
284 }
285 } catch (RemoteException e) {
286 }
287 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700288 cancelJobImpl(toRemove);
Christopher Tate7060b042014-06-09 19:50:00 -0700289 }
290 }
291
292 /**
293 * Entry point from client to cancel the job corresponding to the jobId provided.
294 * This will remove the job from the master list, and cancel the job if it was staged for
295 * execution or being executed.
296 * @param uid Uid of the calling client.
297 * @param jobId Id of the job, provided at schedule-time.
298 */
299 public void cancelJob(int uid, int jobId) {
300 JobStatus toCancel;
301 synchronized (mJobs) {
302 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700303 }
304 if (toCancel != null) {
305 cancelJobImpl(toCancel);
Christopher Tate7060b042014-06-09 19:50:00 -0700306 }
307 }
308
Matthew Williams48a30db2014-09-23 13:39:36 -0700309 private void cancelJobImpl(JobStatus cancelled) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700310 if (DEBUG) {
311 Slog.d(TAG, "Cancelling: " + cancelled);
312 }
Christopher Tate7060b042014-06-09 19:50:00 -0700313 stopTrackingJob(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700314 synchronized (mJobs) {
315 // Remove from pending queue.
316 mPendingJobs.remove(cancelled);
317 // Cancel if running.
318 stopJobOnServiceContextLocked(cancelled);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800319 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700320 }
Christopher Tate7060b042014-06-09 19:50:00 -0700321 }
322
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700323 void updateIdleMode(boolean enabled) {
324 boolean changed = false;
325 boolean rocking;
326 synchronized (mJobs) {
327 if (mDeviceIdleMode != enabled) {
328 changed = true;
329 }
330 rocking = mReadyToRock;
331 }
332 if (changed) {
333 if (rocking) {
334 for (int i=0; i<mControllers.size(); i++) {
335 mControllers.get(i).deviceIdleModeChanged(enabled);
336 }
337 }
338 synchronized (mJobs) {
339 mDeviceIdleMode = enabled;
340 if (enabled) {
341 // When becoming idle, make sure no jobs are actively running.
342 for (int i=0; i<mActiveServices.size(); i++) {
343 JobServiceContext jsc = mActiveServices.get(i);
344 final JobStatus executing = jsc.getRunningJob();
345 if (executing != null) {
346 jsc.cancelExecutingJob();
347 }
348 }
349 } else {
350 // When coming out of idle, allow thing to start back up.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800351 if (rocking) {
352 if (mLocalDeviceIdleController != null) {
353 if (!mReportedActive) {
354 mReportedActive = true;
355 mLocalDeviceIdleController.setJobsActive(true);
356 }
357 }
358 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700359 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
360 }
361 }
362 }
363 }
364
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800365 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000366 // active is true if pending queue contains jobs OR some job is running.
367 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800368 if (mPendingJobs.size() <= 0) {
369 for (int i=0; i<mActiveServices.size(); i++) {
370 JobServiceContext jsc = mActiveServices.get(i);
371 if (!jsc.isAvailable()) {
372 active = true;
373 break;
374 }
375 }
376 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000377
378 if (mReportedActive != active) {
379 mReportedActive = active;
380 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800381 mLocalDeviceIdleController.setJobsActive(active);
382 }
383 }
384 }
385
Christopher Tate7060b042014-06-09 19:50:00 -0700386 /**
387 * Initializes the system service.
388 * <p>
389 * Subclasses must define a single argument constructor that accepts the context
390 * and passes it to super.
391 * </p>
392 *
393 * @param context The system server context.
394 */
395 public JobSchedulerService(Context context) {
396 super(context);
397 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700398 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700399 mControllers.add(ConnectivityController.get(this));
400 mControllers.add(TimeController.get(this));
401 mControllers.add(IdleController.get(this));
402 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800403 mControllers.add(AppIdleController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700404
405 mHandler = new JobHandler(context.getMainLooper());
406 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tate7060b042014-06-09 19:50:00 -0700407 mJobs = JobStore.initAndGet(this);
408 }
409
410 @Override
411 public void onStart() {
412 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
413 }
414
415 @Override
416 public void onBootPhase(int phase) {
417 if (PHASE_SYSTEM_SERVICES_READY == phase) {
418 // Register br for package removals and user removals.
419 final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
420 filter.addDataScheme("package");
421 getContext().registerReceiverAsUser(
422 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
423 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700424 userFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700425 userFilter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
Christopher Tate7060b042014-06-09 19:50:00 -0700426 getContext().registerReceiverAsUser(
427 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700428 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700429 try {
430 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
431 ActivityManager.UID_OBSERVER_IDLE);
432 } catch (RemoteException e) {
433 // ignored; both services live in system_server
434 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700435 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
436 synchronized (mJobs) {
437 // Let's go!
438 mReadyToRock = true;
439 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
440 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800441 mLocalDeviceIdleController
442 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700443 // Create the "runners".
444 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
445 mActiveServices.add(
446 new JobServiceContext(this, mBatteryStats,
447 getContext().getMainLooper()));
448 }
449 // Attach jobs to their controllers.
450 ArraySet<JobStatus> jobs = mJobs.getJobs();
451 for (int i=0; i<jobs.size(); i++) {
452 JobStatus job = jobs.valueAt(i);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700453 for (int controller=0; controller<mControllers.size(); controller++) {
Dianne Hackborn2bf51f42015-03-24 14:17:12 -0700454 mControllers.get(controller).deviceIdleModeChanged(mDeviceIdleMode);
Christopher Tate4a79dae2014-07-18 17:01:40 -0700455 mControllers.get(controller).maybeStartTrackingJob(job);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700456 }
457 }
458 // GO GO GO!
459 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
460 }
Christopher Tate7060b042014-06-09 19:50:00 -0700461 }
462 }
463
464 /**
465 * Called when we have a job status object that we need to insert in our
466 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
467 * about.
468 */
469 private void startTrackingJob(JobStatus jobStatus) {
470 boolean update;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700471 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700472 synchronized (mJobs) {
473 update = mJobs.add(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700474 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700475 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700476 if (rocking) {
477 for (int i=0; i<mControllers.size(); i++) {
478 StateController controller = mControllers.get(i);
479 if (update) {
480 controller.maybeStopTrackingJob(jobStatus);
481 }
482 controller.maybeStartTrackingJob(jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700483 }
Christopher Tate7060b042014-06-09 19:50:00 -0700484 }
485 }
486
487 /**
488 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
489 * object removed.
490 */
491 private boolean stopTrackingJob(JobStatus jobStatus) {
492 boolean removed;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700493 boolean rocking;
Christopher Tate7060b042014-06-09 19:50:00 -0700494 synchronized (mJobs) {
495 // Remove from store as well as controllers.
496 removed = mJobs.remove(jobStatus);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700497 rocking = mReadyToRock;
Christopher Tate7060b042014-06-09 19:50:00 -0700498 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700499 if (removed && rocking) {
500 for (int i=0; i<mControllers.size(); i++) {
501 StateController controller = mControllers.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700502 controller.maybeStopTrackingJob(jobStatus);
503 }
504 }
505 return removed;
506 }
507
508 private boolean stopJobOnServiceContextLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700509 for (int i=0; i<mActiveServices.size(); i++) {
510 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700511 final JobStatus executing = jsc.getRunningJob();
512 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
513 jsc.cancelExecutingJob();
514 return true;
515 }
516 }
517 return false;
518 }
519
520 /**
521 * @param job JobStatus we are querying against.
522 * @return Whether or not the job represented by the status object is currently being run or
523 * is pending.
524 */
525 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700526 for (int i=0; i<mActiveServices.size(); i++) {
527 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700528 final JobStatus running = serviceContext.getRunningJob();
529 if (running != null && running.matches(job.getUid(), job.getJobId())) {
530 return true;
531 }
532 }
533 return false;
534 }
535
536 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700537 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
538 * specify an override deadline on a failed job (the failed job will run even though it's not
539 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
540 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
541 *
Christopher Tate7060b042014-06-09 19:50:00 -0700542 * @param failureToReschedule Provided job status that we will reschedule.
543 * @return A newly instantiated JobStatus with the same constraints as the last job except
544 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700545 *
546 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700547 */
548 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
549 final long elapsedNowMillis = SystemClock.elapsedRealtime();
550 final JobInfo job = failureToReschedule.getJob();
551
552 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700553 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
554 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700555
556 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700557 case JobInfo.BACKOFF_POLICY_LINEAR:
558 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700559 break;
560 default:
561 if (DEBUG) {
562 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
563 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700564 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
565 delayMillis =
566 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700567 break;
568 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700569 delayMillis =
570 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
571 return new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
572 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Christopher Tate7060b042014-06-09 19:50:00 -0700573 }
574
575 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700576 * Called after a periodic has executed so we can reschedule it. We take the last execution
577 * time of the job to be the time of completion (i.e. the time at which this function is
578 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700579 * This could be inaccurate b/c the job can run for as long as
580 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
581 * to underscheduling at least, rather than if we had taken the last execution time to be the
582 * start of the execution.
583 * @return A new job representing the execution criteria for this instantiation of the
584 * recurring job.
585 */
586 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
587 final long elapsedNow = SystemClock.elapsedRealtime();
588 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700589 long runEarly = 0L;
590
591 // If this periodic was rescheduled it won't have a deadline.
592 if (periodicToReschedule.hasDeadlineConstraint()) {
593 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
594 }
Christopher Tate7060b042014-06-09 19:50:00 -0700595 long newEarliestRunTimeElapsed = elapsedNow + runEarly;
596 long period = periodicToReschedule.getJob().getIntervalMillis();
597 long newLatestRuntimeElapsed = newEarliestRunTimeElapsed + period;
598
599 if (DEBUG) {
600 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
601 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
602 }
603 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
604 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
605 }
606
607 // JobCompletedListener implementations.
608
609 /**
610 * A job just finished executing. We fetch the
611 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
612 * whether we want to reschedule we readd it to the controllers.
613 * @param jobStatus Completed job.
614 * @param needsReschedule Whether the implementing class should reschedule this job.
615 */
616 @Override
617 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
618 if (DEBUG) {
619 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
620 }
621 if (!stopTrackingJob(jobStatus)) {
622 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700623 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -0700624 }
625 return;
626 }
627 if (needsReschedule) {
628 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
629 startTrackingJob(rescheduled);
630 } else if (jobStatus.getJob().isPeriodic()) {
631 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
632 startTrackingJob(rescheduledPeriodic);
633 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000634 reportActive();
635 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700636 }
637
638 // StateChangedListener implementations.
639
640 /**
Matthew Williams48a30db2014-09-23 13:39:36 -0700641 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
642 * some controller's state has changed, so as to run through the list of jobs and start/stop
643 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -0700644 */
645 @Override
646 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -0700647 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700648 }
649
650 @Override
651 public void onRunJobNow(JobStatus jobStatus) {
652 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
653 }
654
Christopher Tate7060b042014-06-09 19:50:00 -0700655 private class JobHandler extends Handler {
656
657 public JobHandler(Looper looper) {
658 super(looper);
659 }
660
661 @Override
662 public void handleMessage(Message message) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700663 synchronized (mJobs) {
664 if (!mReadyToRock) {
665 return;
666 }
667 }
Christopher Tate7060b042014-06-09 19:50:00 -0700668 switch (message.what) {
669 case MSG_JOB_EXPIRED:
670 synchronized (mJobs) {
671 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700672 // runNow can be null, which is a controller's way of indicating that its
673 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -0700674 if (runNow != null && !mPendingJobs.contains(runNow)
675 && mJobs.containsJob(runNow)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700676 mPendingJobs.add(runNow);
677 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700678 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -0700679 }
Christopher Tate7060b042014-06-09 19:50:00 -0700680 break;
681 case MSG_CHECK_JOB:
Matthew Williams48a30db2014-09-23 13:39:36 -0700682 synchronized (mJobs) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000683 if (mReportedActive) {
684 // if jobs are currently being run, queue all ready jobs for execution.
685 queueReadyJobsForExecutionLockedH();
686 } else {
687 // Check the list of jobs and run some of them if we feel inclined.
688 maybeQueueReadyJobsForExecutionLockedH();
689 }
690 }
691 break;
692 case MSG_CHECK_JOB_GREEDY:
693 synchronized (mJobs) {
694 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -0700695 }
Christopher Tate7060b042014-06-09 19:50:00 -0700696 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700697 case MSG_STOP_JOB:
698 cancelJobImpl((JobStatus)message.obj);
699 break;
Christopher Tate7060b042014-06-09 19:50:00 -0700700 }
701 maybeRunPendingJobsH();
702 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
703 removeMessages(MSG_CHECK_JOB);
704 }
705
706 /**
707 * Run through list of jobs and execute all possible - at least one is expired so we do
708 * as many as we can.
709 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700710 private void queueReadyJobsForExecutionLockedH() {
711 ArraySet<JobStatus> jobs = mJobs.getJobs();
712 if (DEBUG) {
713 Slog.d(TAG, "queuing all ready jobs for execution:");
714 }
715 for (int i=0; i<jobs.size(); i++) {
716 JobStatus job = jobs.valueAt(i);
717 if (isReadyToBeExecutedLocked(job)) {
718 if (DEBUG) {
719 Slog.d(TAG, " queued " + job.toShortString());
Christopher Tate7060b042014-06-09 19:50:00 -0700720 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700721 mPendingJobs.add(job);
722 } else if (isReadyToBeCancelledLocked(job)) {
723 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700724 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700725 }
726 if (DEBUG) {
727 final int queuedJobs = mPendingJobs.size();
728 if (queuedJobs == 0) {
729 Slog.d(TAG, "No jobs pending.");
730 } else {
731 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -0700732 }
Christopher Tate7060b042014-06-09 19:50:00 -0700733 }
734 }
735
736 /**
737 * The state of at least one job has changed. Here is where we could enforce various
738 * policies on when we want to execute jobs.
739 * Right now the policy is such:
740 * If >1 of the ready jobs is idle mode we send all of them off
741 * if more than 2 network connectivity jobs are ready we send them all off.
742 * If more than 4 jobs total are ready we send them all off.
743 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
744 */
Matthew Williams48a30db2014-09-23 13:39:36 -0700745 private void maybeQueueReadyJobsForExecutionLockedH() {
746 int chargingCount = 0;
747 int idleCount = 0;
748 int backoffCount = 0;
749 int connectivityCount = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700750 List<JobStatus> runnableJobs = null;
Matthew Williams48a30db2014-09-23 13:39:36 -0700751 ArraySet<JobStatus> jobs = mJobs.getJobs();
752 for (int i=0; i<jobs.size(); i++) {
753 JobStatus job = jobs.valueAt(i);
754 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700755 try {
756 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
757 job.getJob().getService().getPackageName())
758 == ActivityManager.APP_START_MODE_DISABLED) {
759 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
760 + job.getJob().toString() + " -- package not allowed to start");
761 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
762 continue;
763 }
764 } catch (RemoteException e) {
765 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700766 if (job.getNumFailures() > 0) {
767 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -0700768 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700769 if (job.hasIdleConstraint()) {
770 idleCount++;
771 }
772 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()) {
773 connectivityCount++;
774 }
775 if (job.hasChargingConstraint()) {
776 chargingCount++;
777 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700778 if (runnableJobs == null) {
779 runnableJobs = new ArrayList<>();
780 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700781 runnableJobs.add(job);
782 } else if (isReadyToBeCancelledLocked(job)) {
783 stopJobOnServiceContextLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -0700784 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700785 }
786 if (backoffCount > 0 ||
787 idleCount >= MIN_IDLE_COUNT ||
788 connectivityCount >= MIN_CONNECTIVITY_COUNT ||
789 chargingCount >= MIN_CHARGING_COUNT ||
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700790 (runnableJobs != null && runnableJobs.size() >= MIN_READY_JOBS_COUNT)) {
Matthew Williamsbe0c4172014-08-06 18:14:16 -0700791 if (DEBUG) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700792 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
Christopher Tate7060b042014-06-09 19:50:00 -0700793 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700794 for (int i=0; i<runnableJobs.size(); i++) {
795 mPendingJobs.add(runnableJobs.get(i));
796 }
797 } else {
798 if (DEBUG) {
799 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
800 }
801 }
802 if (DEBUG) {
803 Slog.d(TAG, "idle=" + idleCount + " connectivity=" +
804 connectivityCount + " charging=" + chargingCount + " tot=" +
805 runnableJobs.size());
Christopher Tate7060b042014-06-09 19:50:00 -0700806 }
807 }
808
809 /**
810 * Criteria for moving a job into the pending queue:
811 * - It's ready.
812 * - It's not pending.
813 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700814 * - The user that requested the job is running.
Christopher Tate7060b042014-06-09 19:50:00 -0700815 */
816 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700817 final boolean jobReady = job.isReady();
818 final boolean jobPending = mPendingJobs.contains(job);
819 final boolean jobActive = isCurrentlyActiveLocked(job);
820 final boolean userRunning = mStartedUsers.contains(job.getUserId());
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700821 if (DEBUG) {
822 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
823 + " ready=" + jobReady + " pending=" + jobPending
824 + " active=" + jobActive + " userRunning=" + userRunning);
825 }
826 return userRunning && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -0700827 }
828
829 /**
830 * Criteria for cancelling an active job:
831 * - It's not ready
832 * - It's running on a JSC.
833 */
834 private boolean isReadyToBeCancelledLocked(JobStatus job) {
835 return !job.isReady() && isCurrentlyActiveLocked(job);
836 }
837
838 /**
839 * Reconcile jobs in the pending queue against available execution contexts.
840 * A controller can force a job into the pending queue even if it's already running, but
841 * here is where we decide whether to actually execute it.
842 */
843 private void maybeRunPendingJobsH() {
844 synchronized (mJobs) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700845 if (mDeviceIdleMode) {
846 // If device is idle, we will not schedule jobs to run.
847 return;
848 }
Christopher Tate7060b042014-06-09 19:50:00 -0700849 Iterator<JobStatus> it = mPendingJobs.iterator();
Matthew Williams75fc5252014-09-02 16:17:53 -0700850 if (DEBUG) {
851 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
852 }
Christopher Tate7060b042014-06-09 19:50:00 -0700853 while (it.hasNext()) {
854 JobStatus nextPending = it.next();
855 JobServiceContext availableContext = null;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700856 for (int i=0; i<mActiveServices.size(); i++) {
857 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700858 final JobStatus running = jsc.getRunningJob();
859 if (running != null && running.matches(nextPending.getUid(),
860 nextPending.getJobId())) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700861 // Already running this job for this uId, skip.
Christopher Tate7060b042014-06-09 19:50:00 -0700862 availableContext = null;
863 break;
864 }
865 if (jsc.isAvailable()) {
866 availableContext = jsc;
867 }
868 }
869 if (availableContext != null) {
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800870 if (DEBUG) {
871 Slog.d(TAG, "About to run job "
872 + nextPending.getJob().getService().toString());
873 }
Christopher Tate7060b042014-06-09 19:50:00 -0700874 if (!availableContext.executeRunnableJob(nextPending)) {
875 if (DEBUG) {
876 Slog.d(TAG, "Error executing " + nextPending);
877 }
878 mJobs.remove(nextPending);
879 }
880 it.remove();
881 }
882 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800883 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -0700884 }
885 }
886 }
887
888 /**
889 * Binder stub trampoline implementation
890 */
891 final class JobSchedulerStub extends IJobScheduler.Stub {
892 /** Cache determination of whether a given app can persist jobs
893 * key is uid of the calling app; value is undetermined/true/false
894 */
895 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
896
897 // Enforce that only the app itself (or shared uid participant) can schedule a
898 // job that runs one of the app's services, as well as verifying that the
899 // named service properly requires the BIND_JOB_SERVICE permission
900 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -0700901 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -0700902 final ComponentName service = job.getService();
903 try {
Christopher Tate5568f542014-06-18 13:53:31 -0700904 ServiceInfo si = pm.getServiceInfo(service, 0, UserHandle.getUserId(uid));
905 if (si == null) {
906 throw new IllegalArgumentException("No such service " + service);
907 }
Christopher Tate7060b042014-06-09 19:50:00 -0700908 if (si.applicationInfo.uid != uid) {
909 throw new IllegalArgumentException("uid " + uid +
910 " cannot schedule job in " + service.getPackageName());
911 }
912 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
913 throw new IllegalArgumentException("Scheduled service " + service
914 + " does not require android.permission.BIND_JOB_SERVICE permission");
915 }
Christopher Tate5568f542014-06-18 13:53:31 -0700916 } catch (RemoteException e) {
917 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -0700918 }
919 }
920
921 private boolean canPersistJobs(int pid, int uid) {
922 // If we get this far we're good to go; all we need to do now is check
923 // whether the app is allowed to persist its scheduled work.
924 final boolean canPersist;
925 synchronized (mPersistCache) {
926 Boolean cached = mPersistCache.get(uid);
927 if (cached != null) {
928 canPersist = cached.booleanValue();
929 } else {
930 // Persisting jobs is tantamount to running at boot, so we permit
931 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
932 // permission
933 int result = getContext().checkPermission(
934 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
935 canPersist = (result == PackageManager.PERMISSION_GRANTED);
936 mPersistCache.put(uid, canPersist);
937 }
938 }
939 return canPersist;
940 }
941
942 // IJobScheduler implementation
943 @Override
944 public int schedule(JobInfo job) throws RemoteException {
945 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -0700946 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -0700947 }
948 final int pid = Binder.getCallingPid();
949 final int uid = Binder.getCallingUid();
950
951 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -0700952 if (job.isPersisted()) {
953 if (!canPersistJobs(pid, uid)) {
954 throw new IllegalArgumentException("Error: requested job be persisted without"
955 + " holding RECEIVE_BOOT_COMPLETED permission.");
956 }
957 }
Christopher Tate7060b042014-06-09 19:50:00 -0700958
959 long ident = Binder.clearCallingIdentity();
960 try {
Matthew Williams900c67f2014-07-09 12:46:53 -0700961 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700962 } finally {
963 Binder.restoreCallingIdentity(ident);
964 }
965 }
966
967 @Override
968 public List<JobInfo> getAllPendingJobs() throws RemoteException {
969 final int uid = Binder.getCallingUid();
970
971 long ident = Binder.clearCallingIdentity();
972 try {
973 return JobSchedulerService.this.getPendingJobs(uid);
974 } finally {
975 Binder.restoreCallingIdentity(ident);
976 }
977 }
978
979 @Override
980 public void cancelAll() throws RemoteException {
981 final int uid = Binder.getCallingUid();
982
983 long ident = Binder.clearCallingIdentity();
984 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700985 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700986 } finally {
987 Binder.restoreCallingIdentity(ident);
988 }
989 }
990
991 @Override
992 public void cancel(int jobId) throws RemoteException {
993 final int uid = Binder.getCallingUid();
994
995 long ident = Binder.clearCallingIdentity();
996 try {
997 JobSchedulerService.this.cancelJob(uid, jobId);
998 } finally {
999 Binder.restoreCallingIdentity(ident);
1000 }
1001 }
1002
1003 /**
1004 * "dumpsys" infrastructure
1005 */
1006 @Override
1007 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1008 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1009
1010 long identityToken = Binder.clearCallingIdentity();
1011 try {
1012 JobSchedulerService.this.dumpInternal(pw);
1013 } finally {
1014 Binder.restoreCallingIdentity(identityToken);
1015 }
1016 }
1017 };
1018
1019 void dumpInternal(PrintWriter pw) {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001020 final long now = SystemClock.elapsedRealtime();
Christopher Tate7060b042014-06-09 19:50:00 -07001021 synchronized (mJobs) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001022 pw.print("Started users: ");
1023 for (int i=0; i<mStartedUsers.size(); i++) {
1024 pw.print("u" + mStartedUsers.get(i) + " ");
1025 }
1026 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07001027 pw.println("Registered jobs:");
1028 if (mJobs.size() > 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001029 ArraySet<JobStatus> jobs = mJobs.getJobs();
1030 for (int i=0; i<jobs.size(); i++) {
1031 JobStatus job = jobs.valueAt(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001032 job.dump(pw, " ");
1033 }
1034 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001035 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001036 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001037 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001038 pw.println();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001039 mControllers.get(i).dumpControllerState(pw);
Christopher Tate7060b042014-06-09 19:50:00 -07001040 }
1041 pw.println();
Christopher Tatef973a7b2014-08-29 12:54:08 -07001042 pw.println("Pending:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001043 for (int i=0; i<mPendingJobs.size(); i++) {
1044 pw.println(mPendingJobs.get(i).hashCode());
Christopher Tate7060b042014-06-09 19:50:00 -07001045 }
1046 pw.println();
1047 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001048 for (int i=0; i<mActiveServices.size(); i++) {
1049 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -07001050 if (jsc.isAvailable()) {
1051 continue;
1052 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001053 final long timeout = jsc.getTimeoutElapsed();
1054 pw.print("Running for: ");
1055 pw.print((now - jsc.getExecutionStartTimeElapsed())/1000);
1056 pw.print("s timeout=");
1057 pw.print(timeout);
1058 pw.print(" fromnow=");
1059 pw.println(timeout-now);
1060 jsc.getRunningJob().dump(pw, " ");
Christopher Tate7060b042014-06-09 19:50:00 -07001061 }
1062 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001063 pw.println();
1064 pw.print("mReadyToRock="); pw.println(mReadyToRock);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001065 pw.print("mDeviceIdleMode="); pw.println(mDeviceIdleMode);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001066 pw.print("mReportedActive="); pw.println(mReportedActive);
Christopher Tate7060b042014-06-09 19:50:00 -07001067 }
1068 pw.println();
1069 }
1070}