blob: 9d931467d91482e86cca438058d9add0d4a44e0e [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
Christopher Tateb5c07882016-05-26 17:11:09 -070019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21
Shreyas Basarge5db09082016-01-07 13:38:29 +000022import java.io.FileDescriptor;
23import java.io.PrintWriter;
24import java.util.ArrayList;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070025import java.util.Arrays;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070026import java.util.Collections;
27import java.util.Comparator;
Shreyas Basarge5db09082016-01-07 13:38:29 +000028import java.util.Iterator;
29import java.util.List;
30
Christopher Tateee7805b2016-07-15 16:56:56 -070031import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070032import android.app.ActivityManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070033import android.app.ActivityManagerNative;
Christopher Tate5568f542014-06-18 13:53:31 -070034import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070035import android.app.IUidObserver;
Christopher Tate7060b042014-06-09 19:50:00 -070036import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000037import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070038import android.app.job.JobScheduler;
39import android.app.job.JobService;
Shreyas Basarge5db09082016-01-07 13:38:29 +000040import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.content.BroadcastReceiver;
42import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070043import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070044import android.content.Context;
45import android.content.Intent;
46import android.content.IntentFilter;
Christopher Tateee7805b2016-07-15 16:56:56 -070047import android.content.pm.ApplicationInfo;
Christopher Tate5568f542014-06-18 13:53:31 -070048import android.content.pm.IPackageManager;
Christopher Tateee7805b2016-07-15 16:56:56 -070049import android.content.pm.PackageInfo;
Christopher Tate7060b042014-06-09 19:50:00 -070050import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070051import android.content.pm.ServiceInfo;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060052import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070053import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070054import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070055import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070056import android.os.Binder;
57import android.os.Handler;
58import android.os.Looper;
59import android.os.Message;
Shreyas Basargecbf5ae92016-03-08 16:13:06 +000060import android.os.Process;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070061import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070062import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080063import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070064import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070065import android.os.SystemClock;
66import android.os.UserHandle;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070067import android.provider.Settings;
68import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070069import android.util.Slog;
70import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080071import android.util.SparseIntArray;
72import android.util.TimeUtils;
Christopher Tate5d346052016-03-08 12:56:08 -080073
Dianne Hackbornfdb19562014-07-11 16:03:36 -070074import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070075import com.android.internal.app.procstats.ProcessStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070076import com.android.internal.util.ArrayUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080077import com.android.server.DeviceIdleController;
78import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080079import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080080import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070081import com.android.server.job.controllers.BatteryController;
82import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080083import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070084import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070085import com.android.server.job.controllers.IdleController;
86import com.android.server.job.controllers.JobStatus;
87import com.android.server.job.controllers.StateController;
88import com.android.server.job.controllers.TimeController;
89
Jeff Sharkey822cbd12016-02-25 11:09:55 -070090import libcore.util.EmptyArray;
91
Christopher Tate7060b042014-06-09 19:50:00 -070092/**
93 * Responsible for taking jobs representing work to be performed by a client app, and determining
94 * based on the criteria specified when that job should be run against the client application's
95 * endpoint.
96 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
97 * about constraints, or the state of active jobs. It receives callbacks from the various
98 * controllers and completed jobs and operates accordingly.
99 *
100 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
101 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
102 * @hide
103 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800104public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700105 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800106 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700107 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800108
Dianne Hackborn970510b2016-02-24 16:56:42 -0800109 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700110 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800111 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800112 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800113 /** The maximum number of jobs that we allow an unprivileged app to schedule */
114 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700115
Christopher Tate2f36fd62016-02-18 18:36:08 -0800116
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800117 /** Global local for all job scheduler state. */
118 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700119 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700120 final JobStore mJobs;
Dianne Hackborn807de782016-04-07 17:54:41 -0700121 /** Tracking amount of time each package runs for. */
122 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700123
124 static final int MSG_JOB_EXPIRED = 0;
125 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700126 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000127 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700128
Christopher Tate7060b042014-06-09 19:50:00 -0700129 /**
130 * Track Services that have currently active or pending jobs. The index is provided by
131 * {@link JobStatus#getServiceToken()}
132 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700133 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700134 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700135 List<StateController> mControllers;
Christopher Tate7060b042014-06-09 19:50:00 -0700136 /**
137 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
138 * when ready to execute them.
139 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700140 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700141
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700142 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700143
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700144 final JobHandler mHandler;
145 final JobSchedulerStub mJobSchedulerStub;
146
147 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700148 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800149 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700150
151 /**
152 * Set to true once we are allowed to run third party apps.
153 */
154 boolean mReadyToRock;
155
Christopher Tate7060b042014-06-09 19:50:00 -0700156 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800157 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800158 */
159 boolean mReportedActive;
160
161 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800162 * Current limit on the number of concurrent JobServiceContext entries we want to
163 * keep actively running a job.
164 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700165 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800166
167 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800168 * Which uids are currently in the foreground.
169 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800170 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
171
172 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
173
174 /**
175 * This array essentially stores the state of mActiveServices array.
176 * The ith index stores the job present on the ith JobServiceContext.
177 * We manipulate this array until we arrive at what jobs should be running on
178 * what JobServiceContext.
179 */
180 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
181 /**
182 * Indicates whether we need to act on this jobContext id
183 */
184 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
185 /**
186 * The uid whose jobs we would like to assign to a context.
187 */
188 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800189
190 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700191 * All times are in milliseconds. These constants are kept synchronized with the system
192 * global Settings. Any access to this class or its fields should be done while
193 * holding the JobSchedulerService.mLock lock.
194 */
195 private final class Constants extends ContentObserver {
196 // Key names stored in the settings value.
197 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
198 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
199 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
200 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
201 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
202 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
203 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
204 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
205 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
206 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
207 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
208 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
209
210 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
211 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
212 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
213 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
214 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
215 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
216 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
217 private static final int DEFAULT_FG_JOB_COUNT = 4;
218 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
219 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
220 private static final int DEFAULT_BG_LOW_JOB_COUNT = 2;
221 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
222
223 /**
224 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
225 * early.
226 */
227 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
228 /**
229 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
230 * things early.
231 */
232 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
233 /**
234 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
235 * things early. 1 == Run connectivity jobs as soon as ready.
236 */
237 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
238 /**
239 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
240 * schedule things early.
241 */
242 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
243 /**
244 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
245 * running some work early. This (and thus the other min counts) is now set to 1, to
246 * prevent any batching at this level. Since we now do batching through doze, that is
247 * a much better mechanism.
248 */
249 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
250 /**
251 * This is the job execution factor that is considered to be heavy use of the system.
252 */
253 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
254 /**
255 * This is the job execution factor that is considered to be moderate use of the system.
256 */
257 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
258 /**
259 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
260 */
261 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
262 /**
263 * The maximum number of background jobs we allow when the system is in a normal
264 * memory state.
265 */
266 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
267 /**
268 * The maximum number of background jobs we allow when the system is in a moderate
269 * memory state.
270 */
271 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
272 /**
273 * The maximum number of background jobs we allow when the system is in a low
274 * memory state.
275 */
276 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
277 /**
278 * The maximum number of background jobs we allow when the system is in a critical
279 * memory state.
280 */
281 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
282
283 private ContentResolver mResolver;
284 private final KeyValueListParser mParser = new KeyValueListParser(',');
285
286 public Constants(Handler handler) {
287 super(handler);
288 }
289
290 public void start(ContentResolver resolver) {
291 mResolver = resolver;
292 mResolver.registerContentObserver(Settings.Global.getUriFor(
293 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
294 updateConstants();
295 }
296
297 @Override
298 public void onChange(boolean selfChange, Uri uri) {
299 updateConstants();
300 }
301
302 private void updateConstants() {
303 synchronized (mLock) {
304 try {
305 mParser.setString(Settings.Global.getString(mResolver,
306 Settings.Global.ALARM_MANAGER_CONSTANTS));
307 } catch (IllegalArgumentException e) {
308 // Failed to parse the settings string, log this and move on
309 // with defaults.
310 Slog.e(TAG, "Bad device idle settings", e);
311 }
312
313 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
314 DEFAULT_MIN_IDLE_COUNT);
315 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
316 DEFAULT_MIN_CHARGING_COUNT);
317 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
318 DEFAULT_MIN_CONNECTIVITY_COUNT);
319 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
320 DEFAULT_MIN_CONTENT_COUNT);
321 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
322 DEFAULT_MIN_READY_JOBS_COUNT);
323 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
324 DEFAULT_HEAVY_USE_FACTOR);
325 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
326 DEFAULT_MODERATE_USE_FACTOR);
327 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
328 DEFAULT_FG_JOB_COUNT);
329 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
330 DEFAULT_BG_NORMAL_JOB_COUNT);
331 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
332 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
333 }
334 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
335 DEFAULT_BG_MODERATE_JOB_COUNT);
336 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
337 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
338 }
339 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
340 DEFAULT_BG_LOW_JOB_COUNT);
341 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
342 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
343 }
344 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
345 DEFAULT_BG_CRITICAL_JOB_COUNT);
346 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
347 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
348 }
349 }
350 }
351
352 void dump(PrintWriter pw) {
353 pw.println(" Settings:");
354
355 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
356 pw.print(MIN_IDLE_COUNT); pw.println();
357
358 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
359 pw.print(MIN_CHARGING_COUNT); pw.println();
360
361 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
362 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
363
364 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
365 pw.print(MIN_CONTENT_COUNT); pw.println();
366
367 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
368 pw.print(MIN_READY_JOBS_COUNT); pw.println();
369
370 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
371 pw.print(HEAVY_USE_FACTOR); pw.println();
372
373 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
374 pw.print(MODERATE_USE_FACTOR); pw.println();
375
376 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
377 pw.print(FG_JOB_COUNT); pw.println();
378
379 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
380 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
381
382 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
383 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
384
385 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
386 pw.print(BG_LOW_JOB_COUNT); pw.println();
387
388 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
389 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
390 }
391 }
392
393 final Constants mConstants;
394
395 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700396 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
397 * still clean up. On reinstall the package will have a new uid.
398 */
399 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
400 @Override
401 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700402 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700403 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700404 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700405 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700406 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700407 // Purge the app's jobs if the whole package was just disabled. When this is
408 // the case the component name will be a bare package name.
409 final String pkgName = getPackageName(intent);
410 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
411 if (pkgName != null && pkgUid != -1) {
412 final String[] changedComponents = intent.getStringArrayExtra(
413 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
414 if (changedComponents != null) {
415 for (String component : changedComponents) {
416 if (component.equals(pkgName)) {
417 if (DEBUG) {
418 Slog.d(TAG, "Package state change: " + pkgName);
419 }
420 try {
421 final int userId = UserHandle.getUserId(pkgUid);
422 IPackageManager pm = AppGlobals.getPackageManager();
423 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
424 if (state == COMPONENT_ENABLED_STATE_DISABLED
425 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
426 if (DEBUG) {
427 Slog.d(TAG, "Removing jobs for package " + pkgName
428 + " in user " + userId);
429 }
430 cancelJobsForUid(pkgUid, true);
431 }
432 } catch (RemoteException e) { /* cannot happen */ }
433 break;
434 }
435 }
436 }
437 } else {
438 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
439 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700440 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700441 // If this is an outright uninstall rather than the first half of an
442 // app update sequence, cancel the jobs associated with the app.
443 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
444 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
445 if (DEBUG) {
446 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
447 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700448 cancelJobsForUid(uidRemoved, true);
Christopher Tate7060b042014-06-09 19:50:00 -0700449 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700450 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700451 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
452 if (DEBUG) {
453 Slog.d(TAG, "Removing jobs for user: " + userId);
454 }
455 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700456 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
457 // Has this package scheduled any jobs, such that we will take action
458 // if it were to be force-stopped?
459 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
460 final String pkgName = intent.getData().getSchemeSpecificPart();
461 if (pkgUid != -1) {
462 List<JobStatus> jobsForUid;
463 synchronized (mLock) {
464 jobsForUid = mJobs.getJobsByUid(pkgUid);
465 }
466 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
467 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
468 if (DEBUG) {
469 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
470 + pkgUid + " has jobs");
471 }
472 setResultCode(Activity.RESULT_OK);
473 break;
474 }
475 }
476 }
477 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
478 // possible force-stop
479 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
480 final String pkgName = intent.getData().getSchemeSpecificPart();
481 if (pkgUid != -1) {
482 if (DEBUG) {
483 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
484 }
485 cancelJobsForPackageAndUid(pkgName, pkgUid);
486 }
Christopher Tate7060b042014-06-09 19:50:00 -0700487 }
488 }
489 };
490
Christopher Tateb5c07882016-05-26 17:11:09 -0700491 private String getPackageName(Intent intent) {
492 Uri uri = intent.getData();
493 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
494 return pkg;
495 }
496
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700497 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
498 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800499 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700500 }
501
502 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800503 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700504 }
505
506 @Override public void onUidActive(int uid) throws RemoteException {
507 }
508
509 @Override public void onUidIdle(int uid) throws RemoteException {
510 cancelJobsForUid(uid, false);
511 }
512 };
513
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800514 public Object getLock() {
515 return mLock;
516 }
517
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700518 public JobStore getJobStore() {
519 return mJobs;
520 }
521
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700522 @Override
523 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700524 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
525 // Let's kick any outstanding jobs for this user.
526 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
527 }
528
529 @Override
530 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700531 // Let's kick any outstanding jobs for this user.
532 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
533 }
534
535 @Override
536 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700537 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700538 }
539
Christopher Tate7060b042014-06-09 19:50:00 -0700540 /**
541 * Entry point from client to schedule the provided job.
542 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
543 * @param job JobInfo object containing execution parameters
544 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700545 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
546 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700547 public int schedule(JobInfo job, int uId) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800548 return scheduleAsPackage(job, uId, null, -1, null);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000549 }
550
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800551 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId,
552 String tag) {
553 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700554 try {
555 if (ActivityManagerNative.getDefault().getAppStartMode(uId,
556 job.getService().getPackageName()) == ActivityManager.APP_START_MODE_DISABLED) {
557 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
558 + " -- package not allowed to start");
559 return JobScheduler.RESULT_FAILURE;
560 }
561 } catch (RemoteException e) {
562 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800563 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
564 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800565 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800566 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800567 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800568 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
569 Slog.w(TAG, "Too many jobs for uid " + uId);
570 throw new IllegalStateException("Apps may not schedule more than "
571 + MAX_JOBS_PER_APP + " distinct jobs");
572 }
573 }
574
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800575 toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700576 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700577 cancelJobImpl(toCancel, jobStatus);
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700578 }
579 startTrackingJob(jobStatus, toCancel);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800580 }
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700581 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700582 return JobScheduler.RESULT_SUCCESS;
583 }
584
585 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800586 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800587 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
588 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
589 for (int i = jobs.size() - 1; i >= 0; i--) {
590 JobStatus job = jobs.get(i);
591 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700592 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800593 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700594 }
Christopher Tate7060b042014-06-09 19:50:00 -0700595 }
596
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600597 public JobInfo getPendingJob(int uid, int jobId) {
598 synchronized (mLock) {
599 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
600 for (int i = jobs.size() - 1; i >= 0; i--) {
601 JobStatus job = jobs.get(i);
602 if (job.getJobId() == jobId) {
603 return job.getJob();
604 }
605 }
606 return null;
607 }
608 }
609
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700610 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700611 List<JobStatus> jobsForUser;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800612 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700613 jobsForUser = mJobs.getJobsByUser(userHandle);
614 }
615 for (int i=0; i<jobsForUser.size(); i++) {
616 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700617 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700618 }
619 }
620
Christopher Tateee7805b2016-07-15 16:56:56 -0700621 void cancelJobsForPackageAndUid(String pkgName, int uid) {
622 List<JobStatus> jobsForUid;
623 synchronized (mLock) {
624 jobsForUid = mJobs.getJobsByUid(uid);
625 }
626 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
627 final JobStatus job = jobsForUid.get(i);
628 if (job.getSourcePackageName().equals(pkgName)) {
629 cancelJobImpl(job, null);
630 }
631 }
632 }
633
Christopher Tate7060b042014-06-09 19:50:00 -0700634 /**
635 * Entry point from client to cancel all jobs originating from their uid.
636 * This will remove the job from the master list, and cancel the job if it was staged for
637 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700638 * @param uid Uid to check against for removal of a job.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700639 * @param forceAll If true, all jobs for the uid will be canceled; if false, only those
640 * whose apps are stopped.
Christopher Tate7060b042014-06-09 19:50:00 -0700641 */
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700642 public void cancelJobsForUid(int uid, boolean forceAll) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700643 List<JobStatus> jobsForUid;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800644 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700645 jobsForUid = mJobs.getJobsByUid(uid);
646 }
647 for (int i=0; i<jobsForUid.size(); i++) {
648 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700649 if (!forceAll) {
650 String packageName = toRemove.getServiceComponent().getPackageName();
651 try {
652 if (ActivityManagerNative.getDefault().getAppStartMode(uid, packageName)
653 != ActivityManager.APP_START_MODE_DISABLED) {
654 continue;
655 }
656 } catch (RemoteException e) {
657 }
658 }
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700659 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700660 }
661 }
662
663 /**
664 * Entry point from client to cancel the job corresponding to the jobId provided.
665 * This will remove the job from the master list, and cancel the job if it was staged for
666 * execution or being executed.
667 * @param uid Uid of the calling client.
668 * @param jobId Id of the job, provided at schedule-time.
669 */
670 public void cancelJob(int uid, int jobId) {
671 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800672 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700673 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700674 }
675 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700676 cancelJobImpl(toCancel, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700677 }
678 }
679
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700680 private void cancelJobImpl(JobStatus cancelled, JobStatus incomingJob) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800681 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700682 stopTrackingJob(cancelled, incomingJob, true /* writeBack */);
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800683 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700684 // Remove from pending queue.
Dianne Hackborn807de782016-04-07 17:54:41 -0700685 if (mPendingJobs.remove(cancelled)) {
686 mJobPackageTracker.noteNonpending(cancelled);
687 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700688 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000689 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800690 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700691 }
Christopher Tate7060b042014-06-09 19:50:00 -0700692 }
693
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800694 void updateUidState(int uid, int procState) {
695 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800696 if (procState == ActivityManager.PROCESS_STATE_TOP) {
697 // Only use this if we are exactly the top app. All others can live
698 // with just the foreground priority. This means that persistent processes
699 // can never be the top app priority... that is fine.
700 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
701 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
702 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800703 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800704 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800705 }
706 }
707 }
708
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700709 @Override
710 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800711 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700712 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600713 // When becoming idle, make sure no jobs are actively running,
714 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700715 for (int i=0; i<mActiveServices.size(); i++) {
716 JobServiceContext jsc = mActiveServices.get(i);
717 final JobStatus executing = jsc.getRunningJob();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600718 if (executing != null
719 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700720 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
721 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700722 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700723 } else {
724 // When coming out of idle, allow thing to start back up.
725 if (mReadyToRock) {
726 if (mLocalDeviceIdleController != null) {
727 if (!mReportedActive) {
728 mReportedActive = true;
729 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700730 }
731 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700732 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700733 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700734 }
735 }
736 }
737
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800738 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000739 // active is true if pending queue contains jobs OR some job is running.
740 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800741 if (mPendingJobs.size() <= 0) {
742 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700743 final JobServiceContext jsc = mActiveServices.get(i);
744 final JobStatus job = jsc.getRunningJob();
745 if (job != null
746 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
747 && !job.dozeWhitelisted) {
748 // We will report active if we have a job running and it is not an exception
749 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800750 active = true;
751 break;
752 }
753 }
754 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000755
756 if (mReportedActive != active) {
757 mReportedActive = active;
758 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800759 mLocalDeviceIdleController.setJobsActive(active);
760 }
761 }
762 }
763
Christopher Tate7060b042014-06-09 19:50:00 -0700764 /**
765 * Initializes the system service.
766 * <p>
767 * Subclasses must define a single argument constructor that accepts the context
768 * and passes it to super.
769 * </p>
770 *
771 * @param context The system server context.
772 */
773 public JobSchedulerService(Context context) {
774 super(context);
Dianne Hackborn970e3f42016-06-01 10:55:13 -0700775 mHandler = new JobHandler(context.getMainLooper());
776 mConstants = new Constants(mHandler);
777 mJobSchedulerStub = new JobSchedulerStub();
778 mJobs = JobStore.initAndGet(this);
779
Christopher Tate7060b042014-06-09 19:50:00 -0700780 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700781 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700782 mControllers.add(ConnectivityController.get(this));
783 mControllers.add(TimeController.get(this));
784 mControllers.add(IdleController.get(this));
785 mControllers.add(BatteryController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800786 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800787 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700788 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700789 }
790
791 @Override
792 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000793 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -0700794 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
795 }
796
797 @Override
798 public void onBootPhase(int phase) {
799 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700800 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +0000801 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -0700802 final IntentFilter filter = new IntentFilter();
803 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
804 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -0700805 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
806 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -0700807 filter.addDataScheme("package");
808 getContext().registerReceiverAsUser(
809 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
810 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
811 getContext().registerReceiverAsUser(
812 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000813 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700814 try {
815 ActivityManagerNative.getDefault().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800816 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
817 | ActivityManager.UID_OBSERVER_IDLE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700818 } catch (RemoteException e) {
819 // ignored; both services live in system_server
820 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700821 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800822 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700823 // Let's go!
824 mReadyToRock = true;
825 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
826 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800827 mLocalDeviceIdleController
828 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700829 // Create the "runners".
830 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
831 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -0700832 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700833 getContext().getMainLooper()));
834 }
835 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -0800836 mJobs.forEachJob(new JobStatusFunctor() {
837 @Override
838 public void process(JobStatus job) {
839 for (int controller = 0; controller < mControllers.size(); controller++) {
840 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800841 sc.maybeStartTrackingJobLocked(job, null);
842 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700843 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800844 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700845 // GO GO GO!
846 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
847 }
Christopher Tate7060b042014-06-09 19:50:00 -0700848 }
849 }
850
851 /**
852 * Called when we have a job status object that we need to insert in our
853 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
854 * about.
855 */
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800856 private void startTrackingJob(JobStatus jobStatus, JobStatus lastJob) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800857 synchronized (mLock) {
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800858 final boolean update = mJobs.add(jobStatus);
859 if (mReadyToRock) {
860 for (int i = 0; i < mControllers.size(); i++) {
861 StateController controller = mControllers.get(i);
862 if (update) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700863 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800864 }
865 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700866 }
Christopher Tate7060b042014-06-09 19:50:00 -0700867 }
Christopher Tate7060b042014-06-09 19:50:00 -0700868 }
869 }
870
871 /**
872 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
873 * object removed.
874 */
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700875 private boolean stopTrackingJob(JobStatus jobStatus, JobStatus incomingJob,
876 boolean writeBack) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800877 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700878 // Remove from store as well as controllers.
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800879 final boolean removed = mJobs.remove(jobStatus, writeBack);
880 if (removed && mReadyToRock) {
881 for (int i=0; i<mControllers.size(); i++) {
882 StateController controller = mControllers.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700883 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800884 }
Christopher Tate7060b042014-06-09 19:50:00 -0700885 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800886 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -0700887 }
Christopher Tate7060b042014-06-09 19:50:00 -0700888 }
889
Shreyas Basarge5db09082016-01-07 13:38:29 +0000890 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700891 for (int i=0; i<mActiveServices.size(); i++) {
892 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700893 final JobStatus executing = jsc.getRunningJob();
894 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000895 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700896 return true;
897 }
898 }
899 return false;
900 }
901
902 /**
903 * @param job JobStatus we are querying against.
904 * @return Whether or not the job represented by the status object is currently being run or
905 * is pending.
906 */
907 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700908 for (int i=0; i<mActiveServices.size(); i++) {
909 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700910 final JobStatus running = serviceContext.getRunningJob();
911 if (running != null && running.matches(job.getUid(), job.getJobId())) {
912 return true;
913 }
914 }
915 return false;
916 }
917
Dianne Hackborn807de782016-04-07 17:54:41 -0700918 void noteJobsPending(List<JobStatus> jobs) {
919 for (int i = jobs.size() - 1; i >= 0; i--) {
920 JobStatus job = jobs.get(i);
921 mJobPackageTracker.notePending(job);
922 }
923 }
924
925 void noteJobsNonpending(List<JobStatus> jobs) {
926 for (int i = jobs.size() - 1; i >= 0; i--) {
927 JobStatus job = jobs.get(i);
928 mJobPackageTracker.noteNonpending(job);
929 }
930 }
931
Christopher Tate7060b042014-06-09 19:50:00 -0700932 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700933 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
934 * specify an override deadline on a failed job (the failed job will run even though it's not
935 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
936 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
937 *
Christopher Tate7060b042014-06-09 19:50:00 -0700938 * @param failureToReschedule Provided job status that we will reschedule.
939 * @return A newly instantiated JobStatus with the same constraints as the last job except
940 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700941 *
942 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700943 */
944 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
945 final long elapsedNowMillis = SystemClock.elapsedRealtime();
946 final JobInfo job = failureToReschedule.getJob();
947
948 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700949 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
950 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -0700951
952 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -0700953 case JobInfo.BACKOFF_POLICY_LINEAR:
954 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -0700955 break;
956 default:
957 if (DEBUG) {
958 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
959 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700960 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
961 delayMillis =
962 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -0700963 break;
964 }
Matthew Williamsd1c06752014-08-22 14:15:28 -0700965 delayMillis =
966 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800967 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -0700968 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800969 for (int ic=0; ic<mControllers.size(); ic++) {
970 StateController controller = mControllers.get(ic);
971 controller.rescheduleForFailure(newJob, failureToReschedule);
972 }
973 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -0700974 }
975
976 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700977 * Called after a periodic has executed so we can reschedule it. We take the last execution
978 * time of the job to be the time of completion (i.e. the time at which this function is
979 * called).
Christopher Tate7060b042014-06-09 19:50:00 -0700980 * This could be inaccurate b/c the job can run for as long as
981 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
982 * to underscheduling at least, rather than if we had taken the last execution time to be the
983 * start of the execution.
984 * @return A new job representing the execution criteria for this instantiation of the
985 * recurring job.
986 */
987 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
988 final long elapsedNow = SystemClock.elapsedRealtime();
989 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700990 long runEarly = 0L;
991
992 // If this periodic was rescheduled it won't have a deadline.
993 if (periodicToReschedule.hasDeadlineConstraint()) {
994 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
995 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000996 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700997 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000998 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
999 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001000
1001 if (DEBUG) {
1002 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1003 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1004 }
1005 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
1006 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
1007 }
1008
1009 // JobCompletedListener implementations.
1010
1011 /**
1012 * A job just finished executing. We fetch the
1013 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1014 * whether we want to reschedule we readd it to the controllers.
1015 * @param jobStatus Completed job.
1016 * @param needsReschedule Whether the implementing class should reschedule this job.
1017 */
1018 @Override
1019 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
1020 if (DEBUG) {
1021 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1022 }
Shreyas Basarge73f10252016-02-11 17:06:13 +00001023 // Do not write back immediately if this is a periodic job. The job may get lost if system
1024 // shuts down before it is added back.
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001025 if (!stopTrackingJob(jobStatus, null, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001026 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001027 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001028 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001029 // We still want to check for jobs to execute, because this job may have
1030 // scheduled a new job under the same job id, and now we can run it.
1031 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001032 return;
1033 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001034 // Note: there is a small window of time in here where, when rescheduling a job,
1035 // we will stop monitoring its content providers. This should be fixed by stopping
1036 // the old job after scheduling the new one, but since we have no lock held here
1037 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -07001038 if (needsReschedule) {
1039 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001040 startTrackingJob(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001041 } else if (jobStatus.getJob().isPeriodic()) {
1042 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001043 startTrackingJob(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001044 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001045 reportActive();
1046 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001047 }
1048
1049 // StateChangedListener implementations.
1050
1051 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001052 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1053 * some controller's state has changed, so as to run through the list of jobs and start/stop
1054 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001055 */
1056 @Override
1057 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001058 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001059 }
1060
1061 @Override
1062 public void onRunJobNow(JobStatus jobStatus) {
1063 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1064 }
1065
Christopher Tate7060b042014-06-09 19:50:00 -07001066 private class JobHandler extends Handler {
1067
1068 public JobHandler(Looper looper) {
1069 super(looper);
1070 }
1071
1072 @Override
1073 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001074 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001075 if (!mReadyToRock) {
1076 return;
1077 }
1078 }
Christopher Tate7060b042014-06-09 19:50:00 -07001079 switch (message.what) {
1080 case MSG_JOB_EXPIRED:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001081 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -07001082 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001083 // runNow can be null, which is a controller's way of indicating that its
1084 // state is such that all ready jobs should be run immediately.
Matthew Williams48a30db2014-09-23 13:39:36 -07001085 if (runNow != null && !mPendingJobs.contains(runNow)
1086 && mJobs.containsJob(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001087 mJobPackageTracker.notePending(runNow);
Christopher Tate7060b042014-06-09 19:50:00 -07001088 mPendingJobs.add(runNow);
1089 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001090 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -07001091 }
Christopher Tate7060b042014-06-09 19:50:00 -07001092 break;
1093 case MSG_CHECK_JOB:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001094 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001095 if (mReportedActive) {
1096 // if jobs are currently being run, queue all ready jobs for execution.
1097 queueReadyJobsForExecutionLockedH();
1098 } else {
1099 // Check the list of jobs and run some of them if we feel inclined.
1100 maybeQueueReadyJobsForExecutionLockedH();
1101 }
1102 }
1103 break;
1104 case MSG_CHECK_JOB_GREEDY:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001105 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001106 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -07001107 }
Christopher Tate7060b042014-06-09 19:50:00 -07001108 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001109 case MSG_STOP_JOB:
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001110 cancelJobImpl((JobStatus)message.obj, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001111 break;
Christopher Tate7060b042014-06-09 19:50:00 -07001112 }
1113 maybeRunPendingJobsH();
1114 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1115 removeMessages(MSG_CHECK_JOB);
1116 }
1117
1118 /**
1119 * Run through list of jobs and execute all possible - at least one is expired so we do
1120 * as many as we can.
1121 */
Matthew Williams48a30db2014-09-23 13:39:36 -07001122 private void queueReadyJobsForExecutionLockedH() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001123 if (DEBUG) {
1124 Slog.d(TAG, "queuing all ready jobs for execution:");
1125 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001126 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001127 mPendingJobs.clear();
1128 mJobs.forEachJob(mReadyQueueFunctor);
1129 mReadyQueueFunctor.postProcess();
1130
Matthew Williams48a30db2014-09-23 13:39:36 -07001131 if (DEBUG) {
1132 final int queuedJobs = mPendingJobs.size();
1133 if (queuedJobs == 0) {
1134 Slog.d(TAG, "No jobs pending.");
1135 } else {
1136 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -07001137 }
Christopher Tate7060b042014-06-09 19:50:00 -07001138 }
1139 }
1140
Christopher Tate2f36fd62016-02-18 18:36:08 -08001141 class ReadyJobQueueFunctor implements JobStatusFunctor {
1142 ArrayList<JobStatus> newReadyJobs;
1143
1144 @Override
1145 public void process(JobStatus job) {
1146 if (isReadyToBeExecutedLocked(job)) {
1147 if (DEBUG) {
1148 Slog.d(TAG, " queued " + job.toShortString());
1149 }
1150 if (newReadyJobs == null) {
1151 newReadyJobs = new ArrayList<JobStatus>();
1152 }
1153 newReadyJobs.add(job);
1154 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
1155 stopJobOnServiceContextLocked(job,
1156 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
1157 }
1158 }
1159
1160 public void postProcess() {
1161 if (newReadyJobs != null) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001162 noteJobsPending(newReadyJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001163 mPendingJobs.addAll(newReadyJobs);
1164 }
1165 newReadyJobs = null;
1166 }
1167 }
1168 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1169
Christopher Tate7060b042014-06-09 19:50:00 -07001170 /**
1171 * The state of at least one job has changed. Here is where we could enforce various
1172 * policies on when we want to execute jobs.
1173 * Right now the policy is such:
1174 * If >1 of the ready jobs is idle mode we send all of them off
1175 * if more than 2 network connectivity jobs are ready we send them all off.
1176 * If more than 4 jobs total are ready we send them all off.
1177 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1178 */
Christopher Tate2f36fd62016-02-18 18:36:08 -08001179 class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1180 int chargingCount;
1181 int idleCount;
1182 int backoffCount;
1183 int connectivityCount;
1184 int contentCount;
1185 List<JobStatus> runnableJobs;
1186
1187 public MaybeReadyJobQueueFunctor() {
1188 reset();
1189 }
1190
1191 // Functor method invoked for each job via JobStore.forEachJob()
1192 @Override
1193 public void process(JobStatus job) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001194 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001195 try {
1196 if (ActivityManagerNative.getDefault().getAppStartMode(job.getUid(),
1197 job.getJob().getService().getPackageName())
1198 == ActivityManager.APP_START_MODE_DISABLED) {
1199 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1200 + job.getJob().toString() + " -- package not allowed to start");
1201 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001202 return;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001203 }
1204 } catch (RemoteException e) {
1205 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001206 if (job.getNumFailures() > 0) {
1207 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -07001208 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001209 if (job.hasIdleConstraint()) {
1210 idleCount++;
1211 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001212 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()
1213 || job.hasNotRoamingConstraint()) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001214 connectivityCount++;
1215 }
1216 if (job.hasChargingConstraint()) {
1217 chargingCount++;
1218 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001219 if (job.hasContentTriggerConstraint()) {
1220 contentCount++;
1221 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001222 if (runnableJobs == null) {
1223 runnableJobs = new ArrayList<>();
1224 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001225 runnableJobs.add(job);
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001226 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001227 stopJobOnServiceContextLocked(job,
1228 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -07001229 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001230 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001231
1232 public void postProcess() {
1233 if (backoffCount > 0 ||
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001234 idleCount >= mConstants.MIN_IDLE_COUNT ||
1235 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1236 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1237 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1238 (runnableJobs != null
1239 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001240 if (DEBUG) {
1241 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
1242 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001243 noteJobsPending(runnableJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001244 mPendingJobs.addAll(runnableJobs);
1245 } else {
1246 if (DEBUG) {
1247 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
1248 }
Christopher Tate7060b042014-06-09 19:50:00 -07001249 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001250
1251 // Be ready for next time
1252 reset();
Matthew Williams48a30db2014-09-23 13:39:36 -07001253 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001254
1255 private void reset() {
1256 chargingCount = 0;
1257 idleCount = 0;
1258 backoffCount = 0;
1259 connectivityCount = 0;
1260 contentCount = 0;
1261 runnableJobs = null;
1262 }
1263 }
1264 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1265
1266 private void maybeQueueReadyJobsForExecutionLockedH() {
1267 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1268
Dianne Hackborn807de782016-04-07 17:54:41 -07001269 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001270 mPendingJobs.clear();
1271 mJobs.forEachJob(mMaybeQueueFunctor);
1272 mMaybeQueueFunctor.postProcess();
Christopher Tate7060b042014-06-09 19:50:00 -07001273 }
1274
1275 /**
1276 * Criteria for moving a job into the pending queue:
1277 * - It's ready.
1278 * - It's not pending.
1279 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001280 * - The user that requested the job is running.
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001281 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -07001282 */
1283 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001284 final boolean jobReady = job.isReady();
1285 final boolean jobPending = mPendingJobs.contains(job);
1286 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001287
1288 final int userId = job.getUserId();
1289 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1290 final boolean componentPresent;
1291 try {
1292 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1293 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1294 userId) != null);
1295 } catch (RemoteException e) {
1296 throw e.rethrowAsRuntimeException();
1297 }
1298
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001299 if (DEBUG) {
1300 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1301 + " ready=" + jobReady + " pending=" + jobPending
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001302 + " active=" + jobActive + " userStarted=" + userStarted
1303 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001304 }
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001305 return userStarted && componentPresent && jobReady && !jobPending && !jobActive;
Christopher Tate7060b042014-06-09 19:50:00 -07001306 }
1307
1308 /**
1309 * Criteria for cancelling an active job:
1310 * - It's not ready
1311 * - It's running on a JSC.
1312 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001313 private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -07001314 return !job.isReady() && isCurrentlyActiveLocked(job);
1315 }
1316
1317 /**
1318 * Reconcile jobs in the pending queue against available execution contexts.
1319 * A controller can force a job into the pending queue even if it's already running, but
1320 * here is where we decide whether to actually execute it.
1321 */
1322 private void maybeRunPendingJobsH() {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001323 synchronized (mLock) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001324 if (DEBUG) {
1325 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1326 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001327 assignJobsToContextsLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001328 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -07001329 }
1330 }
1331 }
1332
Dianne Hackborn807de782016-04-07 17:54:41 -07001333 private int adjustJobPriority(int curPriority, JobStatus job) {
1334 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1335 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001336 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001337 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001338 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001339 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1340 }
1341 }
1342 return curPriority;
1343 }
1344
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001345 private int evaluateJobPriorityLocked(JobStatus job) {
1346 int priority = job.getPriority();
1347 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001348 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001349 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001350 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1351 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001352 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001353 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001354 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001355 }
1356
Christopher Tate7060b042014-06-09 19:50:00 -07001357 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001358 * Takes jobs from pending queue and runs them on available contexts.
1359 * If no contexts are available, preempts lower priority jobs to
1360 * run higher priority ones.
1361 * Lock on mJobs before calling this function.
1362 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001363 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001364 if (DEBUG) {
1365 Slog.d(TAG, printPendingQueue());
1366 }
1367
Dianne Hackborn970510b2016-02-24 16:56:42 -08001368 int memLevel;
1369 try {
1370 memLevel = ActivityManagerNative.getDefault().getMemoryTrimLevel();
1371 } catch (RemoteException e) {
1372 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1373 }
1374 switch (memLevel) {
1375 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001376 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001377 break;
1378 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001379 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001380 break;
1381 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001382 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001383 break;
1384 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001385 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001386 break;
1387 }
1388
1389 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1390 boolean[] act = mTmpAssignAct;
1391 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1392 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001393 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001394 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1395 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001396 final JobStatus status = js.getRunningJob();
1397 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001398 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001399 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1400 numForeground++;
1401 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001402 }
1403 act[i] = false;
1404 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001405 }
1406 if (DEBUG) {
1407 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1408 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001409 for (int i=0; i<mPendingJobs.size(); i++) {
1410 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001411
1412 // If job is already running, go to next job.
1413 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1414 if (jobRunningContext != -1) {
1415 continue;
1416 }
1417
Dianne Hackborn970510b2016-02-24 16:56:42 -08001418 final int priority = evaluateJobPriorityLocked(nextPending);
1419 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001420
Shreyas Basarge5db09082016-01-07 13:38:29 +00001421 // Find a context for nextPending. The context should be available OR
1422 // it should have lowest priority among all running jobs
1423 // (sharing the same Uid as nextPending)
1424 int minPriority = Integer.MAX_VALUE;
1425 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001426 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1427 JobStatus job = contextIdToJobMap[j];
1428 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001429 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001430 if ((numActive < mMaxActiveJobs ||
1431 (priority >= JobInfo.PRIORITY_TOP_APP &&
1432 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001433 (preferredUid == nextPending.getUid() ||
1434 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1435 // This slot is free, and we haven't yet hit the limit on
1436 // concurrent jobs... we can just throw the job in to here.
1437 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001438 break;
1439 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001440 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001441 // the context has a preferred Uid or we have reached the limit on
1442 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001443 continue;
1444 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001445 if (job.getUid() != nextPending.getUid()) {
1446 continue;
1447 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001448 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001449 continue;
1450 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001451 if (minPriority > nextPending.lastEvaluatedPriority) {
1452 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001453 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001454 }
1455 }
1456 if (minPriorityContextId != -1) {
1457 contextIdToJobMap[minPriorityContextId] = nextPending;
1458 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001459 numActive++;
1460 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1461 numForeground++;
1462 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001463 }
1464 }
1465 if (DEBUG) {
1466 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1467 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001468 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001469 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001470 boolean preservePreferredUid = false;
1471 if (act[i]) {
1472 JobStatus js = mActiveServices.get(i).getRunningJob();
1473 if (js != null) {
1474 if (DEBUG) {
1475 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
1476 }
1477 // preferredUid will be set to uid of currently running job.
1478 mActiveServices.get(i).preemptExecutingJob();
1479 preservePreferredUid = true;
1480 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001481 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001482 if (DEBUG) {
1483 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001484 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001485 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001486 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001487 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001488 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001489 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1490 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001491 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001492 if (mPendingJobs.remove(pendingJob)) {
1493 mJobPackageTracker.noteNonpending(pendingJob);
1494 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001495 }
1496 }
1497 if (!preservePreferredUid) {
1498 mActiveServices.get(i).clearPreferredUid();
1499 }
1500 }
1501 }
1502
1503 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1504 for (int i=0; i<map.length; i++) {
1505 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1506 return i;
1507 }
1508 }
1509 return -1;
1510 }
1511
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001512 final class LocalService implements JobSchedulerInternal {
1513
1514 /**
1515 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1516 * jobs are always considered pending.
1517 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001518 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001519 public List<JobInfo> getSystemScheduledPendingJobs() {
1520 synchronized (mLock) {
1521 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1522 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1523 @Override
1524 public void process(JobStatus job) {
1525 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1526 pendingJobs.add(job.getJob());
1527 }
1528 }
1529 });
1530 return pendingJobs;
1531 }
1532 }
1533 }
1534
Shreyas Basarge5db09082016-01-07 13:38:29 +00001535 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001536 * Binder stub trampoline implementation
1537 */
1538 final class JobSchedulerStub extends IJobScheduler.Stub {
1539 /** Cache determination of whether a given app can persist jobs
1540 * key is uid of the calling app; value is undetermined/true/false
1541 */
1542 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1543
1544 // Enforce that only the app itself (or shared uid participant) can schedule a
1545 // job that runs one of the app's services, as well as verifying that the
1546 // named service properly requires the BIND_JOB_SERVICE permission
1547 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001548 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001549 final ComponentName service = job.getService();
1550 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001551 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001552 PackageManager.MATCH_DIRECT_BOOT_AWARE
1553 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001554 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001555 if (si == null) {
1556 throw new IllegalArgumentException("No such service " + service);
1557 }
Christopher Tate7060b042014-06-09 19:50:00 -07001558 if (si.applicationInfo.uid != uid) {
1559 throw new IllegalArgumentException("uid " + uid +
1560 " cannot schedule job in " + service.getPackageName());
1561 }
1562 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1563 throw new IllegalArgumentException("Scheduled service " + service
1564 + " does not require android.permission.BIND_JOB_SERVICE permission");
1565 }
Christopher Tate5568f542014-06-18 13:53:31 -07001566 } catch (RemoteException e) {
1567 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001568 }
1569 }
1570
1571 private boolean canPersistJobs(int pid, int uid) {
1572 // If we get this far we're good to go; all we need to do now is check
1573 // whether the app is allowed to persist its scheduled work.
1574 final boolean canPersist;
1575 synchronized (mPersistCache) {
1576 Boolean cached = mPersistCache.get(uid);
1577 if (cached != null) {
1578 canPersist = cached.booleanValue();
1579 } else {
1580 // Persisting jobs is tantamount to running at boot, so we permit
1581 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1582 // permission
1583 int result = getContext().checkPermission(
1584 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1585 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1586 mPersistCache.put(uid, canPersist);
1587 }
1588 }
1589 return canPersist;
1590 }
1591
1592 // IJobScheduler implementation
1593 @Override
1594 public int schedule(JobInfo job) throws RemoteException {
1595 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001596 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001597 }
1598 final int pid = Binder.getCallingPid();
1599 final int uid = Binder.getCallingUid();
1600
1601 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001602 if (job.isPersisted()) {
1603 if (!canPersistJobs(pid, uid)) {
1604 throw new IllegalArgumentException("Error: requested job be persisted without"
1605 + " holding RECEIVE_BOOT_COMPLETED permission.");
1606 }
1607 }
Christopher Tate7060b042014-06-09 19:50:00 -07001608
Jeff Sharkey785f4942016-07-14 10:31:15 -06001609 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1610 getContext().enforceCallingOrSelfPermission(
1611 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1612 }
1613
Christopher Tate7060b042014-06-09 19:50:00 -07001614 long ident = Binder.clearCallingIdentity();
1615 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001616 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001617 } finally {
1618 Binder.restoreCallingIdentity(ident);
1619 }
1620 }
1621
1622 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001623 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001624 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001625 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001626 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001627 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1628 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001629 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001630
1631 if (packageName == null) {
1632 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001633 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001634
1635 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1636 android.Manifest.permission.UPDATE_DEVICE_STATS);
1637 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1638 throw new SecurityException("Caller uid " + callerUid
1639 + " not permitted to schedule jobs for other apps");
1640 }
1641
Jeff Sharkey4f100402016-05-03 17:44:23 -06001642 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1643 getContext().enforceCallingOrSelfPermission(
1644 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1645 }
1646
Shreyas Basarge968ac752016-01-11 23:09:26 +00001647 long ident = Binder.clearCallingIdentity();
1648 try {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001649 return JobSchedulerService.this.scheduleAsPackage(job, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001650 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001651 } finally {
1652 Binder.restoreCallingIdentity(ident);
1653 }
1654 }
1655
1656 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001657 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1658 final int uid = Binder.getCallingUid();
1659
1660 long ident = Binder.clearCallingIdentity();
1661 try {
1662 return JobSchedulerService.this.getPendingJobs(uid);
1663 } finally {
1664 Binder.restoreCallingIdentity(ident);
1665 }
1666 }
1667
1668 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001669 public JobInfo getPendingJob(int jobId) throws RemoteException {
1670 final int uid = Binder.getCallingUid();
1671
1672 long ident = Binder.clearCallingIdentity();
1673 try {
1674 return JobSchedulerService.this.getPendingJob(uid, jobId);
1675 } finally {
1676 Binder.restoreCallingIdentity(ident);
1677 }
1678 }
1679
1680 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001681 public void cancelAll() throws RemoteException {
1682 final int uid = Binder.getCallingUid();
1683
1684 long ident = Binder.clearCallingIdentity();
1685 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001686 JobSchedulerService.this.cancelJobsForUid(uid, true);
Christopher Tate7060b042014-06-09 19:50:00 -07001687 } finally {
1688 Binder.restoreCallingIdentity(ident);
1689 }
1690 }
1691
1692 @Override
1693 public void cancel(int jobId) throws RemoteException {
1694 final int uid = Binder.getCallingUid();
1695
1696 long ident = Binder.clearCallingIdentity();
1697 try {
1698 JobSchedulerService.this.cancelJob(uid, jobId);
1699 } finally {
1700 Binder.restoreCallingIdentity(ident);
1701 }
1702 }
1703
1704 /**
1705 * "dumpsys" infrastructure
1706 */
1707 @Override
1708 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1709 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1710
1711 long identityToken = Binder.clearCallingIdentity();
1712 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001713 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07001714 } finally {
1715 Binder.restoreCallingIdentity(identityToken);
1716 }
1717 }
Christopher Tate5d346052016-03-08 12:56:08 -08001718
1719 @Override
1720 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
1721 String[] args, ResultReceiver resultReceiver) throws RemoteException {
1722 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
1723 this, in, out, err, args, resultReceiver);
1724 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001725 };
1726
Christopher Tate5d346052016-03-08 12:56:08 -08001727 // Shell command infrastructure: run the given job immediately
1728 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
1729 if (DEBUG) {
1730 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
1731 + " " + jobId + " f=" + force);
1732 }
1733
1734 try {
1735 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0, userId);
1736 if (uid < 0) {
1737 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
1738 }
1739
1740 synchronized (mLock) {
1741 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
1742 if (js == null) {
1743 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
1744 }
1745
1746 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
1747 if (!js.isConstraintsSatisfied()) {
1748 js.overrideState = 0;
1749 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
1750 }
1751
1752 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
1753 }
1754 } catch (RemoteException e) {
1755 // can't happen
1756 }
1757 return 0;
1758 }
1759
Shreyas Basarge5db09082016-01-07 13:38:29 +00001760 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1761 StringBuilder s = new StringBuilder(initial + ": ");
1762 for (int i=0; i<map.length; i++) {
1763 s.append("(")
1764 .append(map[i] == null? -1: map[i].getJobId())
1765 .append(map[i] == null? -1: map[i].getUid())
1766 .append(")" );
1767 }
1768 return s.toString();
1769 }
1770
1771 private String printPendingQueue() {
1772 StringBuilder s = new StringBuilder("Pending queue: ");
1773 Iterator<JobStatus> it = mPendingJobs.iterator();
1774 while (it.hasNext()) {
1775 JobStatus js = it.next();
1776 s.append("(")
1777 .append(js.getJob().getId())
1778 .append(", ")
1779 .append(js.getUid())
1780 .append(") ");
1781 }
1782 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001783 }
Christopher Tate7060b042014-06-09 19:50:00 -07001784
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001785 static void dumpHelp(PrintWriter pw) {
1786 pw.println("Job Scheduler (jobscheduler) dump options:");
1787 pw.println(" [-h] [package] ...");
1788 pw.println(" -h: print this help");
1789 pw.println(" [package] is an optional package name to limit the output to.");
1790 }
1791
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001792 void dumpInternal(final PrintWriter pw, String[] args) {
1793 int filterUid = -1;
1794 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001795 int opti = 0;
1796 while (opti < args.length) {
1797 String arg = args[opti];
1798 if ("-h".equals(arg)) {
1799 dumpHelp(pw);
1800 return;
1801 } else if ("-a".equals(arg)) {
1802 // Ignore, we always dump all.
1803 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
1804 pw.println("Unknown option: " + arg);
1805 return;
1806 } else {
1807 break;
1808 }
1809 opti++;
1810 }
1811 if (opti < args.length) {
1812 String pkg = args[opti];
1813 try {
1814 filterUid = getContext().getPackageManager().getPackageUid(pkg,
1815 PackageManager.MATCH_UNINSTALLED_PACKAGES);
1816 } catch (NameNotFoundException ignored) {
1817 pw.println("Invalid package: " + pkg);
1818 return;
1819 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001820 }
1821 }
1822
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001823 final int filterUidFinal = UserHandle.getAppId(filterUid);
Christopher Tatef973a7b2014-08-29 12:54:08 -07001824 final long now = SystemClock.elapsedRealtime();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001825 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001826 mConstants.dump(pw);
1827 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001828 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001829 pw.print("Registered ");
1830 pw.print(mJobs.size());
1831 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07001832 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001833 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
1834 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001835 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001836 public int compare(JobStatus o1, JobStatus o2) {
1837 int uid1 = o1.getUid();
1838 int uid2 = o2.getUid();
1839 int id1 = o1.getJobId();
1840 int id2 = o2.getJobId();
1841 if (uid1 != uid2) {
1842 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001843 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001844 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001845 }
1846 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001847 for (JobStatus job : jobs) {
1848 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
1849 pw.println(job.toShortStringExceptUniqueId());
1850
1851 // Skip printing details if the caller requested a filter
1852 if (!job.shouldDump(filterUidFinal)) {
1853 continue;
1854 }
1855
1856 job.dump(pw, " ", true);
1857 pw.print(" Ready: ");
1858 pw.print(mHandler.isReadyToBeExecutedLocked(job));
1859 pw.print(" (job=");
1860 pw.print(job.isReady());
1861 pw.print(" pending=");
1862 pw.print(mPendingJobs.contains(job));
1863 pw.print(" active=");
1864 pw.print(isCurrentlyActiveLocked(job));
1865 pw.print(" user=");
1866 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
1867 pw.println(")");
1868 }
Christopher Tate7060b042014-06-09 19:50:00 -07001869 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07001870 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07001871 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001872 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07001873 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001874 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07001875 }
1876 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001877 pw.println("Uid priority overrides:");
1878 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001879 int uid = mUidPriorityOverride.keyAt(i);
1880 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
1881 pw.print(" "); pw.print(UserHandle.formatUid(uid));
1882 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
1883 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001884 }
1885 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001886 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07001887 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001888 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
1889 pw.println();
1890 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001891 pw.println("Pending queue:");
1892 for (int i=0; i<mPendingJobs.size(); i++) {
1893 JobStatus job = mPendingJobs.get(i);
1894 pw.print(" Pending #"); pw.print(i); pw.print(": ");
1895 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08001896 job.dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001897 int priority = evaluateJobPriorityLocked(job);
1898 if (priority != JobInfo.PRIORITY_DEFAULT) {
1899 pw.print(" Evaluated priority: "); pw.println(priority);
1900 }
1901 pw.print(" Tag: "); pw.println(job.getTag());
1902 }
Christopher Tate7060b042014-06-09 19:50:00 -07001903 pw.println();
1904 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001905 for (int i=0; i<mActiveServices.size(); i++) {
1906 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001907 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Shreyas Basarge5db09082016-01-07 13:38:29 +00001908 if (jsc.getRunningJob() == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001909 pw.println("inactive");
Christopher Tate7060b042014-06-09 19:50:00 -07001910 continue;
1911 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001912 pw.println(jsc.getRunningJob().toShortString());
1913 pw.print(" Running for: ");
1914 TimeUtils.formatDuration(now - jsc.getExecutionStartTimeElapsed(), pw);
1915 pw.print(", timeout at: ");
1916 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - now, pw);
1917 pw.println();
1918 jsc.getRunningJob().dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001919 int priority = evaluateJobPriorityLocked(jsc.getRunningJob());
1920 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001921 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001922 }
Christopher Tate7060b042014-06-09 19:50:00 -07001923 }
1924 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001925 if (filterUid == -1) {
1926 pw.println();
1927 pw.print("mReadyToRock="); pw.println(mReadyToRock);
1928 pw.print("mReportedActive="); pw.println(mReportedActive);
1929 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
1930 }
Christopher Tate7060b042014-06-09 19:50:00 -07001931 }
1932 pw.println();
1933 }
1934}