blob: 12087b07444e60f571e54688c36c90eb81b5adb2 [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;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070040import android.app.job.JobWorkItem;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.content.BroadcastReceiver;
42import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070043import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070044import android.content.Context;
45import android.content.Intent;
46import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070047import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070048import android.content.pm.PackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070049import android.content.pm.ServiceInfo;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060050import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070051import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070052import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070053import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070054import android.os.Binder;
55import android.os.Handler;
56import android.os.Looper;
57import android.os.Message;
Shreyas Basargecbf5ae92016-03-08 16:13:06 +000058import android.os.Process;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070059import android.os.PowerManager;
Christopher Tate7060b042014-06-09 19:50:00 -070060import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080061import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070062import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070063import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070064import android.os.SystemClock;
65import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070066import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070067import android.provider.Settings;
68import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070069import android.util.Slog;
70import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080071import android.util.SparseIntArray;
72import android.util.TimeUtils;
Christopher Tate5d346052016-03-08 12:56:08 -080073
Dianne Hackbornfdb19562014-07-11 16:03:36 -070074import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070075import com.android.internal.app.procstats.ProcessStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070076import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060077import com.android.internal.util.DumpUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080078import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070079import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080080import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080081import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080082import com.android.server.job.controllers.AppIdleController;
Christopher Tate7060b042014-06-09 19:50:00 -070083import com.android.server.job.controllers.BatteryController;
84import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080085import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070086import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070087import com.android.server.job.controllers.IdleController;
88import com.android.server.job.controllers.JobStatus;
89import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070090import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070091import com.android.server.job.controllers.TimeController;
92
Jeff Sharkey822cbd12016-02-25 11:09:55 -070093import libcore.util.EmptyArray;
94
Christopher Tate7060b042014-06-09 19:50:00 -070095/**
96 * Responsible for taking jobs representing work to be performed by a client app, and determining
97 * based on the criteria specified when that job should be run against the client application's
98 * endpoint.
99 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
100 * about constraints, or the state of active jobs. It receives callbacks from the various
101 * controllers and completed jobs and operates accordingly.
102 *
103 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
104 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
105 * @hide
106 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800107public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700108 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800109 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700110 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800111
Dianne Hackborn970510b2016-02-24 16:56:42 -0800112 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700113 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800114 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800115 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800116 /** The maximum number of jobs that we allow an unprivileged app to schedule */
117 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700118
Christopher Tate2f36fd62016-02-18 18:36:08 -0800119
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800120 /** Global local for all job scheduler state. */
121 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700122 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700123 final JobStore mJobs;
Dianne Hackborn807de782016-04-07 17:54:41 -0700124 /** Tracking amount of time each package runs for. */
125 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700126
127 static final int MSG_JOB_EXPIRED = 0;
128 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700129 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000130 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700131
Christopher Tate7060b042014-06-09 19:50:00 -0700132 /**
133 * Track Services that have currently active or pending jobs. The index is provided by
134 * {@link JobStatus#getServiceToken()}
135 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700136 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700137 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700138 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800139 /** Need direct access to this for testing. */
140 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700141 /** Need direct access to this for testing. */
142 StorageController mStorageController;
Christopher Tate7060b042014-06-09 19:50:00 -0700143 /**
144 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
145 * when ready to execute them.
146 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700147 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700148
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700149 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700150
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700151 final JobHandler mHandler;
152 final JobSchedulerStub mJobSchedulerStub;
153
154 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700155 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800156 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700157
158 /**
159 * Set to true once we are allowed to run third party apps.
160 */
161 boolean mReadyToRock;
162
Christopher Tate7060b042014-06-09 19:50:00 -0700163 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800164 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800165 */
166 boolean mReportedActive;
167
168 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800169 * Current limit on the number of concurrent JobServiceContext entries we want to
170 * keep actively running a job.
171 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700172 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800173
174 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800175 * Which uids are currently in the foreground.
176 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800177 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
178
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700179 /**
180 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
181 */
182 final SparseIntArray mBackingUpUids = new SparseIntArray();
183
Dianne Hackborn970510b2016-02-24 16:56:42 -0800184 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
185
186 /**
187 * This array essentially stores the state of mActiveServices array.
188 * The ith index stores the job present on the ith JobServiceContext.
189 * We manipulate this array until we arrive at what jobs should be running on
190 * what JobServiceContext.
191 */
192 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
193 /**
194 * Indicates whether we need to act on this jobContext id
195 */
196 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
197 /**
198 * The uid whose jobs we would like to assign to a context.
199 */
200 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800201
202 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700203 * All times are in milliseconds. These constants are kept synchronized with the system
204 * global Settings. Any access to this class or its fields should be done while
205 * holding the JobSchedulerService.mLock lock.
206 */
207 private final class Constants extends ContentObserver {
208 // Key names stored in the settings value.
209 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
210 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800211 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700212 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700213 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
214 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
215 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
216 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
217 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
218 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
219 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
220 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
221 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
222 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700223 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
224 = "max_standard_reschedule_count";
225 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
226 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
227 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700228
229 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
230 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800231 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700232 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700233 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
234 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
235 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
236 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
237 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
238 private static final int DEFAULT_FG_JOB_COUNT = 4;
239 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
240 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700241 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700242 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700243 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
244 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
245 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
246 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700247
248 /**
249 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
250 * early.
251 */
252 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
253 /**
254 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
255 * things early.
256 */
257 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
258 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800259 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
260 * schedule things early.
261 */
262 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
263 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700264 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
265 * schedule things early.
266 */
267 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
268 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700269 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
270 * things early. 1 == Run connectivity jobs as soon as ready.
271 */
272 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
273 /**
274 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
275 * schedule things early.
276 */
277 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
278 /**
279 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
280 * running some work early. This (and thus the other min counts) is now set to 1, to
281 * prevent any batching at this level. Since we now do batching through doze, that is
282 * a much better mechanism.
283 */
284 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
285 /**
286 * This is the job execution factor that is considered to be heavy use of the system.
287 */
288 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
289 /**
290 * This is the job execution factor that is considered to be moderate use of the system.
291 */
292 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
293 /**
294 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
295 */
296 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
297 /**
298 * The maximum number of background jobs we allow when the system is in a normal
299 * memory state.
300 */
301 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
302 /**
303 * The maximum number of background jobs we allow when the system is in a moderate
304 * memory state.
305 */
306 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
307 /**
308 * The maximum number of background jobs we allow when the system is in a low
309 * memory state.
310 */
311 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
312 /**
313 * The maximum number of background jobs we allow when the system is in a critical
314 * memory state.
315 */
316 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700317 /**
318 * The maximum number of times we allow a job to have itself rescheduled before
319 * giving up on it, for standard jobs.
320 */
321 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
322 /**
323 * The maximum number of times we allow a job to have itself rescheduled before
324 * giving up on it, for jobs that are executing work.
325 */
326 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
327 /**
328 * The minimum backoff time to allow for linear backoff.
329 */
330 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
331 /**
332 * The minimum backoff time to allow for exponential backoff.
333 */
334 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700335
336 private ContentResolver mResolver;
337 private final KeyValueListParser mParser = new KeyValueListParser(',');
338
339 public Constants(Handler handler) {
340 super(handler);
341 }
342
343 public void start(ContentResolver resolver) {
344 mResolver = resolver;
345 mResolver.registerContentObserver(Settings.Global.getUriFor(
346 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
347 updateConstants();
348 }
349
350 @Override
351 public void onChange(boolean selfChange, Uri uri) {
352 updateConstants();
353 }
354
355 private void updateConstants() {
356 synchronized (mLock) {
357 try {
358 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000359 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700360 } catch (IllegalArgumentException e) {
361 // Failed to parse the settings string, log this and move on
362 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000363 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700364 }
365
366 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
367 DEFAULT_MIN_IDLE_COUNT);
368 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
369 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800370 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
371 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700372 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
373 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700374 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
375 DEFAULT_MIN_CONNECTIVITY_COUNT);
376 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
377 DEFAULT_MIN_CONTENT_COUNT);
378 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
379 DEFAULT_MIN_READY_JOBS_COUNT);
380 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
381 DEFAULT_HEAVY_USE_FACTOR);
382 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
383 DEFAULT_MODERATE_USE_FACTOR);
384 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
385 DEFAULT_FG_JOB_COUNT);
386 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
387 DEFAULT_BG_NORMAL_JOB_COUNT);
388 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
389 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
390 }
391 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
392 DEFAULT_BG_MODERATE_JOB_COUNT);
393 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
394 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
395 }
396 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
397 DEFAULT_BG_LOW_JOB_COUNT);
398 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
399 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
400 }
401 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
402 DEFAULT_BG_CRITICAL_JOB_COUNT);
403 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
404 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
405 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700406 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
407 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
408 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
409 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
410 MIN_LINEAR_BACKOFF_TIME = mParser.getLong(KEY_MIN_LINEAR_BACKOFF_TIME,
411 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
412 MIN_EXP_BACKOFF_TIME = mParser.getLong(KEY_MIN_EXP_BACKOFF_TIME,
413 DEFAULT_MIN_EXP_BACKOFF_TIME);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700414 }
415 }
416
417 void dump(PrintWriter pw) {
418 pw.println(" Settings:");
419
420 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
421 pw.print(MIN_IDLE_COUNT); pw.println();
422
423 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
424 pw.print(MIN_CHARGING_COUNT); pw.println();
425
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800426 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
427 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
428
Dianne Hackborn532ea262017-03-17 17:50:55 -0700429 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
430 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
431
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700432 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
433 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
434
435 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
436 pw.print(MIN_CONTENT_COUNT); pw.println();
437
438 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
439 pw.print(MIN_READY_JOBS_COUNT); pw.println();
440
441 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
442 pw.print(HEAVY_USE_FACTOR); pw.println();
443
444 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
445 pw.print(MODERATE_USE_FACTOR); pw.println();
446
447 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
448 pw.print(FG_JOB_COUNT); pw.println();
449
450 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
451 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
452
453 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
454 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
455
456 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
457 pw.print(BG_LOW_JOB_COUNT); pw.println();
458
459 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
460 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700461
462 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
463 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
464
465 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
466 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
467
468 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
469 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
470
471 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
472 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700473 }
474 }
475
476 final Constants mConstants;
477
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700478 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
479 if (o1.enqueueTime < o2.enqueueTime) {
480 return -1;
481 }
482 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
483 };
484
485 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
486 int where = Collections.binarySearch(array, newItem, comparator);
487 if (where < 0) {
488 where = ~where;
489 }
490 array.add(where, newItem);
491 }
492
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700493 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700494 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
495 * still clean up. On reinstall the package will have a new uid.
496 */
497 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
498 @Override
499 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700500 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700501 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700502 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700503 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700504 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700505 // Purge the app's jobs if the whole package was just disabled. When this is
506 // the case the component name will be a bare package name.
507 final String pkgName = getPackageName(intent);
508 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
509 if (pkgName != null && pkgUid != -1) {
510 final String[] changedComponents = intent.getStringArrayExtra(
511 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
512 if (changedComponents != null) {
513 for (String component : changedComponents) {
514 if (component.equals(pkgName)) {
515 if (DEBUG) {
516 Slog.d(TAG, "Package state change: " + pkgName);
517 }
518 try {
519 final int userId = UserHandle.getUserId(pkgUid);
520 IPackageManager pm = AppGlobals.getPackageManager();
521 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
522 if (state == COMPONENT_ENABLED_STATE_DISABLED
523 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
524 if (DEBUG) {
525 Slog.d(TAG, "Removing jobs for package " + pkgName
526 + " in user " + userId);
527 }
Dianne Hackborn729a3282017-06-09 16:06:01 -0700528 cancelJobsForUid(pkgUid, "app package state changed");
Christopher Tateb5c07882016-05-26 17:11:09 -0700529 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700530 } catch (RemoteException|IllegalArgumentException e) {
531 /*
532 * IllegalArgumentException means that the package doesn't exist.
533 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
534 * behind outright uninstall, so by the time we try to act it's gone.
535 * We don't need to act on this PACKAGE_CHANGED when this happens;
536 * we'll get a PACKAGE_REMOVED later and clean up then.
537 *
538 * RemoteException can't actually happen; the package manager is
539 * running in this same process.
540 */
541 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700542 break;
543 }
544 }
545 }
546 } else {
547 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
548 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700549 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700550 // If this is an outright uninstall rather than the first half of an
551 // app update sequence, cancel the jobs associated with the app.
552 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
553 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
554 if (DEBUG) {
555 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
556 }
Dianne Hackborn729a3282017-06-09 16:06:01 -0700557 cancelJobsForUid(uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700558 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700559 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700560 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
561 if (DEBUG) {
562 Slog.d(TAG, "Removing jobs for user: " + userId);
563 }
564 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700565 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
566 // Has this package scheduled any jobs, such that we will take action
567 // if it were to be force-stopped?
568 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
569 final String pkgName = intent.getData().getSchemeSpecificPart();
570 if (pkgUid != -1) {
571 List<JobStatus> jobsForUid;
572 synchronized (mLock) {
573 jobsForUid = mJobs.getJobsByUid(pkgUid);
574 }
575 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
576 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
577 if (DEBUG) {
578 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
579 + pkgUid + " has jobs");
580 }
581 setResultCode(Activity.RESULT_OK);
582 break;
583 }
584 }
585 }
586 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
587 // possible force-stop
588 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
589 final String pkgName = intent.getData().getSchemeSpecificPart();
590 if (pkgUid != -1) {
591 if (DEBUG) {
592 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
593 }
594 cancelJobsForPackageAndUid(pkgName, pkgUid);
595 }
Christopher Tate7060b042014-06-09 19:50:00 -0700596 }
597 }
598 };
599
Christopher Tateb5c07882016-05-26 17:11:09 -0700600 private String getPackageName(Intent intent) {
601 Uri uri = intent.getData();
602 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
603 return pkg;
604 }
605
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700606 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700607 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800608 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700609 }
610
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700611 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800612 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800613 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700614 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800615 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700616 }
617
618 @Override public void onUidActive(int uid) throws RemoteException {
619 }
620
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700621 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800622 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700623 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800624 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700625 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700626
627 @Override public void onUidCachedChanged(int uid, boolean cached) {
628 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700629 };
630
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800631 public Object getLock() {
632 return mLock;
633 }
634
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700635 public JobStore getJobStore() {
636 return mJobs;
637 }
638
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700639 @Override
640 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700641 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
642 // Let's kick any outstanding jobs for this user.
643 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
644 }
645
646 @Override
647 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700648 // Let's kick any outstanding jobs for this user.
649 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
650 }
651
652 @Override
653 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700654 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700655 }
656
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700657 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
658 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700659 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800660 if (ActivityManager.getService().isAppStartModeDisabled(uId,
661 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700662 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
663 + " -- package not allowed to start");
664 return JobScheduler.RESULT_FAILURE;
665 }
666 } catch (RemoteException e) {
667 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800668 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700669 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
670
671 if (work != null && toCancel != null) {
672 // Fast path: we are adding work to an existing job, and the JobInfo is not
673 // changing. We can just directly enqueue this work in to the job.
674 if (toCancel.getJob().equals(job)) {
Dianne Hackborn342e6032017-04-13 18:04:31 -0700675 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700676 return JobScheduler.RESULT_SUCCESS;
677 }
678 }
679
680 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
681 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800682 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800683 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800684 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
685 Slog.w(TAG, "Too many jobs for uid " + uId);
686 throw new IllegalStateException("Apps may not schedule more than "
687 + MAX_JOBS_PER_APP + " distinct jobs");
688 }
689 }
690
Dianne Hackborna47223f2017-03-30 13:49:13 -0700691 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700692 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700693
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700694 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700695 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700696 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700697 if (work != null) {
698 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700699 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700700 }
701 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700702
703 // If the job is immediately ready to run, then we can just immediately
704 // put it in the pending list and try to schedule it. This is especially
705 // important for jobs with a 0 deadline constraint, since they will happen a fair
706 // amount, we want to handle them as quickly as possible, and semantically we want to
707 // make sure we have started holding the wake lock for the job before returning to
708 // the caller.
709 // If the job is not yet ready to run, there is nothing more to do -- we are
710 // now just waiting for one of its controllers to change state and schedule
711 // the job appropriately.
712 if (isReadyToBeExecutedLocked(jobStatus)) {
713 // This is a new job, we can just immediately put it on the pending
714 // list and try to run it.
715 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700716 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700717 maybeRunPendingJobsLocked();
718 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800719 }
Christopher Tate7060b042014-06-09 19:50:00 -0700720 return JobScheduler.RESULT_SUCCESS;
721 }
722
723 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800724 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800725 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
726 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
727 for (int i = jobs.size() - 1; i >= 0; i--) {
728 JobStatus job = jobs.get(i);
729 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700730 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800731 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700732 }
Christopher Tate7060b042014-06-09 19:50:00 -0700733 }
734
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600735 public JobInfo getPendingJob(int uid, int jobId) {
736 synchronized (mLock) {
737 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
738 for (int i = jobs.size() - 1; i >= 0; i--) {
739 JobStatus job = jobs.get(i);
740 if (job.getJobId() == jobId) {
741 return job.getJob();
742 }
743 }
744 return null;
745 }
746 }
747
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700748 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800749 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700750 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
751 for (int i=0; i<jobsForUser.size(); i++) {
752 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700753 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700754 }
Christopher Tate7060b042014-06-09 19:50:00 -0700755 }
756 }
757
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700758 private void cancelJobsForNonExistentUsers() {
759 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
760 synchronized (mLock) {
761 mJobs.removeJobsOfNonUsers(umi.getUserIds());
762 }
763 }
764
Christopher Tateee7805b2016-07-15 16:56:56 -0700765 void cancelJobsForPackageAndUid(String pkgName, int uid) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700766 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700767 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
768 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
769 final JobStatus job = jobsForUid.get(i);
770 if (job.getSourcePackageName().equals(pkgName)) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700771 cancelJobImplLocked(job, null, "app force stopped");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700772 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700773 }
774 }
775 }
776
Christopher Tate7060b042014-06-09 19:50:00 -0700777 /**
778 * Entry point from client to cancel all jobs originating from their uid.
779 * This will remove the job from the master list, and cancel the job if it was staged for
780 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700781 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800782 *
Christopher Tate7060b042014-06-09 19:50:00 -0700783 */
Dianne Hackborn729a3282017-06-09 16:06:01 -0700784 public void cancelJobsForUid(int uid, String reason) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800785 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700786 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
787 for (int i=0; i<jobsForUid.size(); i++) {
788 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700789 cancelJobImplLocked(toRemove, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700790 }
Christopher Tate7060b042014-06-09 19:50:00 -0700791 }
792 }
793
794 /**
795 * Entry point from client to cancel the job corresponding to the jobId provided.
796 * This will remove the job from the master list, and cancel the job if it was staged for
797 * execution or being executed.
798 * @param uid Uid of the calling client.
799 * @param jobId Id of the job, provided at schedule-time.
800 */
801 public void cancelJob(int uid, int jobId) {
802 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800803 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700804 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700805 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700806 cancelJobImplLocked(toCancel, null, "cancel() called by app");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700807 }
Christopher Tate7060b042014-06-09 19:50:00 -0700808 }
809 }
810
Dianne Hackborn729a3282017-06-09 16:06:01 -0700811 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700812 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
813 cancelled.unprepareLocked(ActivityManager.getService());
814 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
815 // Remove from pending queue.
816 if (mPendingJobs.remove(cancelled)) {
817 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700818 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700819 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700820 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700821 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700822 }
823
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800824 void updateUidState(int uid, int procState) {
825 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800826 if (procState == ActivityManager.PROCESS_STATE_TOP) {
827 // Only use this if we are exactly the top app. All others can live
828 // with just the foreground priority. This means that persistent processes
829 // can never be the top app priority... that is fine.
830 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
831 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
832 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800833 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800834 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800835 }
836 }
837 }
838
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700839 @Override
840 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800841 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700842 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600843 // When becoming idle, make sure no jobs are actively running,
844 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700845 for (int i=0; i<mActiveServices.size(); i++) {
846 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700847 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600848 if (executing != null
849 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700850 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
851 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700852 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700853 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700854 } else {
855 // When coming out of idle, allow thing to start back up.
856 if (mReadyToRock) {
857 if (mLocalDeviceIdleController != null) {
858 if (!mReportedActive) {
859 mReportedActive = true;
860 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700861 }
862 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700863 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700864 }
865 }
866 }
867 }
868
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700869 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000870 // active is true if pending queue contains jobs OR some job is running.
871 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800872 if (mPendingJobs.size() <= 0) {
873 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700874 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700875 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700876 if (job != null
877 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
878 && !job.dozeWhitelisted) {
879 // We will report active if we have a job running and it is not an exception
880 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800881 active = true;
882 break;
883 }
884 }
885 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000886
887 if (mReportedActive != active) {
888 mReportedActive = active;
889 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800890 mLocalDeviceIdleController.setJobsActive(active);
891 }
892 }
893 }
894
Christopher Tate7060b042014-06-09 19:50:00 -0700895 /**
896 * Initializes the system service.
897 * <p>
898 * Subclasses must define a single argument constructor that accepts the context
899 * and passes it to super.
900 * </p>
901 *
902 * @param context The system server context.
903 */
904 public JobSchedulerService(Context context) {
905 super(context);
Dianne Hackborn970e3f42016-06-01 10:55:13 -0700906 mHandler = new JobHandler(context.getMainLooper());
907 mConstants = new Constants(mHandler);
908 mJobSchedulerStub = new JobSchedulerStub();
909 mJobs = JobStore.initAndGet(this);
910
Christopher Tate7060b042014-06-09 19:50:00 -0700911 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700912 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700913 mControllers.add(ConnectivityController.get(this));
914 mControllers.add(TimeController.get(this));
915 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800916 mBatteryController = BatteryController.get(this);
917 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700918 mStorageController = StorageController.get(this);
919 mControllers.add(mStorageController);
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800920 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800921 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700922 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate616541d2017-07-26 14:27:38 -0700923
924 // If the job store determined that it can't yet reschedule persisted jobs,
925 // we need to start watching the clock.
926 if (!mJobs.jobTimesInflatedValid()) {
927 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
928 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
929 }
Christopher Tate7060b042014-06-09 19:50:00 -0700930 }
931
Christopher Tate616541d2017-07-26 14:27:38 -0700932 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
933 @Override
934 public void onReceive(Context context, Intent intent) {
935 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
936 // When we reach clock sanity, recalculate the temporal windows
937 // of all affected jobs.
938 if (mJobs.clockNowValidToInflate(System.currentTimeMillis())) {
939 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
940
941 // We've done our job now, so stop watching the time.
942 context.unregisterReceiver(this);
943
944 // And kick off the work to update the affected jobs, using a secondary
945 // thread instead of chugging away here on the main looper thread.
946 FgThread.getHandler().post(mJobTimeUpdater);
947 }
948 }
949 }
950 };
951
952 private final Runnable mJobTimeUpdater = () -> {
953 final ArrayList<JobStatus> toRemove = new ArrayList<>();
954 final ArrayList<JobStatus> toAdd = new ArrayList<>();
955 synchronized (mLock) {
956 // Note: we intentionally both look up the existing affected jobs and replace them
957 // with recalculated ones inside the same lock lifetime.
958 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
959
960 // Now, at each position [i], we have both the existing JobStatus
961 // and the one that replaces it.
962 final int N = toAdd.size();
963 for (int i = 0; i < N; i++) {
964 final JobStatus oldJob = toRemove.get(i);
965 final JobStatus newJob = toAdd.get(i);
966 if (DEBUG) {
967 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
968 }
969 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
970 }
971 }
972 };
973
Christopher Tate7060b042014-06-09 19:50:00 -0700974 @Override
975 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000976 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -0700977 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
978 }
979
980 @Override
981 public void onBootPhase(int phase) {
982 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700983 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +0000984 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -0700985 final IntentFilter filter = new IntentFilter();
986 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
987 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -0700988 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
989 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -0700990 filter.addDataScheme("package");
991 getContext().registerReceiverAsUser(
992 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
993 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
994 getContext().registerReceiverAsUser(
995 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +0000996 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700997 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800998 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800999 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Dianne Hackborn5614bf52016-11-07 17:26:41 -08001000 | ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN,
1001 null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001002 } catch (RemoteException e) {
1003 // ignored; both services live in system_server
1004 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001005 // Remove any jobs that are not associated with any of the current users.
1006 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001007 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001008 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001009 // Let's go!
1010 mReadyToRock = true;
1011 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1012 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001013 mLocalDeviceIdleController
1014 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001015 // Create the "runners".
1016 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1017 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001018 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001019 getContext().getMainLooper()));
1020 }
1021 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001022 mJobs.forEachJob(new JobStatusFunctor() {
1023 @Override
1024 public void process(JobStatus job) {
1025 for (int controller = 0; controller < mControllers.size(); controller++) {
1026 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001027 sc.maybeStartTrackingJobLocked(job, null);
1028 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001029 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001030 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001031 // GO GO GO!
1032 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1033 }
Christopher Tate7060b042014-06-09 19:50:00 -07001034 }
1035 }
1036
1037 /**
1038 * Called when we have a job status object that we need to insert in our
1039 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1040 * about.
1041 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001042 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1043 if (!jobStatus.isPreparedLocked()) {
1044 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1045 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001046 jobStatus.enqueueTime = SystemClock.elapsedRealtime();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001047 final boolean update = mJobs.add(jobStatus);
1048 if (mReadyToRock) {
1049 for (int i = 0; i < mControllers.size(); i++) {
1050 StateController controller = mControllers.get(i);
1051 if (update) {
1052 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001053 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001054 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001055 }
Christopher Tate7060b042014-06-09 19:50:00 -07001056 }
1057 }
1058
1059 /**
1060 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1061 * object removed.
1062 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001063 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001064 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001065 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001066 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001067
1068 // Remove from store as well as controllers.
1069 final boolean removed = mJobs.remove(jobStatus, writeBack);
1070 if (removed && mReadyToRock) {
1071 for (int i=0; i<mControllers.size(); i++) {
1072 StateController controller = mControllers.get(i);
1073 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001074 }
1075 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001076 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001077 }
1078
Dianne Hackborn729a3282017-06-09 16:06:01 -07001079 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001080 for (int i=0; i<mActiveServices.size(); i++) {
1081 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001082 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001083 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001084 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001085 return true;
1086 }
1087 }
1088 return false;
1089 }
1090
1091 /**
1092 * @param job JobStatus we are querying against.
1093 * @return Whether or not the job represented by the status object is currently being run or
1094 * is pending.
1095 */
1096 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001097 for (int i=0; i<mActiveServices.size(); i++) {
1098 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001099 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001100 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1101 return true;
1102 }
1103 }
1104 return false;
1105 }
1106
Dianne Hackborn807de782016-04-07 17:54:41 -07001107 void noteJobsPending(List<JobStatus> jobs) {
1108 for (int i = jobs.size() - 1; i >= 0; i--) {
1109 JobStatus job = jobs.get(i);
1110 mJobPackageTracker.notePending(job);
1111 }
1112 }
1113
1114 void noteJobsNonpending(List<JobStatus> jobs) {
1115 for (int i = jobs.size() - 1; i >= 0; i--) {
1116 JobStatus job = jobs.get(i);
1117 mJobPackageTracker.noteNonpending(job);
1118 }
1119 }
1120
Christopher Tate7060b042014-06-09 19:50:00 -07001121 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001122 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1123 * specify an override deadline on a failed job (the failed job will run even though it's not
1124 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1125 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1126 *
Christopher Tate7060b042014-06-09 19:50:00 -07001127 * @param failureToReschedule Provided job status that we will reschedule.
1128 * @return A newly instantiated JobStatus with the same constraints as the last job except
1129 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001130 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001131 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001132 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001133 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001134 final long elapsedNowMillis = SystemClock.elapsedRealtime();
1135 final JobInfo job = failureToReschedule.getJob();
1136
1137 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001138 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1139 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001140
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001141 if (failureToReschedule.hasWorkLocked()) {
1142 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1143 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1144 + backoffAttempts + " > work limit "
1145 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1146 return null;
1147 }
1148 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1149 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1150 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1151 return null;
1152 }
1153
Christopher Tate7060b042014-06-09 19:50:00 -07001154 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001155 case JobInfo.BACKOFF_POLICY_LINEAR: {
1156 long backoff = initialBackoffMillis;
1157 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1158 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1159 }
1160 delayMillis = backoff * backoffAttempts;
1161 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001162 default:
1163 if (DEBUG) {
1164 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1165 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001166 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1167 long backoff = initialBackoffMillis;
1168 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1169 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1170 }
1171 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1172 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001173 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001174 delayMillis =
1175 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001176 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001177 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
1178 failureToReschedule.getLastSuccessfulRunTime(), System.currentTimeMillis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001179 for (int ic=0; ic<mControllers.size(); ic++) {
1180 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001181 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001182 }
1183 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001184 }
1185
1186 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001187 * Called after a periodic has executed so we can reschedule it. We take the last execution
1188 * time of the job to be the time of completion (i.e. the time at which this function is
1189 * called).
Christopher Tate7060b042014-06-09 19:50:00 -07001190 * This could be inaccurate b/c the job can run for as long as
1191 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1192 * to underscheduling at least, rather than if we had taken the last execution time to be the
1193 * start of the execution.
1194 * @return A new job representing the execution criteria for this instantiation of the
1195 * recurring job.
1196 */
1197 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
1198 final long elapsedNow = SystemClock.elapsedRealtime();
1199 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001200 long runEarly = 0L;
1201
1202 // If this periodic was rescheduled it won't have a deadline.
1203 if (periodicToReschedule.hasDeadlineConstraint()) {
1204 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1205 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001206 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001207 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001208 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1209 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001210
1211 if (DEBUG) {
1212 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1213 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1214 }
1215 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001216 newLatestRuntimeElapsed, 0 /* backoffAttempt */,
1217 System.currentTimeMillis() /* lastSuccessfulRunTime */,
1218 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001219 }
1220
1221 // JobCompletedListener implementations.
1222
1223 /**
1224 * A job just finished executing. We fetch the
1225 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1226 * whether we want to reschedule we readd it to the controllers.
1227 * @param jobStatus Completed job.
1228 * @param needsReschedule Whether the implementing class should reschedule this job.
1229 */
1230 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001231 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001232 if (DEBUG) {
1233 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1234 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001235
1236 // If the job wants to be rescheduled, we first need to make the next upcoming
1237 // job so we can transfer any appropriate state over from the previous job when
1238 // we stop it.
1239 final JobStatus rescheduledJob = needsReschedule
1240 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1241
Shreyas Basarge73f10252016-02-11 17:06:13 +00001242 // Do not write back immediately if this is a periodic job. The job may get lost if system
1243 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001244 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001245 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001246 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001247 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001248 // We still want to check for jobs to execute, because this job may have
1249 // scheduled a new job under the same job id, and now we can run it.
1250 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001251 return;
1252 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001253
1254 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001255 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001256 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001257 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001258 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001259 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001260 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001261 } else if (jobStatus.getJob().isPeriodic()) {
1262 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001263 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001264 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001265 } catch (SecurityException e) {
1266 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1267 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001268 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001269 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001270 jobStatus.unprepareLocked(ActivityManager.getService());
1271 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001272 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001273 }
1274
1275 // StateChangedListener implementations.
1276
1277 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001278 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1279 * some controller's state has changed, so as to run through the list of jobs and start/stop
1280 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001281 */
1282 @Override
1283 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001284 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001285 }
1286
1287 @Override
1288 public void onRunJobNow(JobStatus jobStatus) {
1289 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1290 }
1291
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001292 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001293
1294 public JobHandler(Looper looper) {
1295 super(looper);
1296 }
1297
1298 @Override
1299 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001300 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001301 if (!mReadyToRock) {
1302 return;
1303 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001304 switch (message.what) {
1305 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001306 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001307 // runNow can be null, which is a controller's way of indicating that its
1308 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001309 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001310 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001311 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001312 } else {
1313 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001314 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001315 } break;
1316 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001317 if (mReportedActive) {
1318 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001319 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001320 } else {
1321 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001322 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001323 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001324 break;
1325 case MSG_CHECK_JOB_GREEDY:
1326 queueReadyJobsForExecutionLocked();
1327 break;
1328 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001329 cancelJobImplLocked((JobStatus) message.obj, null,
1330 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001331 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001332 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001333 maybeRunPendingJobsLocked();
1334 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1335 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001336 }
1337 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001338 }
Christopher Tate7060b042014-06-09 19:50:00 -07001339
Dianne Hackborn6d068262017-05-16 13:14:37 -07001340 private void stopNonReadyActiveJobsLocked() {
1341 for (int i=0; i<mActiveServices.size(); i++) {
1342 JobServiceContext serviceContext = mActiveServices.get(i);
1343 final JobStatus running = serviceContext.getRunningJobLocked();
1344 if (running != null && !running.isReady()) {
1345 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001346 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1347 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001348 }
1349 }
1350 }
1351
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001352 /**
1353 * Run through list of jobs and execute all possible - at least one is expired so we do
1354 * as many as we can.
1355 */
1356 private void queueReadyJobsForExecutionLocked() {
1357 if (DEBUG) {
1358 Slog.d(TAG, "queuing all ready jobs for execution:");
1359 }
1360 noteJobsNonpending(mPendingJobs);
1361 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001362 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001363 mJobs.forEachJob(mReadyQueueFunctor);
1364 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001365
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001366 if (DEBUG) {
1367 final int queuedJobs = mPendingJobs.size();
1368 if (queuedJobs == 0) {
1369 Slog.d(TAG, "No jobs pending.");
1370 } else {
1371 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001372 }
1373 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001374 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001375
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001376 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1377 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001378
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001379 @Override
1380 public void process(JobStatus job) {
1381 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001382 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001383 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001384 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001385 if (newReadyJobs == null) {
1386 newReadyJobs = new ArrayList<JobStatus>();
1387 }
1388 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001389 }
1390 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001391
1392 public void postProcess() {
1393 if (newReadyJobs != null) {
1394 noteJobsPending(newReadyJobs);
1395 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001396 if (mPendingJobs.size() > 1) {
1397 mPendingJobs.sort(mEnqueueTimeComparator);
1398 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001399 }
1400 newReadyJobs = null;
1401 }
1402 }
1403 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1404
1405 /**
1406 * The state of at least one job has changed. Here is where we could enforce various
1407 * policies on when we want to execute jobs.
1408 * Right now the policy is such:
1409 * If >1 of the ready jobs is idle mode we send all of them off
1410 * if more than 2 network connectivity jobs are ready we send them all off.
1411 * If more than 4 jobs total are ready we send them all off.
1412 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1413 */
1414 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1415 int chargingCount;
1416 int batteryNotLowCount;
1417 int storageNotLowCount;
1418 int idleCount;
1419 int backoffCount;
1420 int connectivityCount;
1421 int contentCount;
1422 List<JobStatus> runnableJobs;
1423
1424 public MaybeReadyJobQueueFunctor() {
1425 reset();
1426 }
1427
1428 // Functor method invoked for each job via JobStore.forEachJob()
1429 @Override
1430 public void process(JobStatus job) {
1431 if (isReadyToBeExecutedLocked(job)) {
1432 try {
1433 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1434 job.getJob().getService().getPackageName())) {
1435 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1436 + job.getJob().toString() + " -- package not allowed to start");
1437 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1438 return;
1439 }
1440 } catch (RemoteException e) {
1441 }
1442 if (job.getNumFailures() > 0) {
1443 backoffCount++;
1444 }
1445 if (job.hasIdleConstraint()) {
1446 idleCount++;
1447 }
1448 if (job.hasConnectivityConstraint()) {
1449 connectivityCount++;
1450 }
1451 if (job.hasChargingConstraint()) {
1452 chargingCount++;
1453 }
1454 if (job.hasBatteryNotLowConstraint()) {
1455 batteryNotLowCount++;
1456 }
1457 if (job.hasStorageNotLowConstraint()) {
1458 storageNotLowCount++;
1459 }
1460 if (job.hasContentTriggerConstraint()) {
1461 contentCount++;
1462 }
1463 if (runnableJobs == null) {
1464 runnableJobs = new ArrayList<>();
1465 }
1466 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001467 }
1468 }
1469
1470 public void postProcess() {
1471 if (backoffCount > 0 ||
1472 idleCount >= mConstants.MIN_IDLE_COUNT ||
1473 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1474 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1475 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1476 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1477 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1478 (runnableJobs != null
1479 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1480 if (DEBUG) {
1481 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1482 }
1483 noteJobsPending(runnableJobs);
1484 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001485 if (mPendingJobs.size() > 1) {
1486 mPendingJobs.sort(mEnqueueTimeComparator);
1487 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001488 } else {
1489 if (DEBUG) {
1490 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1491 }
1492 }
1493
1494 // Be ready for next time
1495 reset();
1496 }
1497
1498 private void reset() {
1499 chargingCount = 0;
1500 idleCount = 0;
1501 backoffCount = 0;
1502 connectivityCount = 0;
1503 batteryNotLowCount = 0;
1504 storageNotLowCount = 0;
1505 contentCount = 0;
1506 runnableJobs = null;
1507 }
1508 }
1509 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1510
1511 private void maybeQueueReadyJobsForExecutionLocked() {
1512 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1513
1514 noteJobsNonpending(mPendingJobs);
1515 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001516 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001517 mJobs.forEachJob(mMaybeQueueFunctor);
1518 mMaybeQueueFunctor.postProcess();
1519 }
1520
1521 /**
1522 * Criteria for moving a job into the pending queue:
1523 * - It's ready.
1524 * - It's not pending.
1525 * - It's not already running on a JSC.
1526 * - The user that requested the job is running.
1527 * - The component is enabled and runnable.
1528 */
1529 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001530 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001531
1532 if (DEBUG) {
1533 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1534 + " ready=" + jobReady);
1535 }
1536
1537 // This is a condition that is very likely to be false (most jobs that are
1538 // scheduled are sitting there, not ready yet) and very cheap to check (just
1539 // a few conditions on data in JobStatus).
1540 if (!jobReady) {
1541 return false;
1542 }
1543
1544 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001545
1546 final int userId = job.getUserId();
1547 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1548
1549 if (DEBUG) {
1550 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001551 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001552 }
1553
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001554 // These are also fairly cheap to check, though they typically will not
1555 // be conditions we fail.
1556 if (!jobExists || !userStarted) {
1557 return false;
1558 }
1559
1560 final boolean jobPending = mPendingJobs.contains(job);
1561 final boolean jobActive = isCurrentlyActiveLocked(job);
1562
1563 if (DEBUG) {
1564 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1565 + " pending=" + jobPending + " active=" + jobActive);
1566 }
1567
1568 // These can be a little more expensive (especially jobActive, since we need to
1569 // go through the array of all potentially active jobs), so we are doing them
1570 // later... but still before checking with the package manager!
1571 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001572 return false;
1573 }
1574
1575 final boolean componentPresent;
1576 try {
1577 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1578 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1579 userId) != null);
1580 } catch (RemoteException e) {
1581 throw e.rethrowAsRuntimeException();
1582 }
1583
1584 if (DEBUG) {
1585 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1586 + " componentPresent=" + componentPresent);
1587 }
1588
1589 // Everything else checked out so far, so this is the final yes/no check
1590 return componentPresent;
1591 }
1592
1593 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001594 * Reconcile jobs in the pending queue against available execution contexts.
1595 * A controller can force a job into the pending queue even if it's already running, but
1596 * here is where we decide whether to actually execute it.
1597 */
1598 private void maybeRunPendingJobsLocked() {
1599 if (DEBUG) {
1600 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1601 }
1602 assignJobsToContextsLocked();
1603 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001604 }
1605
Dianne Hackborn807de782016-04-07 17:54:41 -07001606 private int adjustJobPriority(int curPriority, JobStatus job) {
1607 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1608 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001609 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001610 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001611 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001612 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1613 }
1614 }
1615 return curPriority;
1616 }
1617
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001618 private int evaluateJobPriorityLocked(JobStatus job) {
1619 int priority = job.getPriority();
1620 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001621 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001622 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001623 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1624 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001625 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001626 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001627 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001628 }
1629
Christopher Tate7060b042014-06-09 19:50:00 -07001630 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001631 * Takes jobs from pending queue and runs them on available contexts.
1632 * If no contexts are available, preempts lower priority jobs to
1633 * run higher priority ones.
1634 * Lock on mJobs before calling this function.
1635 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001636 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001637 if (DEBUG) {
1638 Slog.d(TAG, printPendingQueue());
1639 }
1640
Dianne Hackborn970510b2016-02-24 16:56:42 -08001641 int memLevel;
1642 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001643 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001644 } catch (RemoteException e) {
1645 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1646 }
1647 switch (memLevel) {
1648 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001649 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001650 break;
1651 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001652 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001653 break;
1654 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001655 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001656 break;
1657 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001658 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001659 break;
1660 }
1661
1662 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1663 boolean[] act = mTmpAssignAct;
1664 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1665 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001666 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001667 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1668 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001669 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001670 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001671 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001672 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1673 numForeground++;
1674 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001675 }
1676 act[i] = false;
1677 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001678 }
1679 if (DEBUG) {
1680 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1681 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001682 for (int i=0; i<mPendingJobs.size(); i++) {
1683 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001684
1685 // If job is already running, go to next job.
1686 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1687 if (jobRunningContext != -1) {
1688 continue;
1689 }
1690
Dianne Hackborn970510b2016-02-24 16:56:42 -08001691 final int priority = evaluateJobPriorityLocked(nextPending);
1692 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001693
Shreyas Basarge5db09082016-01-07 13:38:29 +00001694 // Find a context for nextPending. The context should be available OR
1695 // it should have lowest priority among all running jobs
1696 // (sharing the same Uid as nextPending)
1697 int minPriority = Integer.MAX_VALUE;
1698 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001699 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1700 JobStatus job = contextIdToJobMap[j];
1701 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001702 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001703 if ((numActive < mMaxActiveJobs ||
1704 (priority >= JobInfo.PRIORITY_TOP_APP &&
1705 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001706 (preferredUid == nextPending.getUid() ||
1707 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1708 // This slot is free, and we haven't yet hit the limit on
1709 // concurrent jobs... we can just throw the job in to here.
1710 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001711 break;
1712 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001713 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001714 // the context has a preferred Uid or we have reached the limit on
1715 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001716 continue;
1717 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001718 if (job.getUid() != nextPending.getUid()) {
1719 continue;
1720 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001721 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001722 continue;
1723 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001724 if (minPriority > nextPending.lastEvaluatedPriority) {
1725 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001726 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001727 }
1728 }
1729 if (minPriorityContextId != -1) {
1730 contextIdToJobMap[minPriorityContextId] = nextPending;
1731 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001732 numActive++;
1733 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1734 numForeground++;
1735 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001736 }
1737 }
1738 if (DEBUG) {
1739 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1740 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001741 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001742 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001743 boolean preservePreferredUid = false;
1744 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001745 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001746 if (js != null) {
1747 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001748 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001749 }
1750 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001751 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001752 preservePreferredUid = true;
1753 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001754 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001755 if (DEBUG) {
1756 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001757 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001758 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001759 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001760 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001761 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001762 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1763 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001764 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001765 if (mPendingJobs.remove(pendingJob)) {
1766 mJobPackageTracker.noteNonpending(pendingJob);
1767 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001768 }
1769 }
1770 if (!preservePreferredUid) {
1771 mActiveServices.get(i).clearPreferredUid();
1772 }
1773 }
1774 }
1775
1776 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1777 for (int i=0; i<map.length; i++) {
1778 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1779 return i;
1780 }
1781 }
1782 return -1;
1783 }
1784
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001785 final class LocalService implements JobSchedulerInternal {
1786
1787 /**
1788 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1789 * jobs are always considered pending.
1790 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001791 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001792 public List<JobInfo> getSystemScheduledPendingJobs() {
1793 synchronized (mLock) {
1794 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1795 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1796 @Override
1797 public void process(JobStatus job) {
1798 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1799 pendingJobs.add(job.getJob());
1800 }
1801 }
1802 });
1803 return pendingJobs;
1804 }
1805 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001806
1807 @Override
1808 public void addBackingUpUid(int uid) {
1809 synchronized (mLock) {
1810 // No need to actually do anything here, since for a full backup the
1811 // activity manager will kill the process which will kill the job (and
1812 // cause it to restart, but now it can't run).
1813 mBackingUpUids.put(uid, uid);
1814 }
1815 }
1816
1817 @Override
1818 public void removeBackingUpUid(int uid) {
1819 synchronized (mLock) {
1820 mBackingUpUids.delete(uid);
1821 // If there are any jobs for this uid, we need to rebuild the pending list
1822 // in case they are now ready to run.
1823 if (mJobs.countJobsForUid(uid) > 0) {
1824 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1825 }
1826 }
1827 }
1828
1829 @Override
1830 public void clearAllBackingUpUids() {
1831 synchronized (mLock) {
1832 if (mBackingUpUids.size() > 0) {
1833 mBackingUpUids.clear();
1834 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1835 }
1836 }
1837 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07001838
1839 @Override
1840 public int countJobs() {
1841 synchronized (mLock) {
1842 return mJobs.size();
1843 }
1844 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001845 }
1846
Shreyas Basarge5db09082016-01-07 13:38:29 +00001847 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001848 * Binder stub trampoline implementation
1849 */
1850 final class JobSchedulerStub extends IJobScheduler.Stub {
1851 /** Cache determination of whether a given app can persist jobs
1852 * key is uid of the calling app; value is undetermined/true/false
1853 */
1854 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1855
1856 // Enforce that only the app itself (or shared uid participant) can schedule a
1857 // job that runs one of the app's services, as well as verifying that the
1858 // named service properly requires the BIND_JOB_SERVICE permission
1859 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001860 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001861 final ComponentName service = job.getService();
1862 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001863 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001864 PackageManager.MATCH_DIRECT_BOOT_AWARE
1865 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001866 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001867 if (si == null) {
1868 throw new IllegalArgumentException("No such service " + service);
1869 }
Christopher Tate7060b042014-06-09 19:50:00 -07001870 if (si.applicationInfo.uid != uid) {
1871 throw new IllegalArgumentException("uid " + uid +
1872 " cannot schedule job in " + service.getPackageName());
1873 }
1874 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1875 throw new IllegalArgumentException("Scheduled service " + service
1876 + " does not require android.permission.BIND_JOB_SERVICE permission");
1877 }
Christopher Tate5568f542014-06-18 13:53:31 -07001878 } catch (RemoteException e) {
1879 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001880 }
1881 }
1882
1883 private boolean canPersistJobs(int pid, int uid) {
1884 // If we get this far we're good to go; all we need to do now is check
1885 // whether the app is allowed to persist its scheduled work.
1886 final boolean canPersist;
1887 synchronized (mPersistCache) {
1888 Boolean cached = mPersistCache.get(uid);
1889 if (cached != null) {
1890 canPersist = cached.booleanValue();
1891 } else {
1892 // Persisting jobs is tantamount to running at boot, so we permit
1893 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1894 // permission
1895 int result = getContext().checkPermission(
1896 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1897 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1898 mPersistCache.put(uid, canPersist);
1899 }
1900 }
1901 return canPersist;
1902 }
1903
1904 // IJobScheduler implementation
1905 @Override
1906 public int schedule(JobInfo job) throws RemoteException {
1907 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001908 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001909 }
1910 final int pid = Binder.getCallingPid();
1911 final int uid = Binder.getCallingUid();
1912
1913 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001914 if (job.isPersisted()) {
1915 if (!canPersistJobs(pid, uid)) {
1916 throw new IllegalArgumentException("Error: requested job be persisted without"
1917 + " holding RECEIVE_BOOT_COMPLETED permission.");
1918 }
1919 }
Christopher Tate7060b042014-06-09 19:50:00 -07001920
Jeff Sharkey785f4942016-07-14 10:31:15 -06001921 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1922 getContext().enforceCallingOrSelfPermission(
1923 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1924 }
1925
Christopher Tate7060b042014-06-09 19:50:00 -07001926 long ident = Binder.clearCallingIdentity();
1927 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001928 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, -1, null);
1929 } finally {
1930 Binder.restoreCallingIdentity(ident);
1931 }
1932 }
1933
1934 // IJobScheduler implementation
1935 @Override
1936 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
1937 if (DEBUG) {
1938 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
1939 }
1940 final int pid = Binder.getCallingPid();
1941 final int uid = Binder.getCallingUid();
1942
1943 enforceValidJobRequest(uid, job);
1944 if (job.isPersisted()) {
1945 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
1946 }
1947 if (work == null) {
1948 throw new NullPointerException("work is null");
1949 }
1950
1951 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1952 getContext().enforceCallingOrSelfPermission(
1953 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1954 }
1955
1956 long ident = Binder.clearCallingIdentity();
1957 try {
1958 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, -1, null);
Christopher Tate7060b042014-06-09 19:50:00 -07001959 } finally {
1960 Binder.restoreCallingIdentity(ident);
1961 }
1962 }
1963
1964 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001965 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001966 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001967 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00001968 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001969 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
1970 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001971 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001972
1973 if (packageName == null) {
1974 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00001975 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001976
1977 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
1978 android.Manifest.permission.UPDATE_DEVICE_STATS);
1979 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
1980 throw new SecurityException("Caller uid " + callerUid
1981 + " not permitted to schedule jobs for other apps");
1982 }
1983
Jeff Sharkey4f100402016-05-03 17:44:23 -06001984 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1985 getContext().enforceCallingOrSelfPermission(
1986 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1987 }
1988
Shreyas Basarge968ac752016-01-11 23:09:26 +00001989 long ident = Binder.clearCallingIdentity();
1990 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001991 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001992 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00001993 } finally {
1994 Binder.restoreCallingIdentity(ident);
1995 }
1996 }
1997
1998 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07001999 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2000 final int uid = Binder.getCallingUid();
2001
2002 long ident = Binder.clearCallingIdentity();
2003 try {
2004 return JobSchedulerService.this.getPendingJobs(uid);
2005 } finally {
2006 Binder.restoreCallingIdentity(ident);
2007 }
2008 }
2009
2010 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002011 public JobInfo getPendingJob(int jobId) throws RemoteException {
2012 final int uid = Binder.getCallingUid();
2013
2014 long ident = Binder.clearCallingIdentity();
2015 try {
2016 return JobSchedulerService.this.getPendingJob(uid, jobId);
2017 } finally {
2018 Binder.restoreCallingIdentity(ident);
2019 }
2020 }
2021
2022 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002023 public void cancelAll() throws RemoteException {
2024 final int uid = Binder.getCallingUid();
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002025 switch (uid) {
2026 case Process.SYSTEM_UID:
2027 // This really shouldn't happen.
2028 Slog.wtf(TAG, "JobScheduler.cancelAll() called for uid=" + uid);
2029 return;
2030 }
Christopher Tate7060b042014-06-09 19:50:00 -07002031
2032 long ident = Binder.clearCallingIdentity();
2033 try {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002034 JobSchedulerService.this.cancelJobsForUid(uid, "cancelAll() called by app");
Christopher Tate7060b042014-06-09 19:50:00 -07002035 } finally {
2036 Binder.restoreCallingIdentity(ident);
2037 }
2038 }
2039
2040 @Override
2041 public void cancel(int jobId) throws RemoteException {
2042 final int uid = Binder.getCallingUid();
2043
2044 long ident = Binder.clearCallingIdentity();
2045 try {
2046 JobSchedulerService.this.cancelJob(uid, jobId);
2047 } finally {
2048 Binder.restoreCallingIdentity(ident);
2049 }
2050 }
2051
2052 /**
2053 * "dumpsys" infrastructure
2054 */
2055 @Override
2056 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002057 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002058
2059 long identityToken = Binder.clearCallingIdentity();
2060 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002061 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07002062 } finally {
2063 Binder.restoreCallingIdentity(identityToken);
2064 }
2065 }
Christopher Tate5d346052016-03-08 12:56:08 -08002066
2067 @Override
2068 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002069 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002070 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002071 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002072 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002073 };
2074
Christopher Tate5d346052016-03-08 12:56:08 -08002075 // Shell command infrastructure: run the given job immediately
2076 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2077 if (DEBUG) {
2078 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2079 + " " + jobId + " f=" + force);
2080 }
2081
2082 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002083 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2084 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002085 if (uid < 0) {
2086 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2087 }
2088
2089 synchronized (mLock) {
2090 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2091 if (js == null) {
2092 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2093 }
2094
2095 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2096 if (!js.isConstraintsSatisfied()) {
2097 js.overrideState = 0;
2098 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2099 }
2100
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002101 queueReadyJobsForExecutionLocked();
2102 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002103 }
2104 } catch (RemoteException e) {
2105 // can't happen
2106 }
2107 return 0;
2108 }
2109
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002110 // Shell command infrastructure: immediately timeout currently executing jobs
2111 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2112 boolean hasJobId, int jobId) {
2113 if (DEBUG) {
2114 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2115 }
2116
2117 synchronized (mLock) {
2118 boolean foundSome = false;
2119 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002120 final JobServiceContext jc = mActiveServices.get(i);
2121 final JobStatus js = jc.getRunningJobLocked();
2122 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId)) {
2123 foundSome = true;
2124 pw.print("Timing out: ");
2125 js.printUniqueId(pw);
2126 pw.print(" ");
2127 pw.println(js.getServiceComponent().flattenToShortString());
2128 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002129 }
2130 if (!foundSome) {
2131 pw.println("No matching executing jobs found.");
2132 }
2133 }
2134 return 0;
2135 }
2136
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002137 void setMonitorBattery(boolean enabled) {
2138 synchronized (mLock) {
2139 if (mBatteryController != null) {
2140 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2141 }
2142 }
2143 }
2144
2145 int getBatterySeq() {
2146 synchronized (mLock) {
2147 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2148 }
2149 }
2150
2151 boolean getBatteryCharging() {
2152 synchronized (mLock) {
2153 return mBatteryController != null
2154 ? mBatteryController.getTracker().isOnStablePower() : false;
2155 }
2156 }
2157
2158 boolean getBatteryNotLow() {
2159 synchronized (mLock) {
2160 return mBatteryController != null
2161 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2162 }
2163 }
2164
Dianne Hackborn532ea262017-03-17 17:50:55 -07002165 int getStorageSeq() {
2166 synchronized (mLock) {
2167 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2168 }
2169 }
2170
2171 boolean getStorageNotLow() {
2172 synchronized (mLock) {
2173 return mStorageController != null
2174 ? mStorageController.getTracker().isStorageNotLow() : false;
2175 }
2176 }
2177
Dianne Hackborn6d068262017-05-16 13:14:37 -07002178 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2179 try {
2180 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2181 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2182 if (uid < 0) {
2183 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2184 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2185 }
2186
2187 synchronized (mLock) {
2188 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2189 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2190 if (js == null) {
2191 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2192 pw.print("/jid"); pw.print(jobId); pw.println(")");
2193 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2194 }
2195
2196 boolean printed = false;
2197 if (mPendingJobs.contains(js)) {
2198 pw.print("pending");
2199 printed = true;
2200 }
2201 if (isCurrentlyActiveLocked(js)) {
2202 if (printed) {
2203 pw.print(" ");
2204 }
2205 printed = true;
2206 pw.println("active");
2207 }
2208 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2209 if (printed) {
2210 pw.print(" ");
2211 }
2212 printed = true;
2213 pw.println("user-stopped");
2214 }
2215 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2216 if (printed) {
2217 pw.print(" ");
2218 }
2219 printed = true;
2220 pw.println("backing-up");
2221 }
2222 boolean componentPresent = false;
2223 try {
2224 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2225 js.getServiceComponent(),
2226 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2227 js.getUserId()) != null);
2228 } catch (RemoteException e) {
2229 }
2230 if (!componentPresent) {
2231 if (printed) {
2232 pw.print(" ");
2233 }
2234 printed = true;
2235 pw.println("no-component");
2236 }
2237 if (js.isReady()) {
2238 if (printed) {
2239 pw.print(" ");
2240 }
2241 printed = true;
2242 pw.println("ready");
2243 }
2244 if (!printed) {
2245 pw.print("waiting");
2246 }
2247 pw.println();
2248 }
2249 } catch (RemoteException e) {
2250 // can't happen
2251 }
2252 return 0;
2253 }
2254
Shreyas Basarge5db09082016-01-07 13:38:29 +00002255 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2256 StringBuilder s = new StringBuilder(initial + ": ");
2257 for (int i=0; i<map.length; i++) {
2258 s.append("(")
2259 .append(map[i] == null? -1: map[i].getJobId())
2260 .append(map[i] == null? -1: map[i].getUid())
2261 .append(")" );
2262 }
2263 return s.toString();
2264 }
2265
2266 private String printPendingQueue() {
2267 StringBuilder s = new StringBuilder("Pending queue: ");
2268 Iterator<JobStatus> it = mPendingJobs.iterator();
2269 while (it.hasNext()) {
2270 JobStatus js = it.next();
2271 s.append("(")
2272 .append(js.getJob().getId())
2273 .append(", ")
2274 .append(js.getUid())
2275 .append(") ");
2276 }
2277 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002278 }
Christopher Tate7060b042014-06-09 19:50:00 -07002279
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002280 static void dumpHelp(PrintWriter pw) {
2281 pw.println("Job Scheduler (jobscheduler) dump options:");
2282 pw.println(" [-h] [package] ...");
2283 pw.println(" -h: print this help");
2284 pw.println(" [package] is an optional package name to limit the output to.");
2285 }
2286
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002287 void dumpInternal(final PrintWriter pw, String[] args) {
2288 int filterUid = -1;
2289 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002290 int opti = 0;
2291 while (opti < args.length) {
2292 String arg = args[opti];
2293 if ("-h".equals(arg)) {
2294 dumpHelp(pw);
2295 return;
2296 } else if ("-a".equals(arg)) {
2297 // Ignore, we always dump all.
2298 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2299 pw.println("Unknown option: " + arg);
2300 return;
2301 } else {
2302 break;
2303 }
2304 opti++;
2305 }
2306 if (opti < args.length) {
2307 String pkg = args[opti];
2308 try {
2309 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002310 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002311 } catch (NameNotFoundException ignored) {
2312 pw.println("Invalid package: " + pkg);
2313 return;
2314 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002315 }
2316 }
2317
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002318 final int filterUidFinal = UserHandle.getAppId(filterUid);
Dianne Hackborn6d068262017-05-16 13:14:37 -07002319 final long nowElapsed = SystemClock.elapsedRealtime();
2320 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002321 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002322 mConstants.dump(pw);
2323 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002324 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002325 pw.print("Registered ");
2326 pw.print(mJobs.size());
2327 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002328 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002329 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2330 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002331 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002332 public int compare(JobStatus o1, JobStatus o2) {
2333 int uid1 = o1.getUid();
2334 int uid2 = o2.getUid();
2335 int id1 = o1.getJobId();
2336 int id2 = o2.getJobId();
2337 if (uid1 != uid2) {
2338 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002339 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002340 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08002341 }
2342 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002343 for (JobStatus job : jobs) {
2344 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2345 pw.println(job.toShortStringExceptUniqueId());
2346
2347 // Skip printing details if the caller requested a filter
2348 if (!job.shouldDump(filterUidFinal)) {
2349 continue;
2350 }
2351
Dianne Hackborn6d068262017-05-16 13:14:37 -07002352 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002353 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002354 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002355 pw.print(" (job=");
2356 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002357 pw.print(" user=");
2358 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002359 pw.print(" !pending=");
2360 pw.print(!mPendingJobs.contains(job));
2361 pw.print(" !active=");
2362 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002363 pw.print(" !backingup=");
2364 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002365 pw.print(" comp=");
2366 boolean componentPresent = false;
2367 try {
2368 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2369 job.getServiceComponent(),
2370 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2371 job.getUserId()) != null);
2372 } catch (RemoteException e) {
2373 }
2374 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002375 pw.println(")");
2376 }
Christopher Tate7060b042014-06-09 19:50:00 -07002377 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002378 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002379 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002380 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002381 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002382 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002383 }
2384 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002385 pw.println("Uid priority overrides:");
2386 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002387 int uid = mUidPriorityOverride.keyAt(i);
2388 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2389 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2390 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2391 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002392 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002393 if (mBackingUpUids.size() > 0) {
2394 pw.println();
2395 pw.println("Backing up uids:");
2396 boolean first = true;
2397 for (int i = 0; i < mBackingUpUids.size(); i++) {
2398 int uid = mBackingUpUids.keyAt(i);
2399 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2400 if (first) {
2401 pw.print(" ");
2402 first = false;
2403 } else {
2404 pw.print(", ");
2405 }
2406 pw.print(UserHandle.formatUid(uid));
2407 }
2408 }
2409 pw.println();
2410 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002411 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002412 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002413 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002414 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2415 pw.println();
2416 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002417 pw.println("Pending queue:");
2418 for (int i=0; i<mPendingJobs.size(); i++) {
2419 JobStatus job = mPendingJobs.get(i);
2420 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2421 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002422 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002423 int priority = evaluateJobPriorityLocked(job);
2424 if (priority != JobInfo.PRIORITY_DEFAULT) {
2425 pw.print(" Evaluated priority: "); pw.println(priority);
2426 }
2427 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002428 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002429 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002430 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002431 }
Christopher Tate7060b042014-06-09 19:50:00 -07002432 pw.println();
2433 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002434 for (int i=0; i<mActiveServices.size(); i++) {
2435 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002436 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002437 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002438 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002439 if (jsc.mStoppedReason != null) {
2440 pw.print("inactive since ");
2441 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2442 pw.print(", stopped because: ");
2443 pw.println(jsc.mStoppedReason);
2444 } else {
2445 pw.println("inactive");
2446 }
Christopher Tate7060b042014-06-09 19:50:00 -07002447 continue;
2448 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002449 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002450 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002451 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002452 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002453 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002454 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002455 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002456 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002457 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002458 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002459 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002460 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002461 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002462 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002463 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2464 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002465 }
2466 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002467 if (filterUid == -1) {
2468 pw.println();
2469 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2470 pw.print("mReportedActive="); pw.println(mReportedActive);
2471 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2472 }
Christopher Tate7060b042014-06-09 19:50:00 -07002473 }
2474 pw.println();
2475 }
2476}