blob: b5497681a2de426176bf9d8574c90a2d02dfb0bd [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
Christopher Tateee7805b2016-07-15 16:56:56 -070022import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070023import android.app.ActivityManager;
Christopher Tate5568f542014-06-18 13:53:31 -070024import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070025import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070026import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070027import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000028import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.app.job.JobScheduler;
30import android.app.job.JobService;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070031import android.app.job.JobWorkItem;
Christopher Tate7060b042014-06-09 19:50:00 -070032import android.content.BroadcastReceiver;
33import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070034import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070035import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070038import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070039import android.content.pm.PackageManager;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060040import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070041import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070042import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070043import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070044import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070045import android.os.Binder;
46import android.os.Handler;
47import android.os.Looper;
48import android.os.Message;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070049import android.os.PowerManager;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070050import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070051import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080052import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070053import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070054import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070055import android.os.SystemClock;
56import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070057import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070058import android.provider.Settings;
59import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070060import android.util.Slog;
61import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080062import android.util.SparseIntArray;
63import android.util.TimeUtils;
Christopher Tate5d346052016-03-08 12:56:08 -080064
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070065import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070066import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070067import com.android.internal.app.procstats.ProcessStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070068import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060069import com.android.internal.util.DumpUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080070import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070071import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080072import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080073import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080074import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070075import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070076import com.android.server.job.controllers.BatteryController;
77import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080078import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070079import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070080import com.android.server.job.controllers.IdleController;
81import com.android.server.job.controllers.JobStatus;
82import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070083import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070084import com.android.server.job.controllers.TimeController;
85
Jeff Sharkey822cbd12016-02-25 11:09:55 -070086import libcore.util.EmptyArray;
87
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070088import java.io.FileDescriptor;
89import java.io.PrintWriter;
90import java.time.Clock;
91import java.util.ArrayList;
92import java.util.Arrays;
93import java.util.Collections;
94import java.util.Comparator;
95import java.util.Iterator;
96import java.util.List;
97
Christopher Tate7060b042014-06-09 19:50:00 -070098/**
99 * Responsible for taking jobs representing work to be performed by a client app, and determining
100 * based on the criteria specified when that job should be run against the client application's
101 * endpoint.
102 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
103 * about constraints, or the state of active jobs. It receives callbacks from the various
104 * controllers and completed jobs and operates accordingly.
105 *
106 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
107 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
108 * @hide
109 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800110public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700111 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800112 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700113 public static final boolean DEBUG = false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800114
Dianne Hackborn970510b2016-02-24 16:56:42 -0800115 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700116 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800117 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800118 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800119 /** The maximum number of jobs that we allow an unprivileged app to schedule */
120 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700121
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700122 @VisibleForTesting
123 public static Clock sSystemClock = Clock.systemUTC();
124 @VisibleForTesting
125 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
126 @VisibleForTesting
127 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800128
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800129 /** Global local for all job scheduler state. */
130 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700131 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700132 final JobStore mJobs;
Dianne Hackborn807de782016-04-07 17:54:41 -0700133 /** Tracking amount of time each package runs for. */
134 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700135
136 static final int MSG_JOB_EXPIRED = 0;
137 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700138 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000139 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700140
Christopher Tate7060b042014-06-09 19:50:00 -0700141 /**
142 * Track Services that have currently active or pending jobs. The index is provided by
143 * {@link JobStatus#getServiceToken()}
144 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700145 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700146 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700147 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800148 /** Need direct access to this for testing. */
149 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700150 /** Need direct access to this for testing. */
151 StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700152 /** Need directly for sending uid state changes */
153 private BackgroundJobsController mBackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700154 /**
155 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
156 * when ready to execute them.
157 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700158 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700159
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700160 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700161
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700162 final JobHandler mHandler;
163 final JobSchedulerStub mJobSchedulerStub;
164
165 IBatteryStats mBatteryStats;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700166 PowerManager mPowerManager;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800167 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700168
169 /**
170 * Set to true once we are allowed to run third party apps.
171 */
172 boolean mReadyToRock;
173
Christopher Tate7060b042014-06-09 19:50:00 -0700174 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800175 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800176 */
177 boolean mReportedActive;
178
179 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800180 * Current limit on the number of concurrent JobServiceContext entries we want to
181 * keep actively running a job.
182 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700183 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800184
185 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800186 * Which uids are currently in the foreground.
187 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800188 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
189
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700190 /**
191 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
192 */
193 final SparseIntArray mBackingUpUids = new SparseIntArray();
194
Dianne Hackborn970510b2016-02-24 16:56:42 -0800195 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
196
197 /**
198 * This array essentially stores the state of mActiveServices array.
199 * The ith index stores the job present on the ith JobServiceContext.
200 * We manipulate this array until we arrive at what jobs should be running on
201 * what JobServiceContext.
202 */
203 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
204 /**
205 * Indicates whether we need to act on this jobContext id
206 */
207 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
208 /**
209 * The uid whose jobs we would like to assign to a context.
210 */
211 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800212
213 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700214 * All times are in milliseconds. These constants are kept synchronized with the system
215 * global Settings. Any access to this class or its fields should be done while
216 * holding the JobSchedulerService.mLock lock.
217 */
218 private final class Constants extends ContentObserver {
219 // Key names stored in the settings value.
220 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
221 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800222 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700223 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700224 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
225 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
226 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
227 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
228 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
229 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
230 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
231 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
232 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
233 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700234 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
235 = "max_standard_reschedule_count";
236 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
237 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
238 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700239
240 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
241 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800242 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700243 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700244 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
245 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
246 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
247 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
248 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
249 private static final int DEFAULT_FG_JOB_COUNT = 4;
250 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
251 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700252 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700253 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700254 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
255 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
256 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
257 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700258
259 /**
260 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
261 * early.
262 */
263 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
264 /**
265 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
266 * things early.
267 */
268 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
269 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800270 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
271 * schedule things early.
272 */
273 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
274 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700275 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
276 * schedule things early.
277 */
278 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
279 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700280 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
281 * things early. 1 == Run connectivity jobs as soon as ready.
282 */
283 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
284 /**
285 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
286 * schedule things early.
287 */
288 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
289 /**
290 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
291 * running some work early. This (and thus the other min counts) is now set to 1, to
292 * prevent any batching at this level. Since we now do batching through doze, that is
293 * a much better mechanism.
294 */
295 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
296 /**
297 * This is the job execution factor that is considered to be heavy use of the system.
298 */
299 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
300 /**
301 * This is the job execution factor that is considered to be moderate use of the system.
302 */
303 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
304 /**
305 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
306 */
307 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
308 /**
309 * The maximum number of background jobs we allow when the system is in a normal
310 * memory state.
311 */
312 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
313 /**
314 * The maximum number of background jobs we allow when the system is in a moderate
315 * memory state.
316 */
317 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
318 /**
319 * The maximum number of background jobs we allow when the system is in a low
320 * memory state.
321 */
322 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
323 /**
324 * The maximum number of background jobs we allow when the system is in a critical
325 * memory state.
326 */
327 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700328 /**
329 * The maximum number of times we allow a job to have itself rescheduled before
330 * giving up on it, for standard jobs.
331 */
332 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
333 /**
334 * The maximum number of times we allow a job to have itself rescheduled before
335 * giving up on it, for jobs that are executing work.
336 */
337 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
338 /**
339 * The minimum backoff time to allow for linear backoff.
340 */
341 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
342 /**
343 * The minimum backoff time to allow for exponential backoff.
344 */
345 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700346
347 private ContentResolver mResolver;
348 private final KeyValueListParser mParser = new KeyValueListParser(',');
349
350 public Constants(Handler handler) {
351 super(handler);
352 }
353
354 public void start(ContentResolver resolver) {
355 mResolver = resolver;
356 mResolver.registerContentObserver(Settings.Global.getUriFor(
357 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
358 updateConstants();
359 }
360
361 @Override
362 public void onChange(boolean selfChange, Uri uri) {
363 updateConstants();
364 }
365
366 private void updateConstants() {
367 synchronized (mLock) {
368 try {
369 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000370 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700371 } catch (IllegalArgumentException e) {
372 // Failed to parse the settings string, log this and move on
373 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000374 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700375 }
376
377 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
378 DEFAULT_MIN_IDLE_COUNT);
379 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
380 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800381 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
382 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700383 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
384 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700385 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
386 DEFAULT_MIN_CONNECTIVITY_COUNT);
387 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
388 DEFAULT_MIN_CONTENT_COUNT);
389 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
390 DEFAULT_MIN_READY_JOBS_COUNT);
391 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
392 DEFAULT_HEAVY_USE_FACTOR);
393 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
394 DEFAULT_MODERATE_USE_FACTOR);
395 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
396 DEFAULT_FG_JOB_COUNT);
397 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
398 DEFAULT_BG_NORMAL_JOB_COUNT);
399 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
400 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
401 }
402 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
403 DEFAULT_BG_MODERATE_JOB_COUNT);
404 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
405 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
406 }
407 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
408 DEFAULT_BG_LOW_JOB_COUNT);
409 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
410 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
411 }
412 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
413 DEFAULT_BG_CRITICAL_JOB_COUNT);
414 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
415 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
416 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700417 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
418 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
419 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
420 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
421 MIN_LINEAR_BACKOFF_TIME = mParser.getLong(KEY_MIN_LINEAR_BACKOFF_TIME,
422 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
423 MIN_EXP_BACKOFF_TIME = mParser.getLong(KEY_MIN_EXP_BACKOFF_TIME,
424 DEFAULT_MIN_EXP_BACKOFF_TIME);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700425 }
426 }
427
428 void dump(PrintWriter pw) {
429 pw.println(" Settings:");
430
431 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
432 pw.print(MIN_IDLE_COUNT); pw.println();
433
434 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
435 pw.print(MIN_CHARGING_COUNT); pw.println();
436
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800437 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
438 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
439
Dianne Hackborn532ea262017-03-17 17:50:55 -0700440 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
441 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
442
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700443 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
444 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
445
446 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
447 pw.print(MIN_CONTENT_COUNT); pw.println();
448
449 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
450 pw.print(MIN_READY_JOBS_COUNT); pw.println();
451
452 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
453 pw.print(HEAVY_USE_FACTOR); pw.println();
454
455 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
456 pw.print(MODERATE_USE_FACTOR); pw.println();
457
458 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
459 pw.print(FG_JOB_COUNT); pw.println();
460
461 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
462 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
463
464 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
465 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
466
467 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
468 pw.print(BG_LOW_JOB_COUNT); pw.println();
469
470 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
471 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700472
473 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
474 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
475
476 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
477 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
478
479 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
480 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
481
482 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
483 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700484 }
485 }
486
487 final Constants mConstants;
488
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700489 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
490 if (o1.enqueueTime < o2.enqueueTime) {
491 return -1;
492 }
493 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
494 };
495
496 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
497 int where = Collections.binarySearch(array, newItem, comparator);
498 if (where < 0) {
499 where = ~where;
500 }
501 array.add(where, newItem);
502 }
503
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700504 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700505 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
506 * still clean up. On reinstall the package will have a new uid.
507 */
508 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
509 @Override
510 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700511 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700512 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700513 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700514 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700515 final String pkgName = getPackageName(intent);
516 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
517
Christopher Tateee7805b2016-07-15 16:56:56 -0700518 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700519 // Purge the app's jobs if the whole package was just disabled. When this is
520 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700521 if (pkgName != null && pkgUid != -1) {
522 final String[] changedComponents = intent.getStringArrayExtra(
523 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
524 if (changedComponents != null) {
525 for (String component : changedComponents) {
526 if (component.equals(pkgName)) {
527 if (DEBUG) {
528 Slog.d(TAG, "Package state change: " + pkgName);
529 }
530 try {
531 final int userId = UserHandle.getUserId(pkgUid);
532 IPackageManager pm = AppGlobals.getPackageManager();
533 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
534 if (state == COMPONENT_ENABLED_STATE_DISABLED
535 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
536 if (DEBUG) {
537 Slog.d(TAG, "Removing jobs for package " + pkgName
538 + " in user " + userId);
539 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700540 cancelJobsForPackageAndUid(pkgName, pkgUid,
541 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700542 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700543 } catch (RemoteException|IllegalArgumentException e) {
544 /*
545 * IllegalArgumentException means that the package doesn't exist.
546 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
547 * behind outright uninstall, so by the time we try to act it's gone.
548 * We don't need to act on this PACKAGE_CHANGED when this happens;
549 * we'll get a PACKAGE_REMOVED later and clean up then.
550 *
551 * RemoteException can't actually happen; the package manager is
552 * running in this same process.
553 */
554 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700555 break;
556 }
557 }
558 }
559 } else {
560 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
561 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700562 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700563 // If this is an outright uninstall rather than the first half of an
564 // app update sequence, cancel the jobs associated with the app.
565 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
566 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
567 if (DEBUG) {
568 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
569 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700570 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700571 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700572 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700573 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
574 if (DEBUG) {
575 Slog.d(TAG, "Removing jobs for user: " + userId);
576 }
577 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700578 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
579 // Has this package scheduled any jobs, such that we will take action
580 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700581 if (pkgUid != -1) {
582 List<JobStatus> jobsForUid;
583 synchronized (mLock) {
584 jobsForUid = mJobs.getJobsByUid(pkgUid);
585 }
586 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
587 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
588 if (DEBUG) {
589 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
590 + pkgUid + " has jobs");
591 }
592 setResultCode(Activity.RESULT_OK);
593 break;
594 }
595 }
596 }
597 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
598 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700599 if (pkgUid != -1) {
600 if (DEBUG) {
601 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
602 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700603 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700604 }
Christopher Tate7060b042014-06-09 19:50:00 -0700605 }
606 }
607 };
608
Christopher Tateb5c07882016-05-26 17:11:09 -0700609 private String getPackageName(Intent intent) {
610 Uri uri = intent.getData();
611 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
612 return pkg;
613 }
614
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700615 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700616 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800617 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700618 }
619
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700620 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800621 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800622 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700623 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800624 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700625 synchronized (mLock) {
626 mBackgroundJobsController.setUidActiveLocked(uid, false);
627 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700628 }
629
630 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700631 synchronized (mLock) {
632 mBackgroundJobsController.setUidActiveLocked(uid, true);
633 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700634 }
635
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700636 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800637 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700638 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800639 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700640 synchronized (mLock) {
641 mBackgroundJobsController.setUidActiveLocked(uid, false);
642 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700643 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700644
645 @Override public void onUidCachedChanged(int uid, boolean cached) {
646 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700647 };
648
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800649 public Object getLock() {
650 return mLock;
651 }
652
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700653 public JobStore getJobStore() {
654 return mJobs;
655 }
656
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700657 @Override
658 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700659 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
660 // Let's kick any outstanding jobs for this user.
661 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
662 }
663
664 @Override
665 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700666 // Let's kick any outstanding jobs for this user.
667 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
668 }
669
670 @Override
671 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700672 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700673 }
674
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700675 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
676 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700677 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800678 if (ActivityManager.getService().isAppStartModeDisabled(uId,
679 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700680 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
681 + " -- package not allowed to start");
682 return JobScheduler.RESULT_FAILURE;
683 }
684 } catch (RemoteException e) {
685 }
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800686 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700687 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
688
689 if (work != null && toCancel != null) {
690 // Fast path: we are adding work to an existing job, and the JobInfo is not
691 // changing. We can just directly enqueue this work in to the job.
692 if (toCancel.getJob().equals(job)) {
Dianne Hackborn342e6032017-04-13 18:04:31 -0700693 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700694 return JobScheduler.RESULT_SUCCESS;
695 }
696 }
697
698 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
699 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800700 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800701 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800702 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
703 Slog.w(TAG, "Too many jobs for uid " + uId);
704 throw new IllegalStateException("Apps may not schedule more than "
705 + MAX_JOBS_PER_APP + " distinct jobs");
706 }
707 }
708
Dianne Hackborna47223f2017-03-30 13:49:13 -0700709 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700710 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700711
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700712 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700713 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700714 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700715 if (work != null) {
716 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700717 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700718 }
719 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700720
721 // If the job is immediately ready to run, then we can just immediately
722 // put it in the pending list and try to schedule it. This is especially
723 // important for jobs with a 0 deadline constraint, since they will happen a fair
724 // amount, we want to handle them as quickly as possible, and semantically we want to
725 // make sure we have started holding the wake lock for the job before returning to
726 // the caller.
727 // If the job is not yet ready to run, there is nothing more to do -- we are
728 // now just waiting for one of its controllers to change state and schedule
729 // the job appropriately.
730 if (isReadyToBeExecutedLocked(jobStatus)) {
731 // This is a new job, we can just immediately put it on the pending
732 // list and try to run it.
733 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700734 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700735 maybeRunPendingJobsLocked();
736 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800737 }
Christopher Tate7060b042014-06-09 19:50:00 -0700738 return JobScheduler.RESULT_SUCCESS;
739 }
740
741 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800742 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800743 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
744 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
745 for (int i = jobs.size() - 1; i >= 0; i--) {
746 JobStatus job = jobs.get(i);
747 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700748 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800749 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700750 }
Christopher Tate7060b042014-06-09 19:50:00 -0700751 }
752
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600753 public JobInfo getPendingJob(int uid, int jobId) {
754 synchronized (mLock) {
755 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
756 for (int i = jobs.size() - 1; i >= 0; i--) {
757 JobStatus job = jobs.get(i);
758 if (job.getJobId() == jobId) {
759 return job.getJob();
760 }
761 }
762 return null;
763 }
764 }
765
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700766 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800767 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700768 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
769 for (int i=0; i<jobsForUser.size(); i++) {
770 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700771 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700772 }
Christopher Tate7060b042014-06-09 19:50:00 -0700773 }
774 }
775
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700776 private void cancelJobsForNonExistentUsers() {
777 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
778 synchronized (mLock) {
779 mJobs.removeJobsOfNonUsers(umi.getUserIds());
780 }
781 }
782
Makoto Onukie7b96182017-08-30 14:53:16 -0700783 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
784 if ("android".equals(pkgName)) {
785 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
786 return;
787 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700788 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700789 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
790 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
791 final JobStatus job = jobsForUid.get(i);
792 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700793 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700794 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700795 }
796 }
797 }
798
Christopher Tate7060b042014-06-09 19:50:00 -0700799 /**
800 * Entry point from client to cancel all jobs originating from their uid.
801 * This will remove the job from the master list, and cancel the job if it was staged for
802 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700803 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800804 *
Christopher Tate7060b042014-06-09 19:50:00 -0700805 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700806 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700807 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700808 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700809 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700810 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700811
812 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800813 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700814 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
815 for (int i=0; i<jobsForUid.size(); i++) {
816 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700817 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700818 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700819 }
Christopher Tate7060b042014-06-09 19:50:00 -0700820 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700821 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700822 }
823
824 /**
825 * Entry point from client to cancel the job corresponding to the jobId provided.
826 * This will remove the job from the master list, and cancel the job if it was staged for
827 * execution or being executed.
828 * @param uid Uid of the calling client.
829 * @param jobId Id of the job, provided at schedule-time.
830 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700831 public boolean cancelJob(int uid, int jobId) {
Christopher Tate7060b042014-06-09 19:50:00 -0700832 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800833 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700834 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700835 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700836 cancelJobImplLocked(toCancel, null, "cancel() called by app");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700837 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700838 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -0700839 }
840 }
841
Dianne Hackborn729a3282017-06-09 16:06:01 -0700842 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700843 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
844 cancelled.unprepareLocked(ActivityManager.getService());
845 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
846 // Remove from pending queue.
847 if (mPendingJobs.remove(cancelled)) {
848 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700849 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700850 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700851 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700852 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700853 }
854
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800855 void updateUidState(int uid, int procState) {
856 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800857 if (procState == ActivityManager.PROCESS_STATE_TOP) {
858 // Only use this if we are exactly the top app. All others can live
859 // with just the foreground priority. This means that persistent processes
860 // can never be the top app priority... that is fine.
861 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
862 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
863 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800864 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800865 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800866 }
867 }
868 }
869
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700870 @Override
871 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800872 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700873 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600874 // When becoming idle, make sure no jobs are actively running,
875 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700876 for (int i=0; i<mActiveServices.size(); i++) {
877 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700878 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600879 if (executing != null
880 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700881 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
882 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700883 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700884 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700885 } else {
886 // When coming out of idle, allow thing to start back up.
887 if (mReadyToRock) {
888 if (mLocalDeviceIdleController != null) {
889 if (!mReportedActive) {
890 mReportedActive = true;
891 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700892 }
893 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700894 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700895 }
896 }
897 }
898 }
899
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700900 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000901 // active is true if pending queue contains jobs OR some job is running.
902 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800903 if (mPendingJobs.size() <= 0) {
904 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700905 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700906 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700907 if (job != null
908 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
909 && !job.dozeWhitelisted) {
910 // We will report active if we have a job running and it is not an exception
911 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800912 active = true;
913 break;
914 }
915 }
916 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000917
918 if (mReportedActive != active) {
919 mReportedActive = active;
920 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800921 mLocalDeviceIdleController.setJobsActive(active);
922 }
923 }
924 }
925
Christopher Tate7060b042014-06-09 19:50:00 -0700926 /**
927 * Initializes the system service.
928 * <p>
929 * Subclasses must define a single argument constructor that accepts the context
930 * and passes it to super.
931 * </p>
932 *
933 * @param context The system server context.
934 */
935 public JobSchedulerService(Context context) {
936 super(context);
Dianne Hackborn970e3f42016-06-01 10:55:13 -0700937 mHandler = new JobHandler(context.getMainLooper());
938 mConstants = new Constants(mHandler);
939 mJobSchedulerStub = new JobSchedulerStub();
940 mJobs = JobStore.initAndGet(this);
941
Christopher Tate7060b042014-06-09 19:50:00 -0700942 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700943 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -0700944 mControllers.add(ConnectivityController.get(this));
945 mControllers.add(TimeController.get(this));
946 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800947 mBatteryController = BatteryController.get(this);
948 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700949 mStorageController = StorageController.get(this);
950 mControllers.add(mStorageController);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700951 mBackgroundJobsController = BackgroundJobsController.get(this);
952 mControllers.add(mBackgroundJobsController);
Amith Yamasanib0ff3222015-03-04 09:56:14 -0800953 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800954 mControllers.add(ContentObserverController.get(this));
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700955 mControllers.add(DeviceIdleJobsController.get(this));
Christopher Tate616541d2017-07-26 14:27:38 -0700956
957 // If the job store determined that it can't yet reschedule persisted jobs,
958 // we need to start watching the clock.
959 if (!mJobs.jobTimesInflatedValid()) {
960 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
961 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
962 }
Christopher Tate7060b042014-06-09 19:50:00 -0700963 }
964
Christopher Tate616541d2017-07-26 14:27:38 -0700965 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
966 @Override
967 public void onReceive(Context context, Intent intent) {
968 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
969 // When we reach clock sanity, recalculate the temporal windows
970 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700971 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -0700972 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
973
974 // We've done our job now, so stop watching the time.
975 context.unregisterReceiver(this);
976
977 // And kick off the work to update the affected jobs, using a secondary
978 // thread instead of chugging away here on the main looper thread.
979 FgThread.getHandler().post(mJobTimeUpdater);
980 }
981 }
982 }
983 };
984
985 private final Runnable mJobTimeUpdater = () -> {
986 final ArrayList<JobStatus> toRemove = new ArrayList<>();
987 final ArrayList<JobStatus> toAdd = new ArrayList<>();
988 synchronized (mLock) {
989 // Note: we intentionally both look up the existing affected jobs and replace them
990 // with recalculated ones inside the same lock lifetime.
991 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
992
993 // Now, at each position [i], we have both the existing JobStatus
994 // and the one that replaces it.
995 final int N = toAdd.size();
996 for (int i = 0; i < N; i++) {
997 final JobStatus oldJob = toRemove.get(i);
998 final JobStatus newJob = toAdd.get(i);
999 if (DEBUG) {
1000 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1001 }
1002 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1003 }
1004 }
1005 };
1006
Christopher Tate7060b042014-06-09 19:50:00 -07001007 @Override
1008 public void onStart() {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001009 publishLocalService(JobSchedulerInternal.class, new LocalService());
Christopher Tate7060b042014-06-09 19:50:00 -07001010 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1011 }
1012
1013 @Override
1014 public void onBootPhase(int phase) {
1015 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001016 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001017 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001018 final IntentFilter filter = new IntentFilter();
1019 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1020 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001021 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1022 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001023 filter.addDataScheme("package");
1024 getContext().registerReceiverAsUser(
1025 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1026 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1027 getContext().registerReceiverAsUser(
1028 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001029 mPowerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001030 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001031 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001032 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001033 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1034 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001035 } catch (RemoteException e) {
1036 // ignored; both services live in system_server
1037 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001038 // Remove any jobs that are not associated with any of the current users.
1039 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001040 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001041 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001042 // Let's go!
1043 mReadyToRock = true;
1044 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1045 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001046 mLocalDeviceIdleController
1047 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001048 // Create the "runners".
1049 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1050 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001051 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001052 getContext().getMainLooper()));
1053 }
1054 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001055 mJobs.forEachJob(new JobStatusFunctor() {
1056 @Override
1057 public void process(JobStatus job) {
1058 for (int controller = 0; controller < mControllers.size(); controller++) {
1059 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001060 sc.maybeStartTrackingJobLocked(job, null);
1061 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001062 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001063 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001064 // GO GO GO!
1065 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1066 }
Christopher Tate7060b042014-06-09 19:50:00 -07001067 }
1068 }
1069
1070 /**
1071 * Called when we have a job status object that we need to insert in our
1072 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1073 * about.
1074 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001075 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1076 if (!jobStatus.isPreparedLocked()) {
1077 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1078 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001079 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001080 final boolean update = mJobs.add(jobStatus);
1081 if (mReadyToRock) {
1082 for (int i = 0; i < mControllers.size(); i++) {
1083 StateController controller = mControllers.get(i);
1084 if (update) {
1085 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001086 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001087 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001088 }
Christopher Tate7060b042014-06-09 19:50:00 -07001089 }
1090 }
1091
1092 /**
1093 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1094 * object removed.
1095 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001096 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001097 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001098 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001099 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001100
1101 // Remove from store as well as controllers.
1102 final boolean removed = mJobs.remove(jobStatus, writeBack);
1103 if (removed && mReadyToRock) {
1104 for (int i=0; i<mControllers.size(); i++) {
1105 StateController controller = mControllers.get(i);
1106 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001107 }
1108 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001109 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001110 }
1111
Dianne Hackborn729a3282017-06-09 16:06:01 -07001112 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001113 for (int i=0; i<mActiveServices.size(); i++) {
1114 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001115 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001116 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001117 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001118 return true;
1119 }
1120 }
1121 return false;
1122 }
1123
1124 /**
1125 * @param job JobStatus we are querying against.
1126 * @return Whether or not the job represented by the status object is currently being run or
1127 * is pending.
1128 */
1129 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001130 for (int i=0; i<mActiveServices.size(); i++) {
1131 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001132 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001133 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1134 return true;
1135 }
1136 }
1137 return false;
1138 }
1139
Dianne Hackborn807de782016-04-07 17:54:41 -07001140 void noteJobsPending(List<JobStatus> jobs) {
1141 for (int i = jobs.size() - 1; i >= 0; i--) {
1142 JobStatus job = jobs.get(i);
1143 mJobPackageTracker.notePending(job);
1144 }
1145 }
1146
1147 void noteJobsNonpending(List<JobStatus> jobs) {
1148 for (int i = jobs.size() - 1; i >= 0; i--) {
1149 JobStatus job = jobs.get(i);
1150 mJobPackageTracker.noteNonpending(job);
1151 }
1152 }
1153
Christopher Tate7060b042014-06-09 19:50:00 -07001154 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001155 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1156 * specify an override deadline on a failed job (the failed job will run even though it's not
1157 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1158 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1159 *
Christopher Tate7060b042014-06-09 19:50:00 -07001160 * @param failureToReschedule Provided job status that we will reschedule.
1161 * @return A newly instantiated JobStatus with the same constraints as the last job except
1162 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001163 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001164 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001165 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001166 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001167 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001168 final JobInfo job = failureToReschedule.getJob();
1169
1170 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001171 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1172 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001173
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001174 if (failureToReschedule.hasWorkLocked()) {
1175 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1176 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1177 + backoffAttempts + " > work limit "
1178 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1179 return null;
1180 }
1181 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1182 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1183 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1184 return null;
1185 }
1186
Christopher Tate7060b042014-06-09 19:50:00 -07001187 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001188 case JobInfo.BACKOFF_POLICY_LINEAR: {
1189 long backoff = initialBackoffMillis;
1190 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1191 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1192 }
1193 delayMillis = backoff * backoffAttempts;
1194 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001195 default:
1196 if (DEBUG) {
1197 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1198 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001199 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1200 long backoff = initialBackoffMillis;
1201 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1202 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1203 }
1204 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1205 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001206 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001207 delayMillis =
1208 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001209 JobStatus newJob = new JobStatus(failureToReschedule, elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001210 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001211 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001212 for (int ic=0; ic<mControllers.size(); ic++) {
1213 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001214 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001215 }
1216 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001217 }
1218
1219 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001220 * Called after a periodic has executed so we can reschedule it. We take the last execution
1221 * time of the job to be the time of completion (i.e. the time at which this function is
1222 * called).
Christopher Tate7060b042014-06-09 19:50:00 -07001223 * This could be inaccurate b/c the job can run for as long as
1224 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1225 * to underscheduling at least, rather than if we had taken the last execution time to be the
1226 * start of the execution.
1227 * @return A new job representing the execution criteria for this instantiation of the
1228 * recurring job.
1229 */
1230 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001231 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001232 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001233 long runEarly = 0L;
1234
1235 // If this periodic was rescheduled it won't have a deadline.
1236 if (periodicToReschedule.hasDeadlineConstraint()) {
1237 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1238 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001239 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001240 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001241 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1242 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001243
1244 if (DEBUG) {
1245 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1246 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1247 }
1248 return new JobStatus(periodicToReschedule, newEarliestRunTimeElapsed,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001249 newLatestRuntimeElapsed, 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001250 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001251 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001252 }
1253
1254 // JobCompletedListener implementations.
1255
1256 /**
1257 * A job just finished executing. We fetch the
1258 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1259 * whether we want to reschedule we readd it to the controllers.
1260 * @param jobStatus Completed job.
1261 * @param needsReschedule Whether the implementing class should reschedule this job.
1262 */
1263 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001264 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001265 if (DEBUG) {
1266 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1267 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001268
1269 // If the job wants to be rescheduled, we first need to make the next upcoming
1270 // job so we can transfer any appropriate state over from the previous job when
1271 // we stop it.
1272 final JobStatus rescheduledJob = needsReschedule
1273 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1274
Shreyas Basarge73f10252016-02-11 17:06:13 +00001275 // Do not write back immediately if this is a periodic job. The job may get lost if system
1276 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001277 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001278 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001279 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001280 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001281 // We still want to check for jobs to execute, because this job may have
1282 // scheduled a new job under the same job id, and now we can run it.
1283 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001284 return;
1285 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001286
1287 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001288 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001289 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001290 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001291 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001292 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001293 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001294 } else if (jobStatus.getJob().isPeriodic()) {
1295 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001296 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001297 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001298 } catch (SecurityException e) {
1299 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1300 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001301 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001302 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001303 jobStatus.unprepareLocked(ActivityManager.getService());
1304 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001305 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001306 }
1307
1308 // StateChangedListener implementations.
1309
1310 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001311 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1312 * some controller's state has changed, so as to run through the list of jobs and start/stop
1313 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001314 */
1315 @Override
1316 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001317 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001318 }
1319
1320 @Override
1321 public void onRunJobNow(JobStatus jobStatus) {
1322 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1323 }
1324
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001325 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001326
1327 public JobHandler(Looper looper) {
1328 super(looper);
1329 }
1330
1331 @Override
1332 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001333 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001334 if (!mReadyToRock) {
1335 return;
1336 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001337 switch (message.what) {
1338 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001339 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001340 // runNow can be null, which is a controller's way of indicating that its
1341 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001342 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001343 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001344 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001345 } else {
1346 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001347 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001348 } break;
1349 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001350 if (mReportedActive) {
1351 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001352 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001353 } else {
1354 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001355 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001356 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001357 break;
1358 case MSG_CHECK_JOB_GREEDY:
1359 queueReadyJobsForExecutionLocked();
1360 break;
1361 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001362 cancelJobImplLocked((JobStatus) message.obj, null,
1363 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001364 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001365 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001366 maybeRunPendingJobsLocked();
1367 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1368 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001369 }
1370 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001371 }
Christopher Tate7060b042014-06-09 19:50:00 -07001372
Dianne Hackborn6d068262017-05-16 13:14:37 -07001373 private void stopNonReadyActiveJobsLocked() {
1374 for (int i=0; i<mActiveServices.size(); i++) {
1375 JobServiceContext serviceContext = mActiveServices.get(i);
1376 final JobStatus running = serviceContext.getRunningJobLocked();
1377 if (running != null && !running.isReady()) {
1378 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001379 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1380 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001381 }
1382 }
1383 }
1384
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001385 /**
1386 * Run through list of jobs and execute all possible - at least one is expired so we do
1387 * as many as we can.
1388 */
1389 private void queueReadyJobsForExecutionLocked() {
1390 if (DEBUG) {
1391 Slog.d(TAG, "queuing all ready jobs for execution:");
1392 }
1393 noteJobsNonpending(mPendingJobs);
1394 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001395 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001396 mJobs.forEachJob(mReadyQueueFunctor);
1397 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001398
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001399 if (DEBUG) {
1400 final int queuedJobs = mPendingJobs.size();
1401 if (queuedJobs == 0) {
1402 Slog.d(TAG, "No jobs pending.");
1403 } else {
1404 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001405 }
1406 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001407 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001408
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001409 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1410 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001411
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001412 @Override
1413 public void process(JobStatus job) {
1414 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001415 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001416 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001417 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001418 if (newReadyJobs == null) {
1419 newReadyJobs = new ArrayList<JobStatus>();
1420 }
1421 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001422 }
1423 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001424
1425 public void postProcess() {
1426 if (newReadyJobs != null) {
1427 noteJobsPending(newReadyJobs);
1428 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001429 if (mPendingJobs.size() > 1) {
1430 mPendingJobs.sort(mEnqueueTimeComparator);
1431 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001432 }
1433 newReadyJobs = null;
1434 }
1435 }
1436 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1437
1438 /**
1439 * The state of at least one job has changed. Here is where we could enforce various
1440 * policies on when we want to execute jobs.
1441 * Right now the policy is such:
1442 * If >1 of the ready jobs is idle mode we send all of them off
1443 * if more than 2 network connectivity jobs are ready we send them all off.
1444 * If more than 4 jobs total are ready we send them all off.
1445 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1446 */
1447 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1448 int chargingCount;
1449 int batteryNotLowCount;
1450 int storageNotLowCount;
1451 int idleCount;
1452 int backoffCount;
1453 int connectivityCount;
1454 int contentCount;
1455 List<JobStatus> runnableJobs;
1456
1457 public MaybeReadyJobQueueFunctor() {
1458 reset();
1459 }
1460
1461 // Functor method invoked for each job via JobStore.forEachJob()
1462 @Override
1463 public void process(JobStatus job) {
1464 if (isReadyToBeExecutedLocked(job)) {
1465 try {
1466 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1467 job.getJob().getService().getPackageName())) {
1468 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1469 + job.getJob().toString() + " -- package not allowed to start");
1470 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1471 return;
1472 }
1473 } catch (RemoteException e) {
1474 }
1475 if (job.getNumFailures() > 0) {
1476 backoffCount++;
1477 }
1478 if (job.hasIdleConstraint()) {
1479 idleCount++;
1480 }
1481 if (job.hasConnectivityConstraint()) {
1482 connectivityCount++;
1483 }
1484 if (job.hasChargingConstraint()) {
1485 chargingCount++;
1486 }
1487 if (job.hasBatteryNotLowConstraint()) {
1488 batteryNotLowCount++;
1489 }
1490 if (job.hasStorageNotLowConstraint()) {
1491 storageNotLowCount++;
1492 }
1493 if (job.hasContentTriggerConstraint()) {
1494 contentCount++;
1495 }
1496 if (runnableJobs == null) {
1497 runnableJobs = new ArrayList<>();
1498 }
1499 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001500 }
1501 }
1502
1503 public void postProcess() {
1504 if (backoffCount > 0 ||
1505 idleCount >= mConstants.MIN_IDLE_COUNT ||
1506 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1507 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1508 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1509 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1510 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1511 (runnableJobs != null
1512 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1513 if (DEBUG) {
1514 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1515 }
1516 noteJobsPending(runnableJobs);
1517 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001518 if (mPendingJobs.size() > 1) {
1519 mPendingJobs.sort(mEnqueueTimeComparator);
1520 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001521 } else {
1522 if (DEBUG) {
1523 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1524 }
1525 }
1526
1527 // Be ready for next time
1528 reset();
1529 }
1530
1531 private void reset() {
1532 chargingCount = 0;
1533 idleCount = 0;
1534 backoffCount = 0;
1535 connectivityCount = 0;
1536 batteryNotLowCount = 0;
1537 storageNotLowCount = 0;
1538 contentCount = 0;
1539 runnableJobs = null;
1540 }
1541 }
1542 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1543
1544 private void maybeQueueReadyJobsForExecutionLocked() {
1545 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1546
1547 noteJobsNonpending(mPendingJobs);
1548 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001549 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001550 mJobs.forEachJob(mMaybeQueueFunctor);
1551 mMaybeQueueFunctor.postProcess();
1552 }
1553
1554 /**
1555 * Criteria for moving a job into the pending queue:
1556 * - It's ready.
1557 * - It's not pending.
1558 * - It's not already running on a JSC.
1559 * - The user that requested the job is running.
1560 * - The component is enabled and runnable.
1561 */
1562 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001563 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001564
1565 if (DEBUG) {
1566 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1567 + " ready=" + jobReady);
1568 }
1569
1570 // This is a condition that is very likely to be false (most jobs that are
1571 // scheduled are sitting there, not ready yet) and very cheap to check (just
1572 // a few conditions on data in JobStatus).
1573 if (!jobReady) {
1574 return false;
1575 }
1576
1577 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001578
1579 final int userId = job.getUserId();
1580 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1581
1582 if (DEBUG) {
1583 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001584 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001585 }
1586
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001587 // These are also fairly cheap to check, though they typically will not
1588 // be conditions we fail.
1589 if (!jobExists || !userStarted) {
1590 return false;
1591 }
1592
1593 final boolean jobPending = mPendingJobs.contains(job);
1594 final boolean jobActive = isCurrentlyActiveLocked(job);
1595
1596 if (DEBUG) {
1597 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1598 + " pending=" + jobPending + " active=" + jobActive);
1599 }
1600
1601 // These can be a little more expensive (especially jobActive, since we need to
1602 // go through the array of all potentially active jobs), so we are doing them
1603 // later... but still before checking with the package manager!
1604 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001605 return false;
1606 }
1607
1608 final boolean componentPresent;
1609 try {
1610 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1611 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1612 userId) != null);
1613 } catch (RemoteException e) {
1614 throw e.rethrowAsRuntimeException();
1615 }
1616
1617 if (DEBUG) {
1618 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1619 + " componentPresent=" + componentPresent);
1620 }
1621
1622 // Everything else checked out so far, so this is the final yes/no check
1623 return componentPresent;
1624 }
1625
1626 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001627 * Reconcile jobs in the pending queue against available execution contexts.
1628 * A controller can force a job into the pending queue even if it's already running, but
1629 * here is where we decide whether to actually execute it.
1630 */
1631 private void maybeRunPendingJobsLocked() {
1632 if (DEBUG) {
1633 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1634 }
1635 assignJobsToContextsLocked();
1636 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001637 }
1638
Dianne Hackborn807de782016-04-07 17:54:41 -07001639 private int adjustJobPriority(int curPriority, JobStatus job) {
1640 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1641 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001642 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001643 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001644 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001645 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1646 }
1647 }
1648 return curPriority;
1649 }
1650
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001651 private int evaluateJobPriorityLocked(JobStatus job) {
1652 int priority = job.getPriority();
1653 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001654 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001655 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001656 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1657 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001658 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001659 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001660 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001661 }
1662
Christopher Tate7060b042014-06-09 19:50:00 -07001663 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001664 * Takes jobs from pending queue and runs them on available contexts.
1665 * If no contexts are available, preempts lower priority jobs to
1666 * run higher priority ones.
1667 * Lock on mJobs before calling this function.
1668 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001669 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001670 if (DEBUG) {
1671 Slog.d(TAG, printPendingQueue());
1672 }
1673
Dianne Hackborn970510b2016-02-24 16:56:42 -08001674 int memLevel;
1675 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001676 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001677 } catch (RemoteException e) {
1678 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1679 }
1680 switch (memLevel) {
1681 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001682 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001683 break;
1684 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001685 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001686 break;
1687 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001688 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001689 break;
1690 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001691 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001692 break;
1693 }
1694
1695 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1696 boolean[] act = mTmpAssignAct;
1697 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1698 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001699 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001700 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1701 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001702 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001703 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001704 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001705 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1706 numForeground++;
1707 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001708 }
1709 act[i] = false;
1710 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001711 }
1712 if (DEBUG) {
1713 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1714 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001715 for (int i=0; i<mPendingJobs.size(); i++) {
1716 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001717
1718 // If job is already running, go to next job.
1719 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1720 if (jobRunningContext != -1) {
1721 continue;
1722 }
1723
Dianne Hackborn970510b2016-02-24 16:56:42 -08001724 final int priority = evaluateJobPriorityLocked(nextPending);
1725 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001726
Shreyas Basarge5db09082016-01-07 13:38:29 +00001727 // Find a context for nextPending. The context should be available OR
1728 // it should have lowest priority among all running jobs
1729 // (sharing the same Uid as nextPending)
1730 int minPriority = Integer.MAX_VALUE;
1731 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001732 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1733 JobStatus job = contextIdToJobMap[j];
1734 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001735 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001736 if ((numActive < mMaxActiveJobs ||
1737 (priority >= JobInfo.PRIORITY_TOP_APP &&
1738 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001739 (preferredUid == nextPending.getUid() ||
1740 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1741 // This slot is free, and we haven't yet hit the limit on
1742 // concurrent jobs... we can just throw the job in to here.
1743 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001744 break;
1745 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001746 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001747 // the context has a preferred Uid or we have reached the limit on
1748 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001749 continue;
1750 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001751 if (job.getUid() != nextPending.getUid()) {
1752 continue;
1753 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001754 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001755 continue;
1756 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001757 if (minPriority > nextPending.lastEvaluatedPriority) {
1758 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001759 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001760 }
1761 }
1762 if (minPriorityContextId != -1) {
1763 contextIdToJobMap[minPriorityContextId] = nextPending;
1764 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001765 numActive++;
1766 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1767 numForeground++;
1768 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001769 }
1770 }
1771 if (DEBUG) {
1772 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1773 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001774 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001775 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001776 boolean preservePreferredUid = false;
1777 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001778 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001779 if (js != null) {
1780 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001781 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001782 }
1783 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001784 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001785 preservePreferredUid = true;
1786 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001787 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001788 if (DEBUG) {
1789 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001790 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001791 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001792 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001793 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001794 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001795 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1796 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001797 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001798 if (mPendingJobs.remove(pendingJob)) {
1799 mJobPackageTracker.noteNonpending(pendingJob);
1800 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001801 }
1802 }
1803 if (!preservePreferredUid) {
1804 mActiveServices.get(i).clearPreferredUid();
1805 }
1806 }
1807 }
1808
1809 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1810 for (int i=0; i<map.length; i++) {
1811 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1812 return i;
1813 }
1814 }
1815 return -1;
1816 }
1817
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001818 final class LocalService implements JobSchedulerInternal {
1819
1820 /**
1821 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1822 * jobs are always considered pending.
1823 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001824 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001825 public List<JobInfo> getSystemScheduledPendingJobs() {
1826 synchronized (mLock) {
1827 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1828 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1829 @Override
1830 public void process(JobStatus job) {
1831 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1832 pendingJobs.add(job.getJob());
1833 }
1834 }
1835 });
1836 return pendingJobs;
1837 }
1838 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001839
1840 @Override
1841 public void addBackingUpUid(int uid) {
1842 synchronized (mLock) {
1843 // No need to actually do anything here, since for a full backup the
1844 // activity manager will kill the process which will kill the job (and
1845 // cause it to restart, but now it can't run).
1846 mBackingUpUids.put(uid, uid);
1847 }
1848 }
1849
1850 @Override
1851 public void removeBackingUpUid(int uid) {
1852 synchronized (mLock) {
1853 mBackingUpUids.delete(uid);
1854 // If there are any jobs for this uid, we need to rebuild the pending list
1855 // in case they are now ready to run.
1856 if (mJobs.countJobsForUid(uid) > 0) {
1857 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1858 }
1859 }
1860 }
1861
1862 @Override
1863 public void clearAllBackingUpUids() {
1864 synchronized (mLock) {
1865 if (mBackingUpUids.size() > 0) {
1866 mBackingUpUids.clear();
1867 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1868 }
1869 }
1870 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07001871
1872 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07001873 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07001874 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07001875 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07001876 }
1877 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001878 }
1879
Shreyas Basarge5db09082016-01-07 13:38:29 +00001880 /**
Christopher Tate7060b042014-06-09 19:50:00 -07001881 * Binder stub trampoline implementation
1882 */
1883 final class JobSchedulerStub extends IJobScheduler.Stub {
1884 /** Cache determination of whether a given app can persist jobs
1885 * key is uid of the calling app; value is undetermined/true/false
1886 */
1887 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
1888
1889 // Enforce that only the app itself (or shared uid participant) can schedule a
1890 // job that runs one of the app's services, as well as verifying that the
1891 // named service properly requires the BIND_JOB_SERVICE permission
1892 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07001893 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07001894 final ComponentName service = job.getService();
1895 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07001896 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001897 PackageManager.MATCH_DIRECT_BOOT_AWARE
1898 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07001899 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07001900 if (si == null) {
1901 throw new IllegalArgumentException("No such service " + service);
1902 }
Christopher Tate7060b042014-06-09 19:50:00 -07001903 if (si.applicationInfo.uid != uid) {
1904 throw new IllegalArgumentException("uid " + uid +
1905 " cannot schedule job in " + service.getPackageName());
1906 }
1907 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
1908 throw new IllegalArgumentException("Scheduled service " + service
1909 + " does not require android.permission.BIND_JOB_SERVICE permission");
1910 }
Christopher Tate5568f542014-06-18 13:53:31 -07001911 } catch (RemoteException e) {
1912 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07001913 }
1914 }
1915
1916 private boolean canPersistJobs(int pid, int uid) {
1917 // If we get this far we're good to go; all we need to do now is check
1918 // whether the app is allowed to persist its scheduled work.
1919 final boolean canPersist;
1920 synchronized (mPersistCache) {
1921 Boolean cached = mPersistCache.get(uid);
1922 if (cached != null) {
1923 canPersist = cached.booleanValue();
1924 } else {
1925 // Persisting jobs is tantamount to running at boot, so we permit
1926 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
1927 // permission
1928 int result = getContext().checkPermission(
1929 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
1930 canPersist = (result == PackageManager.PERMISSION_GRANTED);
1931 mPersistCache.put(uid, canPersist);
1932 }
1933 }
1934 return canPersist;
1935 }
1936
1937 // IJobScheduler implementation
1938 @Override
1939 public int schedule(JobInfo job) throws RemoteException {
1940 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001941 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07001942 }
1943 final int pid = Binder.getCallingPid();
1944 final int uid = Binder.getCallingUid();
1945
1946 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07001947 if (job.isPersisted()) {
1948 if (!canPersistJobs(pid, uid)) {
1949 throw new IllegalArgumentException("Error: requested job be persisted without"
1950 + " holding RECEIVE_BOOT_COMPLETED permission.");
1951 }
1952 }
Christopher Tate7060b042014-06-09 19:50:00 -07001953
Jeff Sharkey785f4942016-07-14 10:31:15 -06001954 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1955 getContext().enforceCallingOrSelfPermission(
1956 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1957 }
1958
Christopher Tate7060b042014-06-09 19:50:00 -07001959 long ident = Binder.clearCallingIdentity();
1960 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001961 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, -1, null);
1962 } finally {
1963 Binder.restoreCallingIdentity(ident);
1964 }
1965 }
1966
1967 // IJobScheduler implementation
1968 @Override
1969 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
1970 if (DEBUG) {
1971 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
1972 }
1973 final int pid = Binder.getCallingPid();
1974 final int uid = Binder.getCallingUid();
1975
1976 enforceValidJobRequest(uid, job);
1977 if (job.isPersisted()) {
1978 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
1979 }
1980 if (work == null) {
1981 throw new NullPointerException("work is null");
1982 }
1983
1984 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
1985 getContext().enforceCallingOrSelfPermission(
1986 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
1987 }
1988
1989 long ident = Binder.clearCallingIdentity();
1990 try {
1991 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, -1, null);
Christopher Tate7060b042014-06-09 19:50:00 -07001992 } finally {
1993 Binder.restoreCallingIdentity(ident);
1994 }
1995 }
1996
1997 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001998 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00001999 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002000 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002001 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002002 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
2003 + " on behalf of " + packageName);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002004 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002005
2006 if (packageName == null) {
2007 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002008 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002009
2010 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2011 android.Manifest.permission.UPDATE_DEVICE_STATS);
2012 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2013 throw new SecurityException("Caller uid " + callerUid
2014 + " not permitted to schedule jobs for other apps");
2015 }
2016
Jeff Sharkey4f100402016-05-03 17:44:23 -06002017 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2018 getContext().enforceCallingOrSelfPermission(
2019 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2020 }
2021
Shreyas Basarge968ac752016-01-11 23:09:26 +00002022 long ident = Binder.clearCallingIdentity();
2023 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002024 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002025 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002026 } finally {
2027 Binder.restoreCallingIdentity(ident);
2028 }
2029 }
2030
2031 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002032 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2033 final int uid = Binder.getCallingUid();
2034
2035 long ident = Binder.clearCallingIdentity();
2036 try {
2037 return JobSchedulerService.this.getPendingJobs(uid);
2038 } finally {
2039 Binder.restoreCallingIdentity(ident);
2040 }
2041 }
2042
2043 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002044 public JobInfo getPendingJob(int jobId) throws RemoteException {
2045 final int uid = Binder.getCallingUid();
2046
2047 long ident = Binder.clearCallingIdentity();
2048 try {
2049 return JobSchedulerService.this.getPendingJob(uid, jobId);
2050 } finally {
2051 Binder.restoreCallingIdentity(ident);
2052 }
2053 }
2054
2055 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002056 public void cancelAll() throws RemoteException {
2057 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002058 long ident = Binder.clearCallingIdentity();
2059 try {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002060 JobSchedulerService.this.cancelJobsForUid(uid, "cancelAll() called by app");
Christopher Tate7060b042014-06-09 19:50:00 -07002061 } finally {
2062 Binder.restoreCallingIdentity(ident);
2063 }
2064 }
2065
2066 @Override
2067 public void cancel(int jobId) throws RemoteException {
2068 final int uid = Binder.getCallingUid();
2069
2070 long ident = Binder.clearCallingIdentity();
2071 try {
2072 JobSchedulerService.this.cancelJob(uid, jobId);
2073 } finally {
2074 Binder.restoreCallingIdentity(ident);
2075 }
2076 }
2077
2078 /**
2079 * "dumpsys" infrastructure
2080 */
2081 @Override
2082 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002083 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002084
2085 long identityToken = Binder.clearCallingIdentity();
2086 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002087 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07002088 } finally {
2089 Binder.restoreCallingIdentity(identityToken);
2090 }
2091 }
Christopher Tate5d346052016-03-08 12:56:08 -08002092
2093 @Override
2094 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002095 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002096 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002097 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002098 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002099 };
2100
Christopher Tate5d346052016-03-08 12:56:08 -08002101 // Shell command infrastructure: run the given job immediately
2102 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2103 if (DEBUG) {
2104 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2105 + " " + jobId + " f=" + force);
2106 }
2107
2108 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002109 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2110 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002111 if (uid < 0) {
2112 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2113 }
2114
2115 synchronized (mLock) {
2116 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2117 if (js == null) {
2118 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2119 }
2120
2121 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2122 if (!js.isConstraintsSatisfied()) {
2123 js.overrideState = 0;
2124 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2125 }
2126
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002127 queueReadyJobsForExecutionLocked();
2128 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002129 }
2130 } catch (RemoteException e) {
2131 // can't happen
2132 }
2133 return 0;
2134 }
2135
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002136 // Shell command infrastructure: immediately timeout currently executing jobs
2137 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2138 boolean hasJobId, int jobId) {
2139 if (DEBUG) {
2140 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2141 }
2142
2143 synchronized (mLock) {
2144 boolean foundSome = false;
2145 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002146 final JobServiceContext jc = mActiveServices.get(i);
2147 final JobStatus js = jc.getRunningJobLocked();
2148 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId)) {
2149 foundSome = true;
2150 pw.print("Timing out: ");
2151 js.printUniqueId(pw);
2152 pw.print(" ");
2153 pw.println(js.getServiceComponent().flattenToShortString());
2154 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002155 }
2156 if (!foundSome) {
2157 pw.println("No matching executing jobs found.");
2158 }
2159 }
2160 return 0;
2161 }
2162
Christopher Tate8c67d122017-09-29 16:54:26 -07002163 // Shell command infrastructure: cancel a scheduled job
2164 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2165 boolean hasJobId, int jobId) {
2166 if (DEBUG) {
2167 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2168 }
2169
2170 int pkgUid = -1;
2171 try {
2172 IPackageManager pm = AppGlobals.getPackageManager();
2173 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2174 } catch (RemoteException e) { /* can't happen */ }
2175
2176 if (pkgUid < 0) {
2177 pw.println("Package " + pkgName + " not found.");
2178 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2179 }
2180
2181 if (!hasJobId) {
2182 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2183 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2184 pw.println("No matching jobs found.");
2185 }
2186 } else {
2187 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
2188 if (!cancelJob(pkgUid, jobId)) {
2189 pw.println("No matching job found.");
2190 }
2191 }
2192
2193 return 0;
2194 }
2195
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002196 void setMonitorBattery(boolean enabled) {
2197 synchronized (mLock) {
2198 if (mBatteryController != null) {
2199 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2200 }
2201 }
2202 }
2203
2204 int getBatterySeq() {
2205 synchronized (mLock) {
2206 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2207 }
2208 }
2209
2210 boolean getBatteryCharging() {
2211 synchronized (mLock) {
2212 return mBatteryController != null
2213 ? mBatteryController.getTracker().isOnStablePower() : false;
2214 }
2215 }
2216
2217 boolean getBatteryNotLow() {
2218 synchronized (mLock) {
2219 return mBatteryController != null
2220 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2221 }
2222 }
2223
Dianne Hackborn532ea262017-03-17 17:50:55 -07002224 int getStorageSeq() {
2225 synchronized (mLock) {
2226 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2227 }
2228 }
2229
2230 boolean getStorageNotLow() {
2231 synchronized (mLock) {
2232 return mStorageController != null
2233 ? mStorageController.getTracker().isStorageNotLow() : false;
2234 }
2235 }
2236
Dianne Hackborn6d068262017-05-16 13:14:37 -07002237 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2238 try {
2239 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2240 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2241 if (uid < 0) {
2242 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2243 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2244 }
2245
2246 synchronized (mLock) {
2247 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2248 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2249 if (js == null) {
2250 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2251 pw.print("/jid"); pw.print(jobId); pw.println(")");
2252 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2253 }
2254
2255 boolean printed = false;
2256 if (mPendingJobs.contains(js)) {
2257 pw.print("pending");
2258 printed = true;
2259 }
2260 if (isCurrentlyActiveLocked(js)) {
2261 if (printed) {
2262 pw.print(" ");
2263 }
2264 printed = true;
2265 pw.println("active");
2266 }
2267 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2268 if (printed) {
2269 pw.print(" ");
2270 }
2271 printed = true;
2272 pw.println("user-stopped");
2273 }
2274 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2275 if (printed) {
2276 pw.print(" ");
2277 }
2278 printed = true;
2279 pw.println("backing-up");
2280 }
2281 boolean componentPresent = false;
2282 try {
2283 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2284 js.getServiceComponent(),
2285 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2286 js.getUserId()) != null);
2287 } catch (RemoteException e) {
2288 }
2289 if (!componentPresent) {
2290 if (printed) {
2291 pw.print(" ");
2292 }
2293 printed = true;
2294 pw.println("no-component");
2295 }
2296 if (js.isReady()) {
2297 if (printed) {
2298 pw.print(" ");
2299 }
2300 printed = true;
2301 pw.println("ready");
2302 }
2303 if (!printed) {
2304 pw.print("waiting");
2305 }
2306 pw.println();
2307 }
2308 } catch (RemoteException e) {
2309 // can't happen
2310 }
2311 return 0;
2312 }
2313
Shreyas Basarge5db09082016-01-07 13:38:29 +00002314 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2315 StringBuilder s = new StringBuilder(initial + ": ");
2316 for (int i=0; i<map.length; i++) {
2317 s.append("(")
2318 .append(map[i] == null? -1: map[i].getJobId())
2319 .append(map[i] == null? -1: map[i].getUid())
2320 .append(")" );
2321 }
2322 return s.toString();
2323 }
2324
2325 private String printPendingQueue() {
2326 StringBuilder s = new StringBuilder("Pending queue: ");
2327 Iterator<JobStatus> it = mPendingJobs.iterator();
2328 while (it.hasNext()) {
2329 JobStatus js = it.next();
2330 s.append("(")
2331 .append(js.getJob().getId())
2332 .append(", ")
2333 .append(js.getUid())
2334 .append(") ");
2335 }
2336 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002337 }
Christopher Tate7060b042014-06-09 19:50:00 -07002338
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002339 static void dumpHelp(PrintWriter pw) {
2340 pw.println("Job Scheduler (jobscheduler) dump options:");
2341 pw.println(" [-h] [package] ...");
2342 pw.println(" -h: print this help");
2343 pw.println(" [package] is an optional package name to limit the output to.");
2344 }
2345
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002346 void dumpInternal(final PrintWriter pw, String[] args) {
2347 int filterUid = -1;
2348 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002349 int opti = 0;
2350 while (opti < args.length) {
2351 String arg = args[opti];
2352 if ("-h".equals(arg)) {
2353 dumpHelp(pw);
2354 return;
2355 } else if ("-a".equals(arg)) {
2356 // Ignore, we always dump all.
2357 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2358 pw.println("Unknown option: " + arg);
2359 return;
2360 } else {
2361 break;
2362 }
2363 opti++;
2364 }
2365 if (opti < args.length) {
2366 String pkg = args[opti];
2367 try {
2368 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002369 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002370 } catch (NameNotFoundException ignored) {
2371 pw.println("Invalid package: " + pkg);
2372 return;
2373 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002374 }
2375 }
2376
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002377 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07002378 final long nowElapsed = sElapsedRealtimeClock.millis();
2379 final long nowUptime = sUptimeMillisClock.millis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002380 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002381 mConstants.dump(pw);
2382 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002383 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002384 pw.print("Registered ");
2385 pw.print(mJobs.size());
2386 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002387 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002388 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2389 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002390 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002391 public int compare(JobStatus o1, JobStatus o2) {
2392 int uid1 = o1.getUid();
2393 int uid2 = o2.getUid();
2394 int id1 = o1.getJobId();
2395 int id2 = o2.getJobId();
2396 if (uid1 != uid2) {
2397 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002398 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002399 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08002400 }
2401 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002402 for (JobStatus job : jobs) {
2403 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2404 pw.println(job.toShortStringExceptUniqueId());
2405
2406 // Skip printing details if the caller requested a filter
2407 if (!job.shouldDump(filterUidFinal)) {
2408 continue;
2409 }
2410
Dianne Hackborn6d068262017-05-16 13:14:37 -07002411 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002412 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002413 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002414 pw.print(" (job=");
2415 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002416 pw.print(" user=");
2417 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002418 pw.print(" !pending=");
2419 pw.print(!mPendingJobs.contains(job));
2420 pw.print(" !active=");
2421 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002422 pw.print(" !backingup=");
2423 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002424 pw.print(" comp=");
2425 boolean componentPresent = false;
2426 try {
2427 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2428 job.getServiceComponent(),
2429 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2430 job.getUserId()) != null);
2431 } catch (RemoteException e) {
2432 }
2433 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002434 pw.println(")");
2435 }
Christopher Tate7060b042014-06-09 19:50:00 -07002436 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002437 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002438 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002439 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002440 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002441 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002442 }
2443 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002444 pw.println("Uid priority overrides:");
2445 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002446 int uid = mUidPriorityOverride.keyAt(i);
2447 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2448 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2449 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2450 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002451 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002452 if (mBackingUpUids.size() > 0) {
2453 pw.println();
2454 pw.println("Backing up uids:");
2455 boolean first = true;
2456 for (int i = 0; i < mBackingUpUids.size(); i++) {
2457 int uid = mBackingUpUids.keyAt(i);
2458 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2459 if (first) {
2460 pw.print(" ");
2461 first = false;
2462 } else {
2463 pw.print(", ");
2464 }
2465 pw.print(UserHandle.formatUid(uid));
2466 }
2467 }
2468 pw.println();
2469 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002470 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002471 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002472 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002473 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2474 pw.println();
2475 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002476 pw.println("Pending queue:");
2477 for (int i=0; i<mPendingJobs.size(); i++) {
2478 JobStatus job = mPendingJobs.get(i);
2479 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2480 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002481 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002482 int priority = evaluateJobPriorityLocked(job);
2483 if (priority != JobInfo.PRIORITY_DEFAULT) {
2484 pw.print(" Evaluated priority: "); pw.println(priority);
2485 }
2486 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002487 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002488 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002489 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002490 }
Christopher Tate7060b042014-06-09 19:50:00 -07002491 pw.println();
2492 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002493 for (int i=0; i<mActiveServices.size(); i++) {
2494 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002495 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002496 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002497 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002498 if (jsc.mStoppedReason != null) {
2499 pw.print("inactive since ");
2500 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2501 pw.print(", stopped because: ");
2502 pw.println(jsc.mStoppedReason);
2503 } else {
2504 pw.println("inactive");
2505 }
Christopher Tate7060b042014-06-09 19:50:00 -07002506 continue;
2507 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002508 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002509 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002510 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002511 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002512 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002513 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002514 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002515 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002516 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002517 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002518 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002519 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002520 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002521 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002522 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2523 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002524 }
2525 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002526 if (filterUid == -1) {
2527 pw.println();
2528 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2529 pw.print("mReportedActive="); pw.println(mReportedActive);
2530 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2531 }
Makoto Onukie7b02982017-08-24 14:23:36 -07002532 pw.println();
2533 pw.print("PersistStats: ");
2534 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07002535 }
2536 pw.println();
2537 }
2538}