blob: 7c231ff45434b5885dfd1bda183e33684da40643 [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;
Christopher Tate5568f542014-06-18 13:53:31 -070033import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070034import android.app.IUidObserver;
Christopher Tate7060b042014-06-09 19:50:00 -070035import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000036import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070037import android.app.job.JobScheduler;
38import android.app.job.JobService;
Shreyas Basarge5db09082016-01-07 13:38:29 +000039import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070040import android.content.BroadcastReceiver;
41import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070042import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070043import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070046import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070047import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070048import android.content.pm.ServiceInfo;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060049import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070050import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070051import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070052import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070053import android.os.Binder;
54import android.os.Handler;
55import android.os.Looper;
56import android.os.Message;
Shreyas Basargecbf5ae92016-03-08 16:13:06 +000057import android.os.Process;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070058import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070059import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080060import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070061import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070062import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070063import android.os.SystemClock;
64import android.os.UserHandle;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070065import android.provider.Settings;
66import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070067import android.util.Slog;
68import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080069import android.util.SparseIntArray;
70import android.util.TimeUtils;
Christopher Tate5d346052016-03-08 12:56:08 -080071
Dianne Hackbornfdb19562014-07-11 16:03:36 -070072import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070073import com.android.internal.app.procstats.ProcessStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070074import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060075import com.android.internal.util.DumpUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080076import com.android.server.DeviceIdleController;
77import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080078import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080079import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070080import com.android.server.job.controllers.BatteryController;
81import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080082import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070083import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070084import com.android.server.job.controllers.IdleController;
85import com.android.server.job.controllers.JobStatus;
86import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070087import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070088import 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;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800136 /** Need direct access to this for testing. */
137 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700138 /** Need direct access to this for testing. */
139 StorageController mStorageController;
Christopher Tate7060b042014-06-09 19:50:00 -0700140 /**
141 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
142 * when ready to execute them.
143 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700144 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700145
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700146 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700147
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700148 final JobHandler mHandler;
149 final JobSchedulerStub mJobSchedulerStub;
150
151 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700152 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800153 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700154
155 /**
156 * Set to true once we are allowed to run third party apps.
157 */
158 boolean mReadyToRock;
159
Christopher Tate7060b042014-06-09 19:50:00 -0700160 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800161 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800162 */
163 boolean mReportedActive;
164
165 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800166 * Current limit on the number of concurrent JobServiceContext entries we want to
167 * keep actively running a job.
168 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700169 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800170
171 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800172 * Which uids are currently in the foreground.
173 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800174 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
175
176 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
177
178 /**
179 * This array essentially stores the state of mActiveServices array.
180 * The ith index stores the job present on the ith JobServiceContext.
181 * We manipulate this array until we arrive at what jobs should be running on
182 * what JobServiceContext.
183 */
184 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
185 /**
186 * Indicates whether we need to act on this jobContext id
187 */
188 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
189 /**
190 * The uid whose jobs we would like to assign to a context.
191 */
192 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800193
194 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700195 * All times are in milliseconds. These constants are kept synchronized with the system
196 * global Settings. Any access to this class or its fields should be done while
197 * holding the JobSchedulerService.mLock lock.
198 */
199 private final class Constants extends ContentObserver {
200 // Key names stored in the settings value.
201 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
202 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800203 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700204 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700205 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
206 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
207 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
208 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
209 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
210 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
211 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
212 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
213 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
214 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
215
216 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
217 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800218 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700219 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700220 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
221 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
222 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
223 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
224 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
225 private static final int DEFAULT_FG_JOB_COUNT = 4;
226 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
227 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700228 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700229 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
230
231 /**
232 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
233 * early.
234 */
235 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
236 /**
237 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
238 * things early.
239 */
240 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
241 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800242 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
243 * schedule things early.
244 */
245 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
246 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700247 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
248 * schedule things early.
249 */
250 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
251 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700252 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
253 * things early. 1 == Run connectivity jobs as soon as ready.
254 */
255 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
256 /**
257 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
258 * schedule things early.
259 */
260 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
261 /**
262 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
263 * running some work early. This (and thus the other min counts) is now set to 1, to
264 * prevent any batching at this level. Since we now do batching through doze, that is
265 * a much better mechanism.
266 */
267 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
268 /**
269 * This is the job execution factor that is considered to be heavy use of the system.
270 */
271 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
272 /**
273 * This is the job execution factor that is considered to be moderate use of the system.
274 */
275 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
276 /**
277 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
278 */
279 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
280 /**
281 * The maximum number of background jobs we allow when the system is in a normal
282 * memory state.
283 */
284 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
285 /**
286 * The maximum number of background jobs we allow when the system is in a moderate
287 * memory state.
288 */
289 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
290 /**
291 * The maximum number of background jobs we allow when the system is in a low
292 * memory state.
293 */
294 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
295 /**
296 * The maximum number of background jobs we allow when the system is in a critical
297 * memory state.
298 */
299 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
300
301 private ContentResolver mResolver;
302 private final KeyValueListParser mParser = new KeyValueListParser(',');
303
304 public Constants(Handler handler) {
305 super(handler);
306 }
307
308 public void start(ContentResolver resolver) {
309 mResolver = resolver;
310 mResolver.registerContentObserver(Settings.Global.getUriFor(
311 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
312 updateConstants();
313 }
314
315 @Override
316 public void onChange(boolean selfChange, Uri uri) {
317 updateConstants();
318 }
319
320 private void updateConstants() {
321 synchronized (mLock) {
322 try {
323 mParser.setString(Settings.Global.getString(mResolver,
324 Settings.Global.ALARM_MANAGER_CONSTANTS));
325 } catch (IllegalArgumentException e) {
326 // Failed to parse the settings string, log this and move on
327 // with defaults.
328 Slog.e(TAG, "Bad device idle settings", e);
329 }
330
331 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
332 DEFAULT_MIN_IDLE_COUNT);
333 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
334 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800335 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
336 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700337 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
338 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700339 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
340 DEFAULT_MIN_CONNECTIVITY_COUNT);
341 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
342 DEFAULT_MIN_CONTENT_COUNT);
343 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
344 DEFAULT_MIN_READY_JOBS_COUNT);
345 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
346 DEFAULT_HEAVY_USE_FACTOR);
347 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
348 DEFAULT_MODERATE_USE_FACTOR);
349 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
350 DEFAULT_FG_JOB_COUNT);
351 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
352 DEFAULT_BG_NORMAL_JOB_COUNT);
353 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
354 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
355 }
356 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
357 DEFAULT_BG_MODERATE_JOB_COUNT);
358 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
359 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
360 }
361 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
362 DEFAULT_BG_LOW_JOB_COUNT);
363 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
364 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
365 }
366 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
367 DEFAULT_BG_CRITICAL_JOB_COUNT);
368 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
369 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
370 }
371 }
372 }
373
374 void dump(PrintWriter pw) {
375 pw.println(" Settings:");
376
377 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
378 pw.print(MIN_IDLE_COUNT); pw.println();
379
380 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
381 pw.print(MIN_CHARGING_COUNT); pw.println();
382
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800383 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
384 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
385
Dianne Hackborn532ea262017-03-17 17:50:55 -0700386 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
387 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
388
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700389 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
390 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
391
392 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
393 pw.print(MIN_CONTENT_COUNT); pw.println();
394
395 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
396 pw.print(MIN_READY_JOBS_COUNT); pw.println();
397
398 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
399 pw.print(HEAVY_USE_FACTOR); pw.println();
400
401 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
402 pw.print(MODERATE_USE_FACTOR); pw.println();
403
404 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
405 pw.print(FG_JOB_COUNT); pw.println();
406
407 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
408 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
409
410 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
411 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
412
413 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
414 pw.print(BG_LOW_JOB_COUNT); pw.println();
415
416 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
417 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
418 }
419 }
420
421 final Constants mConstants;
422
423 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700424 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
425 * still clean up. On reinstall the package will have a new uid.
426 */
427 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
428 @Override
429 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700430 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700431 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700432 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700433 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700434 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700435 // Purge the app's jobs if the whole package was just disabled. When this is
436 // the case the component name will be a bare package name.
437 final String pkgName = getPackageName(intent);
438 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
439 if (pkgName != null && pkgUid != -1) {
440 final String[] changedComponents = intent.getStringArrayExtra(
441 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
442 if (changedComponents != null) {
443 for (String component : changedComponents) {
444 if (component.equals(pkgName)) {
445 if (DEBUG) {
446 Slog.d(TAG, "Package state change: " + pkgName);
447 }
448 try {
449 final int userId = UserHandle.getUserId(pkgUid);
450 IPackageManager pm = AppGlobals.getPackageManager();
451 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
452 if (state == COMPONENT_ENABLED_STATE_DISABLED
453 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
454 if (DEBUG) {
455 Slog.d(TAG, "Removing jobs for package " + pkgName
456 + " in user " + userId);
457 }
Dianne Hackborne07641d2016-11-09 15:07:23 -0800458 cancelJobsForUid(pkgUid);
Christopher Tateb5c07882016-05-26 17:11:09 -0700459 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700460 } catch (RemoteException|IllegalArgumentException e) {
461 /*
462 * IllegalArgumentException means that the package doesn't exist.
463 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
464 * behind outright uninstall, so by the time we try to act it's gone.
465 * We don't need to act on this PACKAGE_CHANGED when this happens;
466 * we'll get a PACKAGE_REMOVED later and clean up then.
467 *
468 * RemoteException can't actually happen; the package manager is
469 * running in this same process.
470 */
471 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700472 break;
473 }
474 }
475 }
476 } else {
477 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
478 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700479 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700480 // If this is an outright uninstall rather than the first half of an
481 // app update sequence, cancel the jobs associated with the app.
482 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
483 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
484 if (DEBUG) {
485 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
486 }
Dianne Hackborne07641d2016-11-09 15:07:23 -0800487 cancelJobsForUid(uidRemoved);
Christopher Tate7060b042014-06-09 19:50:00 -0700488 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700489 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700490 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
491 if (DEBUG) {
492 Slog.d(TAG, "Removing jobs for user: " + userId);
493 }
494 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700495 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
496 // Has this package scheduled any jobs, such that we will take action
497 // if it were to be force-stopped?
498 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
499 final String pkgName = intent.getData().getSchemeSpecificPart();
500 if (pkgUid != -1) {
501 List<JobStatus> jobsForUid;
502 synchronized (mLock) {
503 jobsForUid = mJobs.getJobsByUid(pkgUid);
504 }
505 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
506 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
507 if (DEBUG) {
508 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
509 + pkgUid + " has jobs");
510 }
511 setResultCode(Activity.RESULT_OK);
512 break;
513 }
514 }
515 }
516 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
517 // possible force-stop
518 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
519 final String pkgName = intent.getData().getSchemeSpecificPart();
520 if (pkgUid != -1) {
521 if (DEBUG) {
522 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
523 }
524 cancelJobsForPackageAndUid(pkgName, pkgUid);
525 }
Christopher Tate7060b042014-06-09 19:50:00 -0700526 }
527 }
528 };
529
Christopher Tateb5c07882016-05-26 17:11:09 -0700530 private String getPackageName(Intent intent) {
531 Uri uri = intent.getData();
532 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
533 return pkg;
534 }
535
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700536 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Sudheer Shanka80255802017-03-04 14:48:53 -0800537 @Override public void onUidStateChanged(int uid, int procState,
538 long procStateSeq) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800539 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700540 }
541
Dianne Hackborne07641d2016-11-09 15:07:23 -0800542 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800543 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800544 if (disabled) {
545 cancelJobsForUid(uid);
546 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700547 }
548
549 @Override public void onUidActive(int uid) throws RemoteException {
550 }
551
Dianne Hackborne07641d2016-11-09 15:07:23 -0800552 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
553 if (disabled) {
554 cancelJobsForUid(uid);
555 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700556 }
557 };
558
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800559 public Object getLock() {
560 return mLock;
561 }
562
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700563 public JobStore getJobStore() {
564 return mJobs;
565 }
566
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700567 @Override
568 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700569 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
570 // Let's kick any outstanding jobs for this user.
571 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
572 }
573
574 @Override
575 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700576 // Let's kick any outstanding jobs for this user.
577 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
578 }
579
580 @Override
581 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700582 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700583 }
584
Christopher Tate7060b042014-06-09 19:50:00 -0700585 /**
586 * Entry point from client to schedule the provided job.
587 * This cancels the job if it's already been scheduled, and replaces it with the one provided.
588 * @param job JobInfo object containing execution parameters
589 * @param uId The package identifier of the application this job is for.
Christopher Tate7060b042014-06-09 19:50:00 -0700590 * @return Result of this operation. See <code>JobScheduler#RESULT_*</code> return codes.
591 */
Matthew Williams900c67f2014-07-09 12:46:53 -0700592 public int schedule(JobInfo job, int uId) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800593 return scheduleAsPackage(job, uId, null, -1, null);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000594 }
595
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800596 public int scheduleAsPackage(JobInfo job, int uId, String packageName, int userId,
597 String tag) {
598 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700599 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800600 if (ActivityManager.getService().isAppStartModeDisabled(uId,
601 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700602 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
603 + " -- package not allowed to start");
604 return JobScheduler.RESULT_FAILURE;
605 }
606 } catch (RemoteException e) {
607 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800608 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
609 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800610 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800611 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800612 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800613 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
614 Slog.w(TAG, "Too many jobs for uid " + uId);
615 throw new IllegalStateException("Apps may not schedule more than "
616 + MAX_JOBS_PER_APP + " distinct jobs");
617 }
618 }
619
Dianne Hackborna47223f2017-03-30 13:49:13 -0700620 // This may throw a SecurityException.
621 jobStatus.prepare(ActivityManager.getService());
622
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800623 toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700624 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700625 cancelJobImpl(toCancel, jobStatus);
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700626 }
627 startTrackingJob(jobStatus, toCancel);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800628 }
Matthew Williamsbafeeb92014-08-08 11:51:06 -0700629 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -0700630 return JobScheduler.RESULT_SUCCESS;
631 }
632
633 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800634 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800635 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
636 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
637 for (int i = jobs.size() - 1; i >= 0; i--) {
638 JobStatus job = jobs.get(i);
639 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700640 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800641 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700642 }
Christopher Tate7060b042014-06-09 19:50:00 -0700643 }
644
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600645 public JobInfo getPendingJob(int uid, int jobId) {
646 synchronized (mLock) {
647 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
648 for (int i = jobs.size() - 1; i >= 0; i--) {
649 JobStatus job = jobs.get(i);
650 if (job.getJobId() == jobId) {
651 return job.getJob();
652 }
653 }
654 return null;
655 }
656 }
657
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700658 void cancelJobsForUser(int userHandle) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700659 List<JobStatus> jobsForUser;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800660 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700661 jobsForUser = mJobs.getJobsByUser(userHandle);
662 }
663 for (int i=0; i<jobsForUser.size(); i++) {
664 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700665 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700666 }
667 }
668
Christopher Tateee7805b2016-07-15 16:56:56 -0700669 void cancelJobsForPackageAndUid(String pkgName, int uid) {
670 List<JobStatus> jobsForUid;
671 synchronized (mLock) {
672 jobsForUid = mJobs.getJobsByUid(uid);
673 }
674 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
675 final JobStatus job = jobsForUid.get(i);
676 if (job.getSourcePackageName().equals(pkgName)) {
677 cancelJobImpl(job, null);
678 }
679 }
680 }
681
Christopher Tate7060b042014-06-09 19:50:00 -0700682 /**
683 * Entry point from client to cancel all jobs originating from their uid.
684 * This will remove the job from the master list, and cancel the job if it was staged for
685 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700686 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800687 *
Christopher Tate7060b042014-06-09 19:50:00 -0700688 */
Dianne Hackborne07641d2016-11-09 15:07:23 -0800689 public void cancelJobsForUid(int uid) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700690 List<JobStatus> jobsForUid;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800691 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700692 jobsForUid = mJobs.getJobsByUid(uid);
693 }
694 for (int i=0; i<jobsForUid.size(); i++) {
695 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700696 cancelJobImpl(toRemove, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700697 }
698 }
699
700 /**
701 * Entry point from client to cancel the job corresponding to the jobId provided.
702 * This will remove the job from the master list, and cancel the job if it was staged for
703 * execution or being executed.
704 * @param uid Uid of the calling client.
705 * @param jobId Id of the job, provided at schedule-time.
706 */
707 public void cancelJob(int uid, int jobId) {
708 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800709 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700710 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Matthew Williams48a30db2014-09-23 13:39:36 -0700711 }
712 if (toCancel != null) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700713 cancelJobImpl(toCancel, null);
Christopher Tate7060b042014-06-09 19:50:00 -0700714 }
715 }
716
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700717 private void cancelJobImpl(JobStatus cancelled, JobStatus incomingJob) {
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800718 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700719 cancelled.unprepare(ActivityManager.getService());
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700720 stopTrackingJob(cancelled, incomingJob, true /* writeBack */);
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800721 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -0700722 // Remove from pending queue.
Dianne Hackborn807de782016-04-07 17:54:41 -0700723 if (mPendingJobs.remove(cancelled)) {
724 mJobPackageTracker.noteNonpending(cancelled);
725 }
Matthew Williams48a30db2014-09-23 13:39:36 -0700726 // Cancel if running.
Shreyas Basarge5db09082016-01-07 13:38:29 +0000727 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800728 reportActive();
Matthew Williams48a30db2014-09-23 13:39:36 -0700729 }
Christopher Tate7060b042014-06-09 19:50:00 -0700730 }
731
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800732 void updateUidState(int uid, int procState) {
733 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800734 if (procState == ActivityManager.PROCESS_STATE_TOP) {
735 // Only use this if we are exactly the top app. All others can live
736 // with just the foreground priority. This means that persistent processes
737 // can never be the top app priority... that is fine.
738 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
739 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
740 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800741 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800742 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800743 }
744 }
745 }
746
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700747 @Override
748 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800749 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700750 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600751 // When becoming idle, make sure no jobs are actively running,
752 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700753 for (int i=0; i<mActiveServices.size(); i++) {
754 JobServiceContext jsc = mActiveServices.get(i);
755 final JobStatus executing = jsc.getRunningJob();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600756 if (executing != null
757 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700758 jsc.cancelExecutingJob(JobParameters.REASON_DEVICE_IDLE);
759 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700760 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700761 } else {
762 // When coming out of idle, allow thing to start back up.
763 if (mReadyToRock) {
764 if (mLocalDeviceIdleController != null) {
765 if (!mReportedActive) {
766 mReportedActive = true;
767 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700768 }
769 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700770 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700771 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700772 }
773 }
774 }
775
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800776 void reportActive() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000777 // active is true if pending queue contains jobs OR some job is running.
778 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800779 if (mPendingJobs.size() <= 0) {
780 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700781 final JobServiceContext jsc = mActiveServices.get(i);
782 final JobStatus job = jsc.getRunningJob();
783 if (job != null
784 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
785 && !job.dozeWhitelisted) {
786 // We will report active if we have a job running and it is not an exception
787 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800788 active = true;
789 break;
790 }
791 }
792 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000793
794 if (mReportedActive != active) {
795 mReportedActive = active;
796 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800797 mLocalDeviceIdleController.setJobsActive(active);
798 }
799 }
800 }
801
Christopher Tate7060b042014-06-09 19:50:00 -0700802 /**
803 * Initializes the system service.
804 * <p>
805 * Subclasses must define a single argument constructor that accepts the context
806 * and passes it to super.
807 * </p>
808 *
809 * @param context The system server context.
810 */
811 public JobSchedulerService(Context context) {
812 super(context);
Dianne Hackborn970e3f42016-06-01 10:55:13 -0700813 mHandler = new JobHandler(context.getMainLooper());
814 mConstants = new Constants(mHandler);
815 mJobSchedulerStub = new JobSchedulerStub();
816 mJobs = JobStore.initAndGet(this);
817
Christopher Tate7060b042014-06-09 19:50:00 -0700818 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700819 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700820 mControllers.add(ConnectivityController.get(this));
821 mControllers.add(TimeController.get(this));
822 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800823 mBatteryController = BatteryController.get(this);
824 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700825 mStorageController = StorageController.get(this);
826 mControllers.add(mStorageController);
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800827 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800828 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700829 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate7060b042014-06-09 19:50:00 -0700830 }
831
832 @Override
833 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000834 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -0700835 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
836 }
837
838 @Override
839 public void onBootPhase(int phase) {
840 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700841 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +0000842 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -0700843 final IntentFilter filter = new IntentFilter();
844 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
845 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -0700846 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
847 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -0700848 filter.addDataScheme("package");
849 getContext().registerReceiverAsUser(
850 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
851 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
852 getContext().registerReceiverAsUser(
853 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000854 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700855 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800856 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800857 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800858 | ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN,
859 null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700860 } catch (RemoteException e) {
861 // ignored; both services live in system_server
862 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700863 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800864 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700865 // Let's go!
866 mReadyToRock = true;
867 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
868 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800869 mLocalDeviceIdleController
870 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700871 // Create the "runners".
872 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
873 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -0700874 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700875 getContext().getMainLooper()));
876 }
877 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -0800878 mJobs.forEachJob(new JobStatusFunctor() {
879 @Override
880 public void process(JobStatus job) {
881 for (int controller = 0; controller < mControllers.size(); controller++) {
882 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800883 sc.maybeStartTrackingJobLocked(job, null);
884 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700885 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800886 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700887 // GO GO GO!
888 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
889 }
Christopher Tate7060b042014-06-09 19:50:00 -0700890 }
891 }
892
893 /**
894 * Called when we have a job status object that we need to insert in our
895 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
896 * about.
897 */
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800898 private void startTrackingJob(JobStatus jobStatus, JobStatus lastJob) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800899 synchronized (mLock) {
Dianne Hackborna47223f2017-03-30 13:49:13 -0700900 if (!jobStatus.isPrepared()) {
901 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
902 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800903 final boolean update = mJobs.add(jobStatus);
904 if (mReadyToRock) {
905 for (int i = 0; i < mControllers.size(); i++) {
906 StateController controller = mControllers.get(i);
907 if (update) {
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700908 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800909 }
910 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700911 }
Christopher Tate7060b042014-06-09 19:50:00 -0700912 }
Christopher Tate7060b042014-06-09 19:50:00 -0700913 }
914 }
915
916 /**
917 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
918 * object removed.
919 */
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700920 private boolean stopTrackingJob(JobStatus jobStatus, JobStatus incomingJob,
921 boolean writeBack) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800922 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700923 // Remove from store as well as controllers.
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800924 final boolean removed = mJobs.remove(jobStatus, writeBack);
925 if (removed && mReadyToRock) {
926 for (int i=0; i<mControllers.size(); i++) {
927 StateController controller = mControllers.get(i);
Dianne Hackborn141f11c2016-04-05 15:46:12 -0700928 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800929 }
Christopher Tate7060b042014-06-09 19:50:00 -0700930 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -0800931 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -0700932 }
Christopher Tate7060b042014-06-09 19:50:00 -0700933 }
934
Shreyas Basarge5db09082016-01-07 13:38:29 +0000935 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700936 for (int i=0; i<mActiveServices.size(); i++) {
937 JobServiceContext jsc = mActiveServices.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700938 final JobStatus executing = jsc.getRunningJob();
939 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000940 jsc.cancelExecutingJob(reason);
Christopher Tate7060b042014-06-09 19:50:00 -0700941 return true;
942 }
943 }
944 return false;
945 }
946
947 /**
948 * @param job JobStatus we are querying against.
949 * @return Whether or not the job represented by the status object is currently being run or
950 * is pending.
951 */
952 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700953 for (int i=0; i<mActiveServices.size(); i++) {
954 JobServiceContext serviceContext = mActiveServices.get(i);
Christopher Tateeafb5352016-10-04 16:34:48 -0700955 // The 'unsafe' direct-internal-reference running-job inspector is okay to
956 // use here because we are already holding the necessary lock *and* we
957 // immediately discard the returned object reference, if any; we return
958 // only a boolean state indicator to the caller.
959 final JobStatus running = serviceContext.getRunningJobUnsafeLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700960 if (running != null && running.matches(job.getUid(), job.getJobId())) {
961 return true;
962 }
963 }
964 return false;
965 }
966
Dianne Hackborn807de782016-04-07 17:54:41 -0700967 void noteJobsPending(List<JobStatus> jobs) {
968 for (int i = jobs.size() - 1; i >= 0; i--) {
969 JobStatus job = jobs.get(i);
970 mJobPackageTracker.notePending(job);
971 }
972 }
973
974 void noteJobsNonpending(List<JobStatus> jobs) {
975 for (int i = jobs.size() - 1; i >= 0; i--) {
976 JobStatus job = jobs.get(i);
977 mJobPackageTracker.noteNonpending(job);
978 }
979 }
980
Christopher Tate7060b042014-06-09 19:50:00 -0700981 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -0700982 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
983 * specify an override deadline on a failed job (the failed job will run even though it's not
984 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
985 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
986 *
Christopher Tate7060b042014-06-09 19:50:00 -0700987 * @param failureToReschedule Provided job status that we will reschedule.
988 * @return A newly instantiated JobStatus with the same constraints as the last job except
989 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -0700990 *
991 * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
Christopher Tate7060b042014-06-09 19:50:00 -0700992 */
993 private JobStatus getRescheduleJobForFailure(JobStatus failureToReschedule) {
994 final long elapsedNowMillis = SystemClock.elapsedRealtime();
995 final JobInfo job = failureToReschedule.getJob();
996
997 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -0700998 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
999 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001000
1001 switch (job.getBackoffPolicy()) {
Matthew Williamsd1c06752014-08-22 14:15:28 -07001002 case JobInfo.BACKOFF_POLICY_LINEAR:
1003 delayMillis = initialBackoffMillis * backoffAttempts;
Christopher Tate7060b042014-06-09 19:50:00 -07001004 break;
1005 default:
1006 if (DEBUG) {
1007 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1008 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001009 case JobInfo.BACKOFF_POLICY_EXPONENTIAL:
1010 delayMillis =
1011 (long) Math.scalb(initialBackoffMillis, backoffAttempts - 1);
Christopher Tate7060b042014-06-09 19:50:00 -07001012 break;
1013 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001014 delayMillis =
1015 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001016 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Matthew Williamsd1c06752014-08-22 14:15:28 -07001017 JobStatus.NO_LATEST_RUNTIME, backoffAttempts);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001018 for (int ic=0; ic<mControllers.size(); ic++) {
1019 StateController controller = mControllers.get(ic);
1020 controller.rescheduleForFailure(newJob, failureToReschedule);
1021 }
1022 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001023 }
1024
1025 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001026 * Called after a periodic has executed so we can reschedule it. We take the last execution
1027 * time of the job to be the time of completion (i.e. the time at which this function is
1028 * called).
Christopher Tate7060b042014-06-09 19:50:00 -07001029 * This could be inaccurate b/c the job can run for as long as
1030 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1031 * to underscheduling at least, rather than if we had taken the last execution time to be the
1032 * start of the execution.
1033 * @return A new job representing the execution criteria for this instantiation of the
1034 * recurring job.
1035 */
1036 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
1037 final long elapsedNow = SystemClock.elapsedRealtime();
1038 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001039 long runEarly = 0L;
1040
1041 // If this periodic was rescheduled it won't have a deadline.
1042 if (periodicToReschedule.hasDeadlineConstraint()) {
1043 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1044 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001045 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001046 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001047 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1048 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001049
1050 if (DEBUG) {
1051 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1052 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1053 }
1054 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
1055 newLatestRuntimeElapsed, 0 /* backoffAttempt */);
1056 }
1057
1058 // JobCompletedListener implementations.
1059
1060 /**
1061 * A job just finished executing. We fetch the
1062 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1063 * whether we want to reschedule we readd it to the controllers.
1064 * @param jobStatus Completed job.
1065 * @param needsReschedule Whether the implementing class should reschedule this job.
1066 */
1067 @Override
1068 public void onJobCompleted(JobStatus jobStatus, boolean needsReschedule) {
1069 if (DEBUG) {
1070 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1071 }
Shreyas Basarge73f10252016-02-11 17:06:13 +00001072 // Do not write back immediately if this is a periodic job. The job may get lost if system
1073 // shuts down before it is added back.
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001074 if (!stopTrackingJob(jobStatus, null, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001075 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001076 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001077 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001078 // We still want to check for jobs to execute, because this job may have
1079 // scheduled a new job under the same job id, and now we can run it.
1080 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001081 return;
1082 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001083 // Note: there is a small window of time in here where, when rescheduling a job,
1084 // we will stop monitoring its content providers. This should be fixed by stopping
1085 // the old job after scheduling the new one, but since we have no lock held here
1086 // that may cause ordering problems if the app removes jobStatus while in here.
Christopher Tate7060b042014-06-09 19:50:00 -07001087 if (needsReschedule) {
1088 JobStatus rescheduled = getRescheduleJobForFailure(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001089 try {
1090 rescheduled.prepare(ActivityManager.getService());
1091 } catch (SecurityException e) {
1092 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduled);
1093 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001094 startTrackingJob(rescheduled, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001095 } else if (jobStatus.getJob().isPeriodic()) {
1096 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001097 try {
1098 rescheduledPeriodic.prepare(ActivityManager.getService());
1099 } catch (SecurityException e) {
1100 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1101 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001102 startTrackingJob(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001103 }
Dianne Hackborna47223f2017-03-30 13:49:13 -07001104 jobStatus.unprepare(ActivityManager.getService());
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001105 reportActive();
1106 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001107 }
1108
1109 // StateChangedListener implementations.
1110
1111 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001112 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1113 * some controller's state has changed, so as to run through the list of jobs and start/stop
1114 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001115 */
1116 @Override
1117 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001118 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001119 }
1120
1121 @Override
1122 public void onRunJobNow(JobStatus jobStatus) {
1123 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1124 }
1125
Christopher Tate7060b042014-06-09 19:50:00 -07001126 private class JobHandler extends Handler {
1127
1128 public JobHandler(Looper looper) {
1129 super(looper);
1130 }
1131
1132 @Override
1133 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001134 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001135 if (!mReadyToRock) {
1136 return;
1137 }
1138 }
Christopher Tate7060b042014-06-09 19:50:00 -07001139 switch (message.what) {
1140 case MSG_JOB_EXPIRED:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001141 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -07001142 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001143 // runNow can be null, which is a controller's way of indicating that its
1144 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001145 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001146 mJobPackageTracker.notePending(runNow);
Christopher Tate7060b042014-06-09 19:50:00 -07001147 mPendingJobs.add(runNow);
1148 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001149 queueReadyJobsForExecutionLockedH();
Christopher Tate7060b042014-06-09 19:50:00 -07001150 }
Christopher Tate7060b042014-06-09 19:50:00 -07001151 break;
1152 case MSG_CHECK_JOB:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001153 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001154 if (mReportedActive) {
1155 // if jobs are currently being run, queue all ready jobs for execution.
1156 queueReadyJobsForExecutionLockedH();
1157 } else {
1158 // Check the list of jobs and run some of them if we feel inclined.
1159 maybeQueueReadyJobsForExecutionLockedH();
1160 }
1161 }
1162 break;
1163 case MSG_CHECK_JOB_GREEDY:
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001164 synchronized (mLock) {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001165 queueReadyJobsForExecutionLockedH();
Matthew Williams48a30db2014-09-23 13:39:36 -07001166 }
Christopher Tate7060b042014-06-09 19:50:00 -07001167 break;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001168 case MSG_STOP_JOB:
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001169 cancelJobImpl((JobStatus)message.obj, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001170 break;
Christopher Tate7060b042014-06-09 19:50:00 -07001171 }
1172 maybeRunPendingJobsH();
1173 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1174 removeMessages(MSG_CHECK_JOB);
1175 }
1176
1177 /**
1178 * Run through list of jobs and execute all possible - at least one is expired so we do
1179 * as many as we can.
1180 */
Matthew Williams48a30db2014-09-23 13:39:36 -07001181 private void queueReadyJobsForExecutionLockedH() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001182 if (DEBUG) {
1183 Slog.d(TAG, "queuing all ready jobs for execution:");
1184 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001185 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001186 mPendingJobs.clear();
1187 mJobs.forEachJob(mReadyQueueFunctor);
1188 mReadyQueueFunctor.postProcess();
1189
Matthew Williams48a30db2014-09-23 13:39:36 -07001190 if (DEBUG) {
1191 final int queuedJobs = mPendingJobs.size();
1192 if (queuedJobs == 0) {
1193 Slog.d(TAG, "No jobs pending.");
1194 } else {
1195 Slog.d(TAG, queuedJobs + " jobs queued.");
Matthew Williams75fc5252014-09-02 16:17:53 -07001196 }
Christopher Tate7060b042014-06-09 19:50:00 -07001197 }
1198 }
1199
Christopher Tate2f36fd62016-02-18 18:36:08 -08001200 class ReadyJobQueueFunctor implements JobStatusFunctor {
1201 ArrayList<JobStatus> newReadyJobs;
1202
1203 @Override
1204 public void process(JobStatus job) {
1205 if (isReadyToBeExecutedLocked(job)) {
1206 if (DEBUG) {
1207 Slog.d(TAG, " queued " + job.toShortString());
1208 }
1209 if (newReadyJobs == null) {
1210 newReadyJobs = new ArrayList<JobStatus>();
1211 }
1212 newReadyJobs.add(job);
1213 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
1214 stopJobOnServiceContextLocked(job,
1215 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
1216 }
1217 }
1218
1219 public void postProcess() {
1220 if (newReadyJobs != null) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001221 noteJobsPending(newReadyJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001222 mPendingJobs.addAll(newReadyJobs);
1223 }
1224 newReadyJobs = null;
1225 }
1226 }
1227 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1228
Christopher Tate7060b042014-06-09 19:50:00 -07001229 /**
1230 * The state of at least one job has changed. Here is where we could enforce various
1231 * policies on when we want to execute jobs.
1232 * Right now the policy is such:
1233 * If >1 of the ready jobs is idle mode we send all of them off
1234 * if more than 2 network connectivity jobs are ready we send them all off.
1235 * If more than 4 jobs total are ready we send them all off.
1236 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1237 */
Christopher Tate2f36fd62016-02-18 18:36:08 -08001238 class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1239 int chargingCount;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001240 int batteryNotLowCount;
Dianne Hackborn532ea262017-03-17 17:50:55 -07001241 int storageNotLowCount;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001242 int idleCount;
1243 int backoffCount;
1244 int connectivityCount;
1245 int contentCount;
1246 List<JobStatus> runnableJobs;
1247
1248 public MaybeReadyJobQueueFunctor() {
1249 reset();
1250 }
1251
1252 // Functor method invoked for each job via JobStore.forEachJob()
1253 @Override
1254 public void process(JobStatus job) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001255 if (isReadyToBeExecutedLocked(job)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001256 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001257 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1258 job.getJob().getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001259 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1260 + job.getJob().toString() + " -- package not allowed to start");
1261 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001262 return;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001263 }
1264 } catch (RemoteException e) {
1265 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001266 if (job.getNumFailures() > 0) {
1267 backoffCount++;
Christopher Tate7060b042014-06-09 19:50:00 -07001268 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001269 if (job.hasIdleConstraint()) {
1270 idleCount++;
1271 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001272 if (job.hasConnectivityConstraint() || job.hasUnmeteredConstraint()
1273 || job.hasNotRoamingConstraint()) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001274 connectivityCount++;
1275 }
1276 if (job.hasChargingConstraint()) {
1277 chargingCount++;
1278 }
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001279 if (job.hasBatteryNotLowConstraint()) {
1280 batteryNotLowCount++;
1281 }
Dianne Hackborn532ea262017-03-17 17:50:55 -07001282 if (job.hasStorageNotLowConstraint()) {
1283 storageNotLowCount++;
1284 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001285 if (job.hasContentTriggerConstraint()) {
1286 contentCount++;
1287 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001288 if (runnableJobs == null) {
1289 runnableJobs = new ArrayList<>();
1290 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001291 runnableJobs.add(job);
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001292 } else if (areJobConstraintsNotSatisfiedLocked(job)) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001293 stopJobOnServiceContextLocked(job,
1294 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
Christopher Tate7060b042014-06-09 19:50:00 -07001295 }
Matthew Williams48a30db2014-09-23 13:39:36 -07001296 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001297
1298 public void postProcess() {
1299 if (backoffCount > 0 ||
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001300 idleCount >= mConstants.MIN_IDLE_COUNT ||
1301 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1302 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001303 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
Dianne Hackborn532ea262017-03-17 17:50:55 -07001304 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001305 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1306 (runnableJobs != null
1307 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001308 if (DEBUG) {
1309 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
1310 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001311 noteJobsPending(runnableJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001312 mPendingJobs.addAll(runnableJobs);
1313 } else {
1314 if (DEBUG) {
1315 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
1316 }
Christopher Tate7060b042014-06-09 19:50:00 -07001317 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001318
1319 // Be ready for next time
1320 reset();
Matthew Williams48a30db2014-09-23 13:39:36 -07001321 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001322
1323 private void reset() {
1324 chargingCount = 0;
1325 idleCount = 0;
1326 backoffCount = 0;
1327 connectivityCount = 0;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001328 batteryNotLowCount = 0;
Dianne Hackborn532ea262017-03-17 17:50:55 -07001329 storageNotLowCount = 0;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001330 contentCount = 0;
1331 runnableJobs = null;
1332 }
1333 }
1334 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1335
1336 private void maybeQueueReadyJobsForExecutionLockedH() {
1337 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1338
Dianne Hackborn807de782016-04-07 17:54:41 -07001339 noteJobsNonpending(mPendingJobs);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001340 mPendingJobs.clear();
1341 mJobs.forEachJob(mMaybeQueueFunctor);
1342 mMaybeQueueFunctor.postProcess();
Christopher Tate7060b042014-06-09 19:50:00 -07001343 }
1344
1345 /**
1346 * Criteria for moving a job into the pending queue:
1347 * - It's ready.
1348 * - It's not pending.
1349 * - It's not already running on a JSC.
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001350 * - The user that requested the job is running.
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001351 * - The component is enabled and runnable.
Christopher Tate7060b042014-06-09 19:50:00 -07001352 */
1353 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Christopher Tateb1d64482017-03-15 12:01:22 -07001354 final boolean jobExists = mJobs.containsJob(job);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001355 final boolean jobReady = job.isReady();
1356 final boolean jobPending = mPendingJobs.contains(job);
1357 final boolean jobActive = isCurrentlyActiveLocked(job);
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001358
1359 final int userId = job.getUserId();
1360 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
Christopher Tateb1d64482017-03-15 12:01:22 -07001361
1362 if (DEBUG) {
1363 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1364 + " exists=" + jobExists
1365 + " ready=" + jobReady + " pending=" + jobPending
1366 + " active=" + jobActive + " userStarted=" + userStarted);
1367 }
1368
1369 // Short circuit: don't do the expensive PM check unless we really think
1370 // we might need to run this job now.
1371 if (!jobExists || !userStarted || !jobReady || jobPending || jobActive) {
1372 return false;
1373 }
1374
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001375 final boolean componentPresent;
1376 try {
1377 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1378 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1379 userId) != null);
1380 } catch (RemoteException e) {
1381 throw e.rethrowAsRuntimeException();
1382 }
1383
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001384 if (DEBUG) {
1385 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001386 + " componentPresent=" + componentPresent);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001387 }
Christopher Tateb1d64482017-03-15 12:01:22 -07001388
1389 // Everything else checked out so far, so this is the final yes/no check
1390 return componentPresent;
Christopher Tate7060b042014-06-09 19:50:00 -07001391 }
1392
1393 /**
1394 * Criteria for cancelling an active job:
1395 * - It's not ready
1396 * - It's running on a JSC.
1397 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001398 private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
Christopher Tate7060b042014-06-09 19:50:00 -07001399 return !job.isReady() && isCurrentlyActiveLocked(job);
1400 }
1401
1402 /**
1403 * Reconcile jobs in the pending queue against available execution contexts.
1404 * A controller can force a job into the pending queue even if it's already running, but
1405 * here is where we decide whether to actually execute it.
1406 */
1407 private void maybeRunPendingJobsH() {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001408 synchronized (mLock) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001409 if (DEBUG) {
1410 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1411 }
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001412 assignJobsToContextsLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001413 reportActive();
Christopher Tate7060b042014-06-09 19:50:00 -07001414 }
1415 }
1416 }
1417
Dianne Hackborn807de782016-04-07 17:54:41 -07001418 private int adjustJobPriority(int curPriority, JobStatus job) {
1419 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1420 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001421 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001422 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001423 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001424 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1425 }
1426 }
1427 return curPriority;
1428 }
1429
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001430 private int evaluateJobPriorityLocked(JobStatus job) {
1431 int priority = job.getPriority();
1432 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001433 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001434 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001435 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1436 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001437 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001438 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001439 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001440 }
1441
Christopher Tate7060b042014-06-09 19:50:00 -07001442 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001443 * Takes jobs from pending queue and runs them on available contexts.
1444 * If no contexts are available, preempts lower priority jobs to
1445 * run higher priority ones.
1446 * Lock on mJobs before calling this function.
1447 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001448 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001449 if (DEBUG) {
1450 Slog.d(TAG, printPendingQueue());
1451 }
1452
Dianne Hackborn970510b2016-02-24 16:56:42 -08001453 int memLevel;
1454 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001455 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001456 } catch (RemoteException e) {
1457 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1458 }
1459 switch (memLevel) {
1460 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001461 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001462 break;
1463 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001464 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001465 break;
1466 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001467 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001468 break;
1469 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001470 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001471 break;
1472 }
1473
1474 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1475 boolean[] act = mTmpAssignAct;
1476 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1477 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001478 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001479 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1480 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001481 final JobStatus status = js.getRunningJob();
1482 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001483 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001484 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1485 numForeground++;
1486 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001487 }
1488 act[i] = false;
1489 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001490 }
1491 if (DEBUG) {
1492 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1493 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001494 for (int i=0; i<mPendingJobs.size(); i++) {
1495 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001496
1497 // If job is already running, go to next job.
1498 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1499 if (jobRunningContext != -1) {
1500 continue;
1501 }
1502
Dianne Hackborn970510b2016-02-24 16:56:42 -08001503 final int priority = evaluateJobPriorityLocked(nextPending);
1504 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001505
Shreyas Basarge5db09082016-01-07 13:38:29 +00001506 // Find a context for nextPending. The context should be available OR
1507 // it should have lowest priority among all running jobs
1508 // (sharing the same Uid as nextPending)
1509 int minPriority = Integer.MAX_VALUE;
1510 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001511 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1512 JobStatus job = contextIdToJobMap[j];
1513 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001514 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001515 if ((numActive < mMaxActiveJobs ||
1516 (priority >= JobInfo.PRIORITY_TOP_APP &&
1517 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001518 (preferredUid == nextPending.getUid() ||
1519 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1520 // This slot is free, and we haven't yet hit the limit on
1521 // concurrent jobs... we can just throw the job in to here.
1522 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001523 break;
1524 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001525 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001526 // the context has a preferred Uid or we have reached the limit on
1527 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001528 continue;
1529 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001530 if (job.getUid() != nextPending.getUid()) {
1531 continue;
1532 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001533 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001534 continue;
1535 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001536 if (minPriority > nextPending.lastEvaluatedPriority) {
1537 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001538 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001539 }
1540 }
1541 if (minPriorityContextId != -1) {
1542 contextIdToJobMap[minPriorityContextId] = nextPending;
1543 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001544 numActive++;
1545 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1546 numForeground++;
1547 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001548 }
1549 }
1550 if (DEBUG) {
1551 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1552 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001553 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001554 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001555 boolean preservePreferredUid = false;
1556 if (act[i]) {
1557 JobStatus js = mActiveServices.get(i).getRunningJob();
1558 if (js != null) {
1559 if (DEBUG) {
1560 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJob());
1561 }
1562 // preferredUid will be set to uid of currently running job.
1563 mActiveServices.get(i).preemptExecutingJob();
1564 preservePreferredUid = true;
1565 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001566 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001567 if (DEBUG) {
1568 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001569 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001570 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001571 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001572 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001573 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001574 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1575 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001576 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001577 if (mPendingJobs.remove(pendingJob)) {
1578 mJobPackageTracker.noteNonpending(pendingJob);
1579 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001580 }
1581 }
1582 if (!preservePreferredUid) {
1583 mActiveServices.get(i).clearPreferredUid();
1584 }
1585 }
1586 }
1587
1588 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1589 for (int i=0; i<map.length; i++) {
1590 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1591 return i;
1592 }
1593 }
1594 return -1;
1595 }
1596
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001597 final class LocalService implements JobSchedulerInternal {
1598
1599 /**
1600 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1601 * jobs are always considered pending.
1602 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001603 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001604 public List<JobInfo> getSystemScheduledPendingJobs() {
1605 synchronized (mLock) {
1606 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1607 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1608 @Override
1609 public void process(JobStatus job) {
1610 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1611 pendingJobs.add(job.getJob());
1612 }
1613 }
1614 });
1615 return pendingJobs;
1616 }
1617 }
1618 }
1619
Shreyas Basarge5db09082016-01-07 13:38:29 +00001620 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001621 * Binder stub trampoline implementation
1622 */
1623 final class JobSchedulerStub extends IJobScheduler.Stub {
1624 /** Cache determination of whether a given app can persist jobs
1625 * key is uid of the calling app; value is undetermined/true/false
1626 */
1627 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1628
1629 // Enforce that only the app itself (or shared uid participant) can schedule a
1630 // job that runs one of the app's services, as well as verifying that the
1631 // named service properly requires the BIND_JOB_SERVICE permission
1632 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001633 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001634 final ComponentName service = job.getService();
1635 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001636 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001637 PackageManager.MATCH_DIRECT_BOOT_AWARE
1638 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001639 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001640 if (si == null) {
1641 throw new IllegalArgumentException("No such service " + service);
1642 }
Christopher Tate7060b042014-06-09 19:50:00 -07001643 if (si.applicationInfo.uid != uid) {
1644 throw new IllegalArgumentException("uid " + uid +
1645 " cannot schedule job in " + service.getPackageName());
1646 }
1647 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1648 throw new IllegalArgumentException("Scheduled service " + service
1649 + " does not require android.permission.BIND_JOB_SERVICE permission");
1650 }
Christopher Tate5568f542014-06-18 13:53:31 -07001651 } catch (RemoteException e) {
1652 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001653 }
1654 }
1655
1656 private boolean canPersistJobs(int pid, int uid) {
1657 // If we get this far we're good to go; all we need to do now is check
1658 // whether the app is allowed to persist its scheduled work.
1659 final boolean canPersist;
1660 synchronized (mPersistCache) {
1661 Boolean cached = mPersistCache.get(uid);
1662 if (cached != null) {
1663 canPersist = cached.booleanValue();
1664 } else {
1665 // Persisting jobs is tantamount to running at boot, so we permit
1666 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1667 // permission
1668 int result = getContext().checkPermission(
1669 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1670 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1671 mPersistCache.put(uid, canPersist);
1672 }
1673 }
1674 return canPersist;
1675 }
1676
1677 // IJobScheduler implementation
1678 @Override
1679 public int schedule(JobInfo job) throws RemoteException {
1680 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001681 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001682 }
1683 final int pid = Binder.getCallingPid();
1684 final int uid = Binder.getCallingUid();
1685
1686 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001687 if (job.isPersisted()) {
1688 if (!canPersistJobs(pid, uid)) {
1689 throw new IllegalArgumentException("Error: requested job be persisted without"
1690 + " holding RECEIVE_BOOT_COMPLETED permission.");
1691 }
1692 }
Christopher Tate7060b042014-06-09 19:50:00 -07001693
Jeff Sharkey785f4942016-07-14 10:31:15 -06001694 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1695 getContext().enforceCallingOrSelfPermission(
1696 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1697 }
1698
Christopher Tate7060b042014-06-09 19:50:00 -07001699 long ident = Binder.clearCallingIdentity();
1700 try {
Matthew Williams900c67f2014-07-09 12:46:53 -07001701 return JobSchedulerService.this.schedule(job, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001702 } finally {
1703 Binder.restoreCallingIdentity(ident);
1704 }
1705 }
1706
1707 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001708 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001709 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001710 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001711 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001712 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1713 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001714 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001715
1716 if (packageName == null) {
1717 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001718 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001719
1720 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1721 android.Manifest.permission.UPDATE_DEVICE_STATS);
1722 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1723 throw new SecurityException("Caller uid " + callerUid
1724 + " not permitted to schedule jobs for other apps");
1725 }
1726
Jeff Sharkey4f100402016-05-03 17:44:23 -06001727 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1728 getContext().enforceCallingOrSelfPermission(
1729 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1730 }
1731
Shreyas Basarge968ac752016-01-11 23:09:26 +00001732 long ident = Binder.clearCallingIdentity();
1733 try {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001734 return JobSchedulerService.this.scheduleAsPackage(job, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001735 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001736 } finally {
1737 Binder.restoreCallingIdentity(ident);
1738 }
1739 }
1740
1741 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001742 public List<JobInfo> getAllPendingJobs() throws RemoteException {
1743 final int uid = Binder.getCallingUid();
1744
1745 long ident = Binder.clearCallingIdentity();
1746 try {
1747 return JobSchedulerService.this.getPendingJobs(uid);
1748 } finally {
1749 Binder.restoreCallingIdentity(ident);
1750 }
1751 }
1752
1753 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001754 public JobInfo getPendingJob(int jobId) throws RemoteException {
1755 final int uid = Binder.getCallingUid();
1756
1757 long ident = Binder.clearCallingIdentity();
1758 try {
1759 return JobSchedulerService.this.getPendingJob(uid, jobId);
1760 } finally {
1761 Binder.restoreCallingIdentity(ident);
1762 }
1763 }
1764
1765 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001766 public void cancelAll() throws RemoteException {
1767 final int uid = Binder.getCallingUid();
1768
1769 long ident = Binder.clearCallingIdentity();
1770 try {
Dianne Hackborne07641d2016-11-09 15:07:23 -08001771 JobSchedulerService.this.cancelJobsForUid(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07001772 } finally {
1773 Binder.restoreCallingIdentity(ident);
1774 }
1775 }
1776
1777 @Override
1778 public void cancel(int jobId) throws RemoteException {
1779 final int uid = Binder.getCallingUid();
1780
1781 long ident = Binder.clearCallingIdentity();
1782 try {
1783 JobSchedulerService.this.cancelJob(uid, jobId);
1784 } finally {
1785 Binder.restoreCallingIdentity(ident);
1786 }
1787 }
1788
1789 /**
1790 * "dumpsys" infrastructure
1791 */
1792 @Override
1793 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001794 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07001795
1796 long identityToken = Binder.clearCallingIdentity();
1797 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001798 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07001799 } finally {
1800 Binder.restoreCallingIdentity(identityToken);
1801 }
1802 }
Christopher Tate5d346052016-03-08 12:56:08 -08001803
1804 @Override
1805 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001806 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08001807 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07001808 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08001809 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001810 };
1811
Christopher Tate5d346052016-03-08 12:56:08 -08001812 // Shell command infrastructure: run the given job immediately
1813 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
1814 if (DEBUG) {
1815 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
1816 + " " + jobId + " f=" + force);
1817 }
1818
1819 try {
1820 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0, userId);
1821 if (uid < 0) {
1822 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
1823 }
1824
1825 synchronized (mLock) {
1826 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
1827 if (js == null) {
1828 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
1829 }
1830
1831 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
1832 if (!js.isConstraintsSatisfied()) {
1833 js.overrideState = 0;
1834 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
1835 }
1836
1837 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
1838 }
1839 } catch (RemoteException e) {
1840 // can't happen
1841 }
1842 return 0;
1843 }
1844
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001845 void setMonitorBattery(boolean enabled) {
1846 synchronized (mLock) {
1847 if (mBatteryController != null) {
1848 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
1849 }
1850 }
1851 }
1852
1853 int getBatterySeq() {
1854 synchronized (mLock) {
1855 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
1856 }
1857 }
1858
1859 boolean getBatteryCharging() {
1860 synchronized (mLock) {
1861 return mBatteryController != null
1862 ? mBatteryController.getTracker().isOnStablePower() : false;
1863 }
1864 }
1865
1866 boolean getBatteryNotLow() {
1867 synchronized (mLock) {
1868 return mBatteryController != null
1869 ? mBatteryController.getTracker().isBatteryNotLow() : false;
1870 }
1871 }
1872
Dianne Hackborn532ea262017-03-17 17:50:55 -07001873 int getStorageSeq() {
1874 synchronized (mLock) {
1875 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
1876 }
1877 }
1878
1879 boolean getStorageNotLow() {
1880 synchronized (mLock) {
1881 return mStorageController != null
1882 ? mStorageController.getTracker().isStorageNotLow() : false;
1883 }
1884 }
1885
Shreyas Basarge5db09082016-01-07 13:38:29 +00001886 private String printContextIdToJobMap(JobStatus[] map, String initial) {
1887 StringBuilder s = new StringBuilder(initial + ": ");
1888 for (int i=0; i<map.length; i++) {
1889 s.append("(")
1890 .append(map[i] == null? -1: map[i].getJobId())
1891 .append(map[i] == null? -1: map[i].getUid())
1892 .append(")" );
1893 }
1894 return s.toString();
1895 }
1896
1897 private String printPendingQueue() {
1898 StringBuilder s = new StringBuilder("Pending queue: ");
1899 Iterator<JobStatus> it = mPendingJobs.iterator();
1900 while (it.hasNext()) {
1901 JobStatus js = it.next();
1902 s.append("(")
1903 .append(js.getJob().getId())
1904 .append(", ")
1905 .append(js.getUid())
1906 .append(") ");
1907 }
1908 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001909 }
Christopher Tate7060b042014-06-09 19:50:00 -07001910
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001911 static void dumpHelp(PrintWriter pw) {
1912 pw.println("Job Scheduler (jobscheduler) dump options:");
1913 pw.println(" [-h] [package] ...");
1914 pw.println(" -h: print this help");
1915 pw.println(" [package] is an optional package name to limit the output to.");
1916 }
1917
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001918 void dumpInternal(final PrintWriter pw, String[] args) {
1919 int filterUid = -1;
1920 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001921 int opti = 0;
1922 while (opti < args.length) {
1923 String arg = args[opti];
1924 if ("-h".equals(arg)) {
1925 dumpHelp(pw);
1926 return;
1927 } else if ("-a".equals(arg)) {
1928 // Ignore, we always dump all.
1929 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
1930 pw.println("Unknown option: " + arg);
1931 return;
1932 } else {
1933 break;
1934 }
1935 opti++;
1936 }
1937 if (opti < args.length) {
1938 String pkg = args[opti];
1939 try {
1940 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001941 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001942 } catch (NameNotFoundException ignored) {
1943 pw.println("Invalid package: " + pkg);
1944 return;
1945 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001946 }
1947 }
1948
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07001949 final int filterUidFinal = UserHandle.getAppId(filterUid);
Christopher Tatef973a7b2014-08-29 12:54:08 -07001950 final long now = SystemClock.elapsedRealtime();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001951 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001952 mConstants.dump(pw);
1953 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001954 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001955 pw.print("Registered ");
1956 pw.print(mJobs.size());
1957 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07001958 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001959 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
1960 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001961 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001962 public int compare(JobStatus o1, JobStatus o2) {
1963 int uid1 = o1.getUid();
1964 int uid2 = o2.getUid();
1965 int id1 = o1.getJobId();
1966 int id2 = o2.getJobId();
1967 if (uid1 != uid2) {
1968 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001969 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001970 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001971 }
1972 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001973 for (JobStatus job : jobs) {
1974 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
1975 pw.println(job.toShortStringExceptUniqueId());
1976
1977 // Skip printing details if the caller requested a filter
1978 if (!job.shouldDump(filterUidFinal)) {
1979 continue;
1980 }
1981
1982 job.dump(pw, " ", true);
1983 pw.print(" Ready: ");
1984 pw.print(mHandler.isReadyToBeExecutedLocked(job));
1985 pw.print(" (job=");
1986 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001987 pw.print(" user=");
1988 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07001989 pw.print(" !pending=");
1990 pw.print(!mPendingJobs.contains(job));
1991 pw.print(" !active=");
1992 pw.print(!isCurrentlyActiveLocked(job));
1993 pw.print(" comp=");
1994 boolean componentPresent = false;
1995 try {
1996 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1997 job.getServiceComponent(),
1998 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1999 job.getUserId()) != null);
2000 } catch (RemoteException e) {
2001 }
2002 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002003 pw.println(")");
2004 }
Christopher Tate7060b042014-06-09 19:50:00 -07002005 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002006 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002007 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002008 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002009 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002010 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002011 }
2012 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002013 pw.println("Uid priority overrides:");
2014 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002015 int uid = mUidPriorityOverride.keyAt(i);
2016 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2017 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2018 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2019 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002020 }
2021 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002022 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002023 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002024 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2025 pw.println();
2026 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002027 pw.println("Pending queue:");
2028 for (int i=0; i<mPendingJobs.size(); i++) {
2029 JobStatus job = mPendingJobs.get(i);
2030 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2031 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002032 job.dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002033 int priority = evaluateJobPriorityLocked(job);
2034 if (priority != JobInfo.PRIORITY_DEFAULT) {
2035 pw.print(" Evaluated priority: "); pw.println(priority);
2036 }
2037 pw.print(" Tag: "); pw.println(job.getTag());
2038 }
Christopher Tate7060b042014-06-09 19:50:00 -07002039 pw.println();
2040 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002041 for (int i=0; i<mActiveServices.size(); i++) {
2042 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002043 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Shreyas Basarge5db09082016-01-07 13:38:29 +00002044 if (jsc.getRunningJob() == null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002045 pw.println("inactive");
Christopher Tate7060b042014-06-09 19:50:00 -07002046 continue;
2047 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002048 pw.println(jsc.getRunningJob().toShortString());
2049 pw.print(" Running for: ");
2050 TimeUtils.formatDuration(now - jsc.getExecutionStartTimeElapsed(), pw);
2051 pw.print(", timeout at: ");
2052 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - now, pw);
2053 pw.println();
2054 jsc.getRunningJob().dump(pw, " ", false);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002055 int priority = evaluateJobPriorityLocked(jsc.getRunningJob());
2056 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002057 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002058 }
Christopher Tate7060b042014-06-09 19:50:00 -07002059 }
2060 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002061 if (filterUid == -1) {
2062 pw.println();
2063 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2064 pw.print("mReportedActive="); pw.println(mReportedActive);
2065 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2066 }
Christopher Tate7060b042014-06-09 19:50:00 -07002067 }
2068 pw.println();
2069 }
2070}