blob: bc427f72cc7383e10ae16cfbc203a26ae53b25e9 [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;
Makoto Onuki15407842018-01-19 14:23:11 -080024import android.app.ActivityManagerInternal;
Christopher Tate5568f542014-06-18 13:53:31 -070025import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070026import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070027import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070028import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000029import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070030import android.app.job.JobScheduler;
31import android.app.job.JobService;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070032import android.app.job.JobWorkItem;
Amith Yamasaniafbccb72017-11-27 10:44:24 -080033import android.app.usage.UsageStatsManager;
Christopher Tatea732f012017-10-26 17:26:53 -070034import android.app.usage.UsageStatsManagerInternal;
35import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
Christopher Tate7060b042014-06-09 19:50:00 -070036import android.content.BroadcastReceiver;
37import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070038import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070039import android.content.Context;
40import android.content.Intent;
41import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070042import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070043import android.content.pm.PackageManager;
Christopher Tatea732f012017-10-26 17:26:53 -070044import android.content.pm.PackageManagerInternal;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060045import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070046import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070047import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070048import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070049import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070050import android.os.Binder;
51import android.os.Handler;
52import android.os.Looper;
53import android.os.Message;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070054import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070055import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080056import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070057import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070058import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070059import android.os.SystemClock;
60import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070061import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070062import android.provider.Settings;
63import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070064import android.util.Slog;
65import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080066import android.util.SparseIntArray;
67import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080068import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080069
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070070import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070071import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070072import com.android.internal.app.procstats.ProcessStats;
Christopher Tatea732f012017-10-26 17:26:53 -070073import com.android.internal.os.BackgroundThread;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070074import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060075import com.android.internal.util.DumpUtils;
Makoto Onuki15407842018-01-19 14:23:11 -080076import com.android.internal.util.Preconditions;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080077import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070078import com.android.server.FgThread;
Makoto Onuki15407842018-01-19 14:23:11 -080079import com.android.server.ForceAppStandbyTracker;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080080import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080081import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
82import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Christopher Tate2f36fd62016-02-18 18:36:08 -080083import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080084import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070085import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070086import com.android.server.job.controllers.BatteryController;
87import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080088import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070089import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070090import com.android.server.job.controllers.IdleController;
91import com.android.server.job.controllers.JobStatus;
92import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070093import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070094import com.android.server.job.controllers.TimeController;
95
Jeff Sharkey822cbd12016-02-25 11:09:55 -070096import libcore.util.EmptyArray;
97
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070098import java.io.FileDescriptor;
99import java.io.PrintWriter;
100import java.time.Clock;
101import java.util.ArrayList;
102import java.util.Arrays;
103import java.util.Collections;
104import java.util.Comparator;
105import java.util.Iterator;
106import java.util.List;
Makoto Onuki15407842018-01-19 14:23:11 -0800107import java.util.function.Predicate;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700108
Christopher Tate7060b042014-06-09 19:50:00 -0700109/**
110 * Responsible for taking jobs representing work to be performed by a client app, and determining
111 * based on the criteria specified when that job should be run against the client application's
112 * endpoint.
113 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
114 * about constraints, or the state of active jobs. It receives callbacks from the various
115 * controllers and completed jobs and operates accordingly.
116 *
117 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
118 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
119 * @hide
120 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800121public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700122 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800123 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700124 public static final boolean DEBUG = false;
Christopher Tatea732f012017-10-26 17:26:53 -0700125 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800126
Dianne Hackborn970510b2016-02-24 16:56:42 -0800127 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700128 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800129 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800130 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800131 /** The maximum number of jobs that we allow an unprivileged app to schedule */
132 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700133
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700134 @VisibleForTesting
135 public static Clock sSystemClock = Clock.systemUTC();
136 @VisibleForTesting
137 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
138 @VisibleForTesting
139 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800140
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800141 /** Global local for all job scheduler state. */
142 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700143 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700144 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700145 /** Tracking the standby bucket state of each app */
146 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700147 /** Tracking amount of time each package runs for. */
148 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700149
150 static final int MSG_JOB_EXPIRED = 0;
151 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700152 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000153 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700154
Christopher Tate7060b042014-06-09 19:50:00 -0700155 /**
156 * Track Services that have currently active or pending jobs. The index is provided by
157 * {@link JobStatus#getServiceToken()}
158 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700159 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700160 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700161 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800162 /** Need direct access to this for testing. */
163 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700164 /** Need direct access to this for testing. */
165 StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700166 /** Need directly for sending uid state changes */
167 private BackgroundJobsController mBackgroundJobsController;
Suprabh Shukla106203b2017-11-02 21:23:44 -0700168 private DeviceIdleJobsController mDeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700169 /**
170 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
171 * when ready to execute them.
172 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700173 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700174
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700175 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700176
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700177 final JobHandler mHandler;
178 final JobSchedulerStub mJobSchedulerStub;
179
Christopher Tatea732f012017-10-26 17:26:53 -0700180 PackageManagerInternal mLocalPM;
Makoto Onuki15407842018-01-19 14:23:11 -0800181 ActivityManagerInternal mActivityManagerInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700182 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800183 DeviceIdleController.LocalService mLocalDeviceIdleController;
Makoto Onuki15407842018-01-19 14:23:11 -0800184 final ForceAppStandbyTracker mForceAppStandbyTracker;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700185
186 /**
187 * Set to true once we are allowed to run third party apps.
188 */
189 boolean mReadyToRock;
190
Christopher Tate7060b042014-06-09 19:50:00 -0700191 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800192 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800193 */
194 boolean mReportedActive;
195
196 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800197 * Are we currently in device-wide standby parole?
198 */
199 volatile boolean mInParole;
200
201 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800202 * Current limit on the number of concurrent JobServiceContext entries we want to
203 * keep actively running a job.
204 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700205 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800206
207 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800208 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800209 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800210 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
211
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700212 /**
213 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
214 */
215 final SparseIntArray mBackingUpUids = new SparseIntArray();
216
Christopher Tatea732f012017-10-26 17:26:53 -0700217 /**
218 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
219 * next become runnable. Index into this array is by normalized bucket:
220 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
221 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
222 * and NEVER apps don't get them at all.
223 */
224 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
225 long mHeartbeat = 0;
226 long mLastHeartbeatTime = 0;
227
Dianne Hackborn970510b2016-02-24 16:56:42 -0800228 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
229
230 /**
231 * This array essentially stores the state of mActiveServices array.
232 * The ith index stores the job present on the ith JobServiceContext.
233 * We manipulate this array until we arrive at what jobs should be running on
234 * what JobServiceContext.
235 */
236 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
237 /**
238 * Indicates whether we need to act on this jobContext id
239 */
240 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
241 /**
242 * The uid whose jobs we would like to assign to a context.
243 */
244 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800245
246 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700247 * All times are in milliseconds. These constants are kept synchronized with the system
248 * global Settings. Any access to this class or its fields should be done while
249 * holding the JobSchedulerService.mLock lock.
250 */
251 private final class Constants extends ContentObserver {
252 // Key names stored in the settings value.
253 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
254 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800255 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700256 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700257 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
258 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
259 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
260 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
261 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
262 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
263 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
264 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
265 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
266 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700267 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
268 = "max_standard_reschedule_count";
269 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
270 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
271 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700272 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
273 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
274 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
275 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700276
277 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
278 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800279 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700280 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700281 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
282 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
283 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
284 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
285 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
286 private static final int DEFAULT_FG_JOB_COUNT = 4;
287 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
288 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700289 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700290 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700291 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
292 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
293 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
294 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700295 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000296 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
297 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700298 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700299
300 /**
301 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
302 * early.
303 */
304 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
305 /**
306 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
307 * things early.
308 */
309 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
310 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800311 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
312 * schedule things early.
313 */
314 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
315 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700316 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
317 * schedule things early.
318 */
319 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
320 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700321 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
322 * things early. 1 == Run connectivity jobs as soon as ready.
323 */
324 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
325 /**
326 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
327 * schedule things early.
328 */
329 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
330 /**
331 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
332 * running some work early. This (and thus the other min counts) is now set to 1, to
333 * prevent any batching at this level. Since we now do batching through doze, that is
334 * a much better mechanism.
335 */
336 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
337 /**
338 * This is the job execution factor that is considered to be heavy use of the system.
339 */
340 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
341 /**
342 * This is the job execution factor that is considered to be moderate use of the system.
343 */
344 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
345 /**
346 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
347 */
348 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
349 /**
350 * The maximum number of background jobs we allow when the system is in a normal
351 * memory state.
352 */
353 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
354 /**
355 * The maximum number of background jobs we allow when the system is in a moderate
356 * memory state.
357 */
358 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
359 /**
360 * The maximum number of background jobs we allow when the system is in a low
361 * memory state.
362 */
363 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
364 /**
365 * The maximum number of background jobs we allow when the system is in a critical
366 * memory state.
367 */
368 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700369 /**
370 * The maximum number of times we allow a job to have itself rescheduled before
371 * giving up on it, for standard jobs.
372 */
373 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
374 /**
375 * The maximum number of times we allow a job to have itself rescheduled before
376 * giving up on it, for jobs that are executing work.
377 */
378 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
379 /**
380 * The minimum backoff time to allow for linear backoff.
381 */
382 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
383 /**
384 * The minimum backoff time to allow for exponential backoff.
385 */
386 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700387 /**
388 * How often we recalculate runnability based on apps' standby bucket assignment.
389 * This should be prime relative to common time interval lengths such as a quarter-
390 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
391 */
392 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
393
394 /**
395 * Mapping: standby bucket -> number of heartbeats between each sweep of that
396 * bucket's jobs.
397 *
398 * Bucket assignments as recorded in the JobStatus objects are normalized to be
399 * indices into this array, rather than the raw constants used
400 * by AppIdleHistory.
401 */
402 final int[] STANDBY_BEATS = {
403 0,
404 DEFAULT_STANDBY_WORKING_BEATS,
405 DEFAULT_STANDBY_FREQUENT_BEATS,
406 DEFAULT_STANDBY_RARE_BEATS
407 };
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700408
409 private ContentResolver mResolver;
410 private final KeyValueListParser mParser = new KeyValueListParser(',');
411
412 public Constants(Handler handler) {
413 super(handler);
414 }
415
416 public void start(ContentResolver resolver) {
417 mResolver = resolver;
418 mResolver.registerContentObserver(Settings.Global.getUriFor(
419 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
420 updateConstants();
421 }
422
423 @Override
424 public void onChange(boolean selfChange, Uri uri) {
425 updateConstants();
426 }
427
428 private void updateConstants() {
429 synchronized (mLock) {
430 try {
431 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000432 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700433 } catch (IllegalArgumentException e) {
434 // Failed to parse the settings string, log this and move on
435 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000436 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700437 }
438
439 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
440 DEFAULT_MIN_IDLE_COUNT);
441 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
442 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800443 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
444 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700445 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
446 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700447 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
448 DEFAULT_MIN_CONNECTIVITY_COUNT);
449 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
450 DEFAULT_MIN_CONTENT_COUNT);
451 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
452 DEFAULT_MIN_READY_JOBS_COUNT);
453 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
454 DEFAULT_HEAVY_USE_FACTOR);
455 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
456 DEFAULT_MODERATE_USE_FACTOR);
457 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
458 DEFAULT_FG_JOB_COUNT);
459 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
460 DEFAULT_BG_NORMAL_JOB_COUNT);
461 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
462 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
463 }
464 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
465 DEFAULT_BG_MODERATE_JOB_COUNT);
466 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
467 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
468 }
469 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
470 DEFAULT_BG_LOW_JOB_COUNT);
471 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
472 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
473 }
474 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
475 DEFAULT_BG_CRITICAL_JOB_COUNT);
476 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
477 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
478 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700479 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
480 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
481 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
482 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800483 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700484 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800485 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700486 DEFAULT_MIN_EXP_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800487 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
Christopher Tatea732f012017-10-26 17:26:53 -0700488 DEFAULT_STANDBY_HEARTBEAT_TIME);
489 STANDBY_BEATS[1] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
490 DEFAULT_STANDBY_WORKING_BEATS);
491 STANDBY_BEATS[2] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
492 DEFAULT_STANDBY_FREQUENT_BEATS);
493 STANDBY_BEATS[3] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
494 DEFAULT_STANDBY_RARE_BEATS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700495 }
496 }
497
498 void dump(PrintWriter pw) {
499 pw.println(" Settings:");
500
501 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
502 pw.print(MIN_IDLE_COUNT); pw.println();
503
504 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
505 pw.print(MIN_CHARGING_COUNT); pw.println();
506
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800507 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
508 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
509
Dianne Hackborn532ea262017-03-17 17:50:55 -0700510 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
511 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
512
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700513 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
514 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
515
516 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
517 pw.print(MIN_CONTENT_COUNT); pw.println();
518
519 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
520 pw.print(MIN_READY_JOBS_COUNT); pw.println();
521
522 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
523 pw.print(HEAVY_USE_FACTOR); pw.println();
524
525 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
526 pw.print(MODERATE_USE_FACTOR); pw.println();
527
528 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
529 pw.print(FG_JOB_COUNT); pw.println();
530
531 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
532 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
533
534 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
535 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
536
537 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
538 pw.print(BG_LOW_JOB_COUNT); pw.println();
539
540 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
541 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700542
543 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
544 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
545
546 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
547 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
548
549 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
550 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
551
552 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
553 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Christopher Tatea732f012017-10-26 17:26:53 -0700554
555 pw.print(" "); pw.print(KEY_STANDBY_HEARTBEAT_TIME); pw.print("=");
556 pw.print(STANDBY_HEARTBEAT_TIME); pw.println();
557
558 pw.print(" standby_beats={");
559 pw.print(STANDBY_BEATS[0]);
560 for (int i = 1; i < STANDBY_BEATS.length; i++) {
561 pw.print(", ");
562 pw.print(STANDBY_BEATS[i]);
563 }
564 pw.println('}');
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700565 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800566
567 void dump(ProtoOutputStream proto, long fieldId) {
568 final long token = proto.start(fieldId);
569
570 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
571 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
572 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
573 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
574 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
575 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
576 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
577 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
578 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
579 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
580 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
581 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
582 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
583 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
584 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
585 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
586 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
587 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
588 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
589
590 for (int period : STANDBY_BEATS) {
591 proto.write(ConstantsProto.STANDBY_BEATS, period);
592 }
593
594 proto.end(token);
595 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700596 }
597
598 final Constants mConstants;
599
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700600 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
601 if (o1.enqueueTime < o2.enqueueTime) {
602 return -1;
603 }
604 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
605 };
606
607 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
608 int where = Collections.binarySearch(array, newItem, comparator);
609 if (where < 0) {
610 where = ~where;
611 }
612 array.add(where, newItem);
613 }
614
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700615 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700616 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
617 * still clean up. On reinstall the package will have a new uid.
618 */
619 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
620 @Override
621 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700622 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700623 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700624 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700625 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700626 final String pkgName = getPackageName(intent);
627 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
628
Christopher Tateee7805b2016-07-15 16:56:56 -0700629 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700630 // Purge the app's jobs if the whole package was just disabled. When this is
631 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700632 if (pkgName != null && pkgUid != -1) {
633 final String[] changedComponents = intent.getStringArrayExtra(
634 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
635 if (changedComponents != null) {
636 for (String component : changedComponents) {
637 if (component.equals(pkgName)) {
638 if (DEBUG) {
639 Slog.d(TAG, "Package state change: " + pkgName);
640 }
641 try {
642 final int userId = UserHandle.getUserId(pkgUid);
643 IPackageManager pm = AppGlobals.getPackageManager();
644 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
645 if (state == COMPONENT_ENABLED_STATE_DISABLED
646 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
647 if (DEBUG) {
648 Slog.d(TAG, "Removing jobs for package " + pkgName
649 + " in user " + userId);
650 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700651 cancelJobsForPackageAndUid(pkgName, pkgUid,
652 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700653 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700654 } catch (RemoteException|IllegalArgumentException e) {
655 /*
656 * IllegalArgumentException means that the package doesn't exist.
657 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
658 * behind outright uninstall, so by the time we try to act it's gone.
659 * We don't need to act on this PACKAGE_CHANGED when this happens;
660 * we'll get a PACKAGE_REMOVED later and clean up then.
661 *
662 * RemoteException can't actually happen; the package manager is
663 * running in this same process.
664 */
665 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700666 break;
667 }
668 }
669 }
670 } else {
671 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
672 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700673 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700674 // If this is an outright uninstall rather than the first half of an
675 // app update sequence, cancel the jobs associated with the app.
676 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
677 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
678 if (DEBUG) {
679 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
680 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700681 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700682 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700683 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700684 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
685 if (DEBUG) {
686 Slog.d(TAG, "Removing jobs for user: " + userId);
687 }
688 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700689 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
690 // Has this package scheduled any jobs, such that we will take action
691 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700692 if (pkgUid != -1) {
693 List<JobStatus> jobsForUid;
694 synchronized (mLock) {
695 jobsForUid = mJobs.getJobsByUid(pkgUid);
696 }
697 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
698 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
699 if (DEBUG) {
700 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
701 + pkgUid + " has jobs");
702 }
703 setResultCode(Activity.RESULT_OK);
704 break;
705 }
706 }
707 }
708 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
709 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700710 if (pkgUid != -1) {
711 if (DEBUG) {
712 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
713 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700714 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700715 }
Christopher Tate7060b042014-06-09 19:50:00 -0700716 }
717 }
718 };
719
Christopher Tateb5c07882016-05-26 17:11:09 -0700720 private String getPackageName(Intent intent) {
721 Uri uri = intent.getData();
722 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
723 return pkg;
724 }
725
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700726 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700727 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800728 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700729 }
730
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700731 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800732 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800733 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700734 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800735 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700736 synchronized (mLock) {
737 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
738 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700739 }
740
741 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla106203b2017-11-02 21:23:44 -0700742 synchronized (mLock) {
743 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
744 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700745 }
746
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700747 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800748 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700749 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800750 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700751 synchronized (mLock) {
752 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
753 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700754 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700755
756 @Override public void onUidCachedChanged(int uid, boolean cached) {
757 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700758 };
759
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800760 public Object getLock() {
761 return mLock;
762 }
763
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700764 public JobStore getJobStore() {
765 return mJobs;
766 }
767
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700768 @Override
769 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700770 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
771 // Let's kick any outstanding jobs for this user.
772 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
773 }
774
775 @Override
776 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700777 // Let's kick any outstanding jobs for this user.
778 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
779 }
780
781 @Override
782 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700783 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700784 }
785
Makoto Onuki15407842018-01-19 14:23:11 -0800786 /**
787 * Return whether an UID is in the foreground or not.
788 */
789 private boolean isUidInForeground(int uid) {
790 synchronized (mLock) {
791 if (mUidPriorityOverride.get(uid, 0) > 0) {
792 return true;
793 }
794 }
795 // Note UID observer may not be called in time, so we always check with the AM.
796 return mActivityManagerInternal.getUidProcessState(uid)
797 <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
798 }
799
800 private final Predicate<Integer> mIsUidInForegroundPredicate = this::isUidInForeground;
801
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700802 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
803 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700804 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800805 if (ActivityManager.getService().isAppStartModeDisabled(uId,
806 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700807 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
808 + " -- package not allowed to start");
809 return JobScheduler.RESULT_FAILURE;
810 }
811 } catch (RemoteException e) {
812 }
Christopher Tatea732f012017-10-26 17:26:53 -0700813
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800814 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700815 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
816
817 if (work != null && toCancel != null) {
818 // Fast path: we are adding work to an existing job, and the JobInfo is not
819 // changing. We can just directly enqueue this work in to the job.
820 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -0800821
Dianne Hackborn342e6032017-04-13 18:04:31 -0700822 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Makoto Onuki15407842018-01-19 14:23:11 -0800823
824 // If any of work item is enqueued when the source is in the foreground,
825 // exempt the entire job.
826 toCancel.maybeAddForegroundExemption(mIsUidInForegroundPredicate);
827
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700828 return JobScheduler.RESULT_SUCCESS;
829 }
830 }
831
832 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -0800833
834 // Give exemption if the source is in the foreground just now.
835 // Note if it's a sync job, this method is called on the handler so it's not exactly
836 // the state when requestSync() was called, but that should be fine because of the
837 // 1 minute foreground grace period.
838 jobStatus.maybeAddForegroundExemption(mIsUidInForegroundPredicate);
839
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700840 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800841 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800842 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800843 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
844 Slog.w(TAG, "Too many jobs for uid " + uId);
845 throw new IllegalStateException("Apps may not schedule more than "
846 + MAX_JOBS_PER_APP + " distinct jobs");
847 }
848 }
849
Dianne Hackborna47223f2017-03-30 13:49:13 -0700850 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700851 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700852
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700853 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700854 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700855 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700856 if (work != null) {
857 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700858 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700859 }
860 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700861
862 // If the job is immediately ready to run, then we can just immediately
863 // put it in the pending list and try to schedule it. This is especially
864 // important for jobs with a 0 deadline constraint, since they will happen a fair
865 // amount, we want to handle them as quickly as possible, and semantically we want to
866 // make sure we have started holding the wake lock for the job before returning to
867 // the caller.
868 // If the job is not yet ready to run, there is nothing more to do -- we are
869 // now just waiting for one of its controllers to change state and schedule
870 // the job appropriately.
871 if (isReadyToBeExecutedLocked(jobStatus)) {
872 // This is a new job, we can just immediately put it on the pending
873 // list and try to run it.
874 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700875 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700876 maybeRunPendingJobsLocked();
877 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800878 }
Christopher Tate7060b042014-06-09 19:50:00 -0700879 return JobScheduler.RESULT_SUCCESS;
880 }
881
882 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800883 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800884 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
885 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
886 for (int i = jobs.size() - 1; i >= 0; i--) {
887 JobStatus job = jobs.get(i);
888 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700889 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800890 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700891 }
Christopher Tate7060b042014-06-09 19:50:00 -0700892 }
893
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600894 public JobInfo getPendingJob(int uid, int jobId) {
895 synchronized (mLock) {
896 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
897 for (int i = jobs.size() - 1; i >= 0; i--) {
898 JobStatus job = jobs.get(i);
899 if (job.getJobId() == jobId) {
900 return job.getJob();
901 }
902 }
903 return null;
904 }
905 }
906
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700907 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800908 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700909 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
910 for (int i=0; i<jobsForUser.size(); i++) {
911 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700912 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700913 }
Christopher Tate7060b042014-06-09 19:50:00 -0700914 }
915 }
916
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700917 private void cancelJobsForNonExistentUsers() {
918 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
919 synchronized (mLock) {
920 mJobs.removeJobsOfNonUsers(umi.getUserIds());
921 }
922 }
923
Makoto Onukie7b96182017-08-30 14:53:16 -0700924 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
925 if ("android".equals(pkgName)) {
926 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
927 return;
928 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700929 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700930 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
931 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
932 final JobStatus job = jobsForUid.get(i);
933 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700934 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700935 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700936 }
937 }
938 }
939
Christopher Tate7060b042014-06-09 19:50:00 -0700940 /**
941 * Entry point from client to cancel all jobs originating from their uid.
942 * This will remove the job from the master list, and cancel the job if it was staged for
943 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700944 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800945 *
Christopher Tate7060b042014-06-09 19:50:00 -0700946 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700947 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700948 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700949 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700950 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700951 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700952
953 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800954 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700955 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
956 for (int i=0; i<jobsForUid.size(); i++) {
957 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700958 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700959 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700960 }
Christopher Tate7060b042014-06-09 19:50:00 -0700961 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700962 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700963 }
964
965 /**
966 * Entry point from client to cancel the job corresponding to the jobId provided.
967 * This will remove the job from the master list, and cancel the job if it was staged for
968 * execution or being executed.
969 * @param uid Uid of the calling client.
970 * @param jobId Id of the job, provided at schedule-time.
971 */
Makoto Onukid2bfec62018-01-12 13:58:01 -0800972 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -0700973 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800974 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700975 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700976 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -0800977 cancelJobImplLocked(toCancel, null,
978 "cancel() called by app, callingUid=" + callingUid
979 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700980 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700981 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -0700982 }
983 }
984
Dianne Hackborn729a3282017-06-09 16:06:01 -0700985 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700986 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
987 cancelled.unprepareLocked(ActivityManager.getService());
988 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
989 // Remove from pending queue.
990 if (mPendingJobs.remove(cancelled)) {
991 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700992 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700993 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700994 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700995 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700996 }
997
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800998 void updateUidState(int uid, int procState) {
999 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001000 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1001 // Only use this if we are exactly the top app. All others can live
1002 // with just the foreground priority. This means that persistent processes
1003 // can never be the top app priority... that is fine.
1004 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001005 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001006 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001007 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001008 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001009 }
1010 }
1011 }
1012
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001013 @Override
1014 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001015 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001016 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001017 // When becoming idle, make sure no jobs are actively running,
1018 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001019 for (int i=0; i<mActiveServices.size(); i++) {
1020 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001021 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001022 if (executing != null
1023 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001024 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1025 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001026 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001027 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001028 } else {
1029 // When coming out of idle, allow thing to start back up.
1030 if (mReadyToRock) {
1031 if (mLocalDeviceIdleController != null) {
1032 if (!mReportedActive) {
1033 mReportedActive = true;
1034 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001035 }
1036 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001037 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001038 }
1039 }
1040 }
1041 }
1042
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001043 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001044 // active is true if pending queue contains jobs OR some job is running.
1045 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001046 if (mPendingJobs.size() <= 0) {
1047 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001048 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001049 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001050 if (job != null
1051 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
1052 && !job.dozeWhitelisted) {
1053 // We will report active if we have a job running and it is not an exception
1054 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001055 active = true;
1056 break;
1057 }
1058 }
1059 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001060
1061 if (mReportedActive != active) {
1062 mReportedActive = active;
1063 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001064 mLocalDeviceIdleController.setJobsActive(active);
1065 }
1066 }
1067 }
1068
Christopher Tate7060b042014-06-09 19:50:00 -07001069 /**
1070 * Initializes the system service.
1071 * <p>
1072 * Subclasses must define a single argument constructor that accepts the context
1073 * and passes it to super.
1074 * </p>
1075 *
1076 * @param context The system server context.
1077 */
1078 public JobSchedulerService(Context context) {
1079 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001080
1081 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Makoto Onuki15407842018-01-19 14:23:11 -08001082 mActivityManagerInternal = Preconditions.checkNotNull(
1083 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001084
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001085 mHandler = new JobHandler(context.getMainLooper());
1086 mConstants = new Constants(mHandler);
1087 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001088
1089 // Set up the app standby bucketing tracker
1090 UsageStatsManagerInternal usageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1091 mStandbyTracker = new StandbyTracker(usageStats);
1092 usageStats.addAppIdleStateChangeListener(mStandbyTracker);
1093
1094 // The job store needs to call back
1095 publishLocalService(JobSchedulerInternal.class, new LocalService());
1096
1097 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001098 mJobs = JobStore.initAndGet(this);
1099
Christopher Tate7060b042014-06-09 19:50:00 -07001100 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001101 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -07001102 mControllers.add(ConnectivityController.get(this));
1103 mControllers.add(TimeController.get(this));
1104 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001105 mBatteryController = BatteryController.get(this);
1106 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001107 mStorageController = StorageController.get(this);
1108 mControllers.add(mStorageController);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001109 mControllers.add(BackgroundJobsController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -08001110 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001111 mControllers.add(ContentObserverController.get(this));
Suprabh Shukla106203b2017-11-02 21:23:44 -07001112 mDeviceIdleJobsController = DeviceIdleJobsController.get(this);
1113 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001114
Makoto Onuki15407842018-01-19 14:23:11 -08001115 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
1116
Christopher Tate616541d2017-07-26 14:27:38 -07001117 // If the job store determined that it can't yet reschedule persisted jobs,
1118 // we need to start watching the clock.
1119 if (!mJobs.jobTimesInflatedValid()) {
1120 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1121 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1122 }
Christopher Tate7060b042014-06-09 19:50:00 -07001123 }
1124
Christopher Tate616541d2017-07-26 14:27:38 -07001125 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1126 @Override
1127 public void onReceive(Context context, Intent intent) {
1128 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1129 // When we reach clock sanity, recalculate the temporal windows
1130 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001131 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001132 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1133
1134 // We've done our job now, so stop watching the time.
1135 context.unregisterReceiver(this);
1136
1137 // And kick off the work to update the affected jobs, using a secondary
1138 // thread instead of chugging away here on the main looper thread.
1139 FgThread.getHandler().post(mJobTimeUpdater);
1140 }
1141 }
1142 }
1143 };
1144
1145 private final Runnable mJobTimeUpdater = () -> {
1146 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1147 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1148 synchronized (mLock) {
1149 // Note: we intentionally both look up the existing affected jobs and replace them
1150 // with recalculated ones inside the same lock lifetime.
1151 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1152
1153 // Now, at each position [i], we have both the existing JobStatus
1154 // and the one that replaces it.
1155 final int N = toAdd.size();
1156 for (int i = 0; i < N; i++) {
1157 final JobStatus oldJob = toRemove.get(i);
1158 final JobStatus newJob = toAdd.get(i);
1159 if (DEBUG) {
1160 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1161 }
1162 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1163 }
1164 }
1165 };
1166
Christopher Tate7060b042014-06-09 19:50:00 -07001167 @Override
1168 public void onStart() {
1169 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1170 }
1171
1172 @Override
1173 public void onBootPhase(int phase) {
1174 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001175 mConstants.start(getContext().getContentResolver());
Makoto Onuki15407842018-01-19 14:23:11 -08001176
1177 mForceAppStandbyTracker.start();
1178
Shreyas Basarge5db09082016-01-07 13:38:29 +00001179 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001180 final IntentFilter filter = new IntentFilter();
1181 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1182 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001183 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1184 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001185 filter.addDataScheme("package");
1186 getContext().registerReceiverAsUser(
1187 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1188 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1189 getContext().registerReceiverAsUser(
1190 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001191 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001192 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001193 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001194 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1195 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001196 } catch (RemoteException e) {
1197 // ignored; both services live in system_server
1198 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001199 // Remove any jobs that are not associated with any of the current users.
1200 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001201 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001202 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001203 // Let's go!
1204 mReadyToRock = true;
1205 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1206 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001207 mLocalDeviceIdleController
1208 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001209 // Create the "runners".
1210 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1211 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001212 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001213 getContext().getMainLooper()));
1214 }
1215 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001216 mJobs.forEachJob(new JobStatusFunctor() {
1217 @Override
1218 public void process(JobStatus job) {
1219 for (int controller = 0; controller < mControllers.size(); controller++) {
1220 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001221 sc.maybeStartTrackingJobLocked(job, null);
1222 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001223 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001224 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001225 // GO GO GO!
1226 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1227 }
Christopher Tate7060b042014-06-09 19:50:00 -07001228 }
1229 }
1230
1231 /**
1232 * Called when we have a job status object that we need to insert in our
1233 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1234 * about.
1235 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001236 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1237 if (!jobStatus.isPreparedLocked()) {
1238 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1239 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001240 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001241 final boolean update = mJobs.add(jobStatus);
1242 if (mReadyToRock) {
1243 for (int i = 0; i < mControllers.size(); i++) {
1244 StateController controller = mControllers.get(i);
1245 if (update) {
1246 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001247 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001248 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001249 }
Christopher Tate7060b042014-06-09 19:50:00 -07001250 }
1251 }
1252
1253 /**
1254 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1255 * object removed.
1256 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001257 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001258 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001259 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001260 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001261
1262 // Remove from store as well as controllers.
1263 final boolean removed = mJobs.remove(jobStatus, writeBack);
1264 if (removed && mReadyToRock) {
1265 for (int i=0; i<mControllers.size(); i++) {
1266 StateController controller = mControllers.get(i);
1267 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001268 }
1269 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001270 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001271 }
1272
Dianne Hackborn729a3282017-06-09 16:06:01 -07001273 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001274 for (int i=0; i<mActiveServices.size(); i++) {
1275 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001276 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001277 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001278 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001279 return true;
1280 }
1281 }
1282 return false;
1283 }
1284
1285 /**
1286 * @param job JobStatus we are querying against.
1287 * @return Whether or not the job represented by the status object is currently being run or
1288 * is pending.
1289 */
1290 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001291 for (int i=0; i<mActiveServices.size(); i++) {
1292 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001293 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001294 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1295 return true;
1296 }
1297 }
1298 return false;
1299 }
1300
Dianne Hackborn807de782016-04-07 17:54:41 -07001301 void noteJobsPending(List<JobStatus> jobs) {
1302 for (int i = jobs.size() - 1; i >= 0; i--) {
1303 JobStatus job = jobs.get(i);
1304 mJobPackageTracker.notePending(job);
1305 }
1306 }
1307
1308 void noteJobsNonpending(List<JobStatus> jobs) {
1309 for (int i = jobs.size() - 1; i >= 0; i--) {
1310 JobStatus job = jobs.get(i);
1311 mJobPackageTracker.noteNonpending(job);
1312 }
1313 }
1314
Christopher Tate7060b042014-06-09 19:50:00 -07001315 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001316 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1317 * specify an override deadline on a failed job (the failed job will run even though it's not
1318 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1319 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1320 *
Christopher Tate7060b042014-06-09 19:50:00 -07001321 * @param failureToReschedule Provided job status that we will reschedule.
1322 * @return A newly instantiated JobStatus with the same constraints as the last job except
1323 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001324 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001325 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001326 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001327 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001328 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001329 final JobInfo job = failureToReschedule.getJob();
1330
1331 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001332 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1333 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001334
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001335 if (failureToReschedule.hasWorkLocked()) {
1336 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1337 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1338 + backoffAttempts + " > work limit "
1339 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1340 return null;
1341 }
1342 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1343 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1344 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1345 return null;
1346 }
1347
Christopher Tate7060b042014-06-09 19:50:00 -07001348 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001349 case JobInfo.BACKOFF_POLICY_LINEAR: {
1350 long backoff = initialBackoffMillis;
1351 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1352 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1353 }
1354 delayMillis = backoff * backoffAttempts;
1355 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001356 default:
1357 if (DEBUG) {
1358 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1359 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001360 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1361 long backoff = initialBackoffMillis;
1362 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1363 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1364 }
1365 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1366 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001367 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001368 delayMillis =
1369 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001370 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1371 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001372 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001373 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001374 for (int ic=0; ic<mControllers.size(); ic++) {
1375 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001376 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001377 }
1378 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001379 }
1380
1381 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001382 * Called after a periodic has executed so we can reschedule it. We take the last execution
1383 * time of the job to be the time of completion (i.e. the time at which this function is
1384 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001385 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001386 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1387 * to underscheduling at least, rather than if we had taken the last execution time to be the
1388 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001389 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1390 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001391 * @return A new job representing the execution criteria for this instantiation of the
1392 * recurring job.
1393 */
1394 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001395 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001396 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001397 long runEarly = 0L;
1398
1399 // If this periodic was rescheduled it won't have a deadline.
1400 if (periodicToReschedule.hasDeadlineConstraint()) {
1401 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1402 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001403 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001404 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001405 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1406 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001407
1408 if (DEBUG) {
1409 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1410 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1411 }
Christopher Tatea732f012017-10-26 17:26:53 -07001412 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1413 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1414 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001415 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001416 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001417 }
1418
1419 // JobCompletedListener implementations.
1420
1421 /**
1422 * A job just finished executing. We fetch the
1423 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1424 * whether we want to reschedule we readd it to the controllers.
1425 * @param jobStatus Completed job.
1426 * @param needsReschedule Whether the implementing class should reschedule this job.
1427 */
1428 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001429 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001430 if (DEBUG) {
1431 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1432 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001433
1434 // If the job wants to be rescheduled, we first need to make the next upcoming
1435 // job so we can transfer any appropriate state over from the previous job when
1436 // we stop it.
1437 final JobStatus rescheduledJob = needsReschedule
1438 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1439
Shreyas Basarge73f10252016-02-11 17:06:13 +00001440 // Do not write back immediately if this is a periodic job. The job may get lost if system
1441 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001442 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001443 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001444 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001445 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001446 // We still want to check for jobs to execute, because this job may have
1447 // scheduled a new job under the same job id, and now we can run it.
1448 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001449 return;
1450 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001451
1452 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001453 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001454 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001455 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001456 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001457 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001458 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001459 } else if (jobStatus.getJob().isPeriodic()) {
1460 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001461 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001462 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001463 } catch (SecurityException e) {
1464 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1465 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001466 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001467 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001468 jobStatus.unprepareLocked(ActivityManager.getService());
1469 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001470 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001471 }
1472
1473 // StateChangedListener implementations.
1474
1475 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001476 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1477 * some controller's state has changed, so as to run through the list of jobs and start/stop
1478 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001479 */
1480 @Override
1481 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001482 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001483 }
1484
1485 @Override
1486 public void onRunJobNow(JobStatus jobStatus) {
1487 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1488 }
1489
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001490 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001491
1492 public JobHandler(Looper looper) {
1493 super(looper);
1494 }
1495
1496 @Override
1497 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001498 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001499 if (!mReadyToRock) {
1500 return;
1501 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001502 switch (message.what) {
1503 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001504 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001505 // runNow can be null, which is a controller's way of indicating that its
1506 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001507 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001508 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001509 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001510 } else {
1511 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001512 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001513 } break;
1514 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001515 if (mReportedActive) {
1516 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001517 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001518 } else {
1519 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001520 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001521 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001522 break;
1523 case MSG_CHECK_JOB_GREEDY:
1524 queueReadyJobsForExecutionLocked();
1525 break;
1526 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001527 cancelJobImplLocked((JobStatus) message.obj, null,
1528 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001529 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001530 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001531 maybeRunPendingJobsLocked();
1532 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1533 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001534 }
1535 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001536 }
Christopher Tate7060b042014-06-09 19:50:00 -07001537
Dianne Hackborn6d068262017-05-16 13:14:37 -07001538 private void stopNonReadyActiveJobsLocked() {
1539 for (int i=0; i<mActiveServices.size(); i++) {
1540 JobServiceContext serviceContext = mActiveServices.get(i);
1541 final JobStatus running = serviceContext.getRunningJobLocked();
1542 if (running != null && !running.isReady()) {
1543 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001544 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1545 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001546 }
1547 }
1548 }
1549
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001550 /**
1551 * Run through list of jobs and execute all possible - at least one is expired so we do
1552 * as many as we can.
1553 */
1554 private void queueReadyJobsForExecutionLocked() {
1555 if (DEBUG) {
1556 Slog.d(TAG, "queuing all ready jobs for execution:");
1557 }
1558 noteJobsNonpending(mPendingJobs);
1559 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001560 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001561 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001562 mJobs.forEachJob(mReadyQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001563 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001564 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001565
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001566 if (DEBUG) {
1567 final int queuedJobs = mPendingJobs.size();
1568 if (queuedJobs == 0) {
1569 Slog.d(TAG, "No jobs pending.");
1570 } else {
1571 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001572 }
1573 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001574 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001575
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001576 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1577 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001578
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001579 @Override
1580 public void process(JobStatus job) {
1581 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001582 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001583 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001584 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001585 if (newReadyJobs == null) {
1586 newReadyJobs = new ArrayList<JobStatus>();
1587 }
1588 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001589 }
1590 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001591
1592 public void postProcess() {
1593 if (newReadyJobs != null) {
1594 noteJobsPending(newReadyJobs);
1595 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001596 if (mPendingJobs.size() > 1) {
1597 mPendingJobs.sort(mEnqueueTimeComparator);
1598 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001599 }
1600 newReadyJobs = null;
1601 }
1602 }
1603 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1604
1605 /**
1606 * The state of at least one job has changed. Here is where we could enforce various
1607 * policies on when we want to execute jobs.
1608 * Right now the policy is such:
1609 * If >1 of the ready jobs is idle mode we send all of them off
1610 * if more than 2 network connectivity jobs are ready we send them all off.
1611 * If more than 4 jobs total are ready we send them all off.
1612 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1613 */
1614 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1615 int chargingCount;
1616 int batteryNotLowCount;
1617 int storageNotLowCount;
1618 int idleCount;
1619 int backoffCount;
1620 int connectivityCount;
1621 int contentCount;
1622 List<JobStatus> runnableJobs;
1623
1624 public MaybeReadyJobQueueFunctor() {
1625 reset();
1626 }
1627
1628 // Functor method invoked for each job via JobStore.forEachJob()
1629 @Override
1630 public void process(JobStatus job) {
1631 if (isReadyToBeExecutedLocked(job)) {
1632 try {
1633 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1634 job.getJob().getService().getPackageName())) {
1635 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1636 + job.getJob().toString() + " -- package not allowed to start");
1637 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1638 return;
1639 }
1640 } catch (RemoteException e) {
1641 }
1642 if (job.getNumFailures() > 0) {
1643 backoffCount++;
1644 }
1645 if (job.hasIdleConstraint()) {
1646 idleCount++;
1647 }
1648 if (job.hasConnectivityConstraint()) {
1649 connectivityCount++;
1650 }
1651 if (job.hasChargingConstraint()) {
1652 chargingCount++;
1653 }
1654 if (job.hasBatteryNotLowConstraint()) {
1655 batteryNotLowCount++;
1656 }
1657 if (job.hasStorageNotLowConstraint()) {
1658 storageNotLowCount++;
1659 }
1660 if (job.hasContentTriggerConstraint()) {
1661 contentCount++;
1662 }
1663 if (runnableJobs == null) {
1664 runnableJobs = new ArrayList<>();
1665 }
1666 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001667 }
1668 }
1669
1670 public void postProcess() {
1671 if (backoffCount > 0 ||
1672 idleCount >= mConstants.MIN_IDLE_COUNT ||
1673 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1674 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1675 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1676 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1677 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1678 (runnableJobs != null
1679 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1680 if (DEBUG) {
1681 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1682 }
1683 noteJobsPending(runnableJobs);
1684 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001685 if (mPendingJobs.size() > 1) {
1686 mPendingJobs.sort(mEnqueueTimeComparator);
1687 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001688 } else {
1689 if (DEBUG) {
1690 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1691 }
1692 }
1693
1694 // Be ready for next time
1695 reset();
1696 }
1697
1698 private void reset() {
1699 chargingCount = 0;
1700 idleCount = 0;
1701 backoffCount = 0;
1702 connectivityCount = 0;
1703 batteryNotLowCount = 0;
1704 storageNotLowCount = 0;
1705 contentCount = 0;
1706 runnableJobs = null;
1707 }
1708 }
1709 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1710
1711 private void maybeQueueReadyJobsForExecutionLocked() {
1712 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1713
1714 noteJobsNonpending(mPendingJobs);
1715 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001716 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001717 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001718 mJobs.forEachJob(mMaybeQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001719 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001720 mMaybeQueueFunctor.postProcess();
1721 }
1722
Christopher Tatea732f012017-10-26 17:26:53 -07001723 private boolean updateStandbyHeartbeatLocked() {
1724 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1725 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1726 if (beatsElapsed > 0) {
1727 mHeartbeat += beatsElapsed;
1728 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1729 if (DEBUG_STANDBY) {
1730 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed + " to " + mHeartbeat);
1731 }
1732 return true;
1733 }
1734 return false;
1735 }
1736
1737 private void updateNextStandbyHeartbeatsLocked() {
1738 // don't update ACTIVE or NEVER bucket milestones
1739 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
1740 while (mHeartbeat >= mNextBucketHeartbeat[i]) {
1741 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1742 }
1743 if (DEBUG_STANDBY) {
1744 Slog.v(TAG, " Bucket " + i + " next heartbeat " + mNextBucketHeartbeat[i]);
1745 }
1746 }
1747 }
1748
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001749 /**
1750 * Criteria for moving a job into the pending queue:
1751 * - It's ready.
1752 * - It's not pending.
1753 * - It's not already running on a JSC.
1754 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001755 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001756 * - The component is enabled and runnable.
1757 */
1758 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001759 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001760
1761 if (DEBUG) {
1762 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1763 + " ready=" + jobReady);
1764 }
1765
1766 // This is a condition that is very likely to be false (most jobs that are
1767 // scheduled are sitting there, not ready yet) and very cheap to check (just
1768 // a few conditions on data in JobStatus).
1769 if (!jobReady) {
1770 return false;
1771 }
1772
1773 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001774
1775 final int userId = job.getUserId();
1776 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1777
1778 if (DEBUG) {
1779 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001780 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001781 }
1782
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001783 // These are also fairly cheap to check, though they typically will not
1784 // be conditions we fail.
1785 if (!jobExists || !userStarted) {
1786 return false;
1787 }
1788
1789 final boolean jobPending = mPendingJobs.contains(job);
1790 final boolean jobActive = isCurrentlyActiveLocked(job);
1791
1792 if (DEBUG) {
1793 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1794 + " pending=" + jobPending + " active=" + jobActive);
1795 }
1796
1797 // These can be a little more expensive (especially jobActive, since we need to
1798 // go through the array of all potentially active jobs), so we are doing them
1799 // later... but still before checking with the package manager!
1800 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001801 return false;
1802 }
1803
Christopher Tatea732f012017-10-26 17:26:53 -07001804 // If the app is in a non-active standby bucket, make sure we've waited
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001805 // an appropriate amount of time since the last invocation. During device-
1806 // wide parole, standby bucketing is ignored.
1807 if (!mInParole) {
1808 final int bucket = job.getStandbyBucket();
1809 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
1810 // Only skip this job if it's still waiting for the end of its (initial) nominal
1811 // bucket interval. Once it's waited that long, we let it go ahead and clear.
1812 // The final (NEVER) bucket is special; we never age those apps' jobs into
1813 // runnability.
1814 if (bucket >= mConstants.STANDBY_BEATS.length
1815 || (mHeartbeat < job.getBaseHeartbeat() + mConstants.STANDBY_BEATS[bucket])) {
1816 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
1817 if (job.getWhenStandbyDeferred() == 0) {
1818 if (DEBUG_STANDBY) {
1819 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
1820 + mNextBucketHeartbeat[job.getStandbyBucket()] + " for " + job);
1821 }
1822 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tate0c4d7682017-12-06 15:10:22 -08001823 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001824 return false;
1825 } else {
1826 if (DEBUG_STANDBY) {
1827 Slog.v(TAG, "Bucket deferred job aged into runnability at "
1828 + mHeartbeat + " : " + job);
1829 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08001830 }
Christopher Tatea732f012017-10-26 17:26:53 -07001831 }
Christopher Tatea732f012017-10-26 17:26:53 -07001832 }
1833
1834 // The expensive check last: validate that the defined package+service is
1835 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001836 final boolean componentPresent;
1837 try {
1838 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1839 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1840 userId) != null);
1841 } catch (RemoteException e) {
1842 throw e.rethrowAsRuntimeException();
1843 }
1844
1845 if (DEBUG) {
1846 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1847 + " componentPresent=" + componentPresent);
1848 }
1849
1850 // Everything else checked out so far, so this is the final yes/no check
1851 return componentPresent;
1852 }
1853
1854 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001855 * Reconcile jobs in the pending queue against available execution contexts.
1856 * A controller can force a job into the pending queue even if it's already running, but
1857 * here is where we decide whether to actually execute it.
1858 */
1859 private void maybeRunPendingJobsLocked() {
1860 if (DEBUG) {
1861 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1862 }
1863 assignJobsToContextsLocked();
1864 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001865 }
1866
Dianne Hackborn807de782016-04-07 17:54:41 -07001867 private int adjustJobPriority(int curPriority, JobStatus job) {
1868 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1869 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001870 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001871 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001872 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001873 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1874 }
1875 }
1876 return curPriority;
1877 }
1878
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001879 private int evaluateJobPriorityLocked(JobStatus job) {
1880 int priority = job.getPriority();
1881 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001882 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001883 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001884 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1885 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001886 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001887 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001888 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001889 }
1890
Christopher Tate7060b042014-06-09 19:50:00 -07001891 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001892 * Takes jobs from pending queue and runs them on available contexts.
1893 * If no contexts are available, preempts lower priority jobs to
1894 * run higher priority ones.
1895 * Lock on mJobs before calling this function.
1896 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001897 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001898 if (DEBUG) {
1899 Slog.d(TAG, printPendingQueue());
1900 }
1901
Dianne Hackborn970510b2016-02-24 16:56:42 -08001902 int memLevel;
1903 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001904 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001905 } catch (RemoteException e) {
1906 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1907 }
1908 switch (memLevel) {
1909 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001910 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001911 break;
1912 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001913 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001914 break;
1915 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001916 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001917 break;
1918 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001919 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001920 break;
1921 }
1922
1923 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1924 boolean[] act = mTmpAssignAct;
1925 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1926 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001927 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001928 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1929 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001930 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001931 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001932 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001933 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1934 numForeground++;
1935 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001936 }
1937 act[i] = false;
1938 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001939 }
1940 if (DEBUG) {
1941 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1942 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001943 for (int i=0; i<mPendingJobs.size(); i++) {
1944 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001945
1946 // If job is already running, go to next job.
1947 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1948 if (jobRunningContext != -1) {
1949 continue;
1950 }
1951
Dianne Hackborn970510b2016-02-24 16:56:42 -08001952 final int priority = evaluateJobPriorityLocked(nextPending);
1953 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001954
Shreyas Basarge5db09082016-01-07 13:38:29 +00001955 // Find a context for nextPending. The context should be available OR
1956 // it should have lowest priority among all running jobs
1957 // (sharing the same Uid as nextPending)
1958 int minPriority = Integer.MAX_VALUE;
1959 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001960 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1961 JobStatus job = contextIdToJobMap[j];
1962 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001963 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001964 if ((numActive < mMaxActiveJobs ||
1965 (priority >= JobInfo.PRIORITY_TOP_APP &&
1966 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001967 (preferredUid == nextPending.getUid() ||
1968 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1969 // This slot is free, and we haven't yet hit the limit on
1970 // concurrent jobs... we can just throw the job in to here.
1971 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001972 break;
1973 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001974 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001975 // the context has a preferred Uid or we have reached the limit on
1976 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001977 continue;
1978 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001979 if (job.getUid() != nextPending.getUid()) {
1980 continue;
1981 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001982 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001983 continue;
1984 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001985 if (minPriority > nextPending.lastEvaluatedPriority) {
1986 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001987 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001988 }
1989 }
1990 if (minPriorityContextId != -1) {
1991 contextIdToJobMap[minPriorityContextId] = nextPending;
1992 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001993 numActive++;
1994 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1995 numForeground++;
1996 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001997 }
1998 }
1999 if (DEBUG) {
2000 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
2001 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002002 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002003 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002004 boolean preservePreferredUid = false;
2005 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002006 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002007 if (js != null) {
2008 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002009 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00002010 }
2011 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07002012 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002013 preservePreferredUid = true;
2014 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002015 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00002016 if (DEBUG) {
2017 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002018 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002019 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002020 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002021 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002022 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002023 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
2024 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002025 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002026 if (mPendingJobs.remove(pendingJob)) {
2027 mJobPackageTracker.noteNonpending(pendingJob);
2028 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002029 }
2030 }
2031 if (!preservePreferredUid) {
2032 mActiveServices.get(i).clearPreferredUid();
2033 }
2034 }
2035 }
2036
2037 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
2038 for (int i=0; i<map.length; i++) {
2039 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
2040 return i;
2041 }
2042 }
2043 return -1;
2044 }
2045
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002046 final class LocalService implements JobSchedulerInternal {
2047
2048 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002049 * The current bucket heartbeat ordinal
2050 */
2051 public long currentHeartbeat() {
2052 return getCurrentHeartbeat();
2053 }
2054
2055 /**
2056 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2057 */
2058 public long nextHeartbeatForBucket(int bucket) {
2059 synchronized (mLock) {
2060 return mNextBucketHeartbeat[bucket];
2061 }
2062 }
2063
2064 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002065 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2066 * jobs are always considered pending.
2067 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002068 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002069 public List<JobInfo> getSystemScheduledPendingJobs() {
2070 synchronized (mLock) {
2071 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
2072 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
2073 @Override
2074 public void process(JobStatus job) {
2075 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2076 pendingJobs.add(job.getJob());
2077 }
2078 }
2079 });
2080 return pendingJobs;
2081 }
2082 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002083
2084 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002085 public void cancelJobsForUid(int uid, String reason) {
2086 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2087 }
2088
2089 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002090 public void addBackingUpUid(int uid) {
2091 synchronized (mLock) {
2092 // No need to actually do anything here, since for a full backup the
2093 // activity manager will kill the process which will kill the job (and
2094 // cause it to restart, but now it can't run).
2095 mBackingUpUids.put(uid, uid);
2096 }
2097 }
2098
2099 @Override
2100 public void removeBackingUpUid(int uid) {
2101 synchronized (mLock) {
2102 mBackingUpUids.delete(uid);
2103 // If there are any jobs for this uid, we need to rebuild the pending list
2104 // in case they are now ready to run.
2105 if (mJobs.countJobsForUid(uid) > 0) {
2106 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2107 }
2108 }
2109 }
2110
2111 @Override
2112 public void clearAllBackingUpUids() {
2113 synchronized (mLock) {
2114 if (mBackingUpUids.size() > 0) {
2115 mBackingUpUids.clear();
2116 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2117 }
2118 }
2119 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002120
2121 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002122 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002123 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002124 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002125 }
2126 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002127 }
2128
Shreyas Basarge5db09082016-01-07 13:38:29 +00002129 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002130 * Tracking of app assignments to standby buckets
2131 */
2132 final class StandbyTracker extends AppIdleStateChangeListener {
2133 final UsageStatsManagerInternal mUsageStats;
2134
2135 StandbyTracker(UsageStatsManagerInternal usageStats) {
2136 mUsageStats = usageStats;
2137 }
2138
2139 // AppIdleStateChangeListener interface for live updates
2140
2141 @Override
Robert Berrye2369a42018-01-19 10:52:19 +00002142 public void onAppIdleStateChanged(final String packageName, final int userId,
Christopher Tatea732f012017-10-26 17:26:53 -07002143 boolean idle, int bucket) {
2144 final int uid = mLocalPM.getPackageUid(packageName,
2145 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2146 if (uid < 0) {
2147 if (DEBUG_STANDBY) {
2148 Slog.i(TAG, "App idle state change for unknown app "
2149 + packageName + "/" + userId);
2150 }
2151 return;
2152 }
2153
2154 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2155 // update job bookkeeping out of band
2156 BackgroundThread.getHandler().post(() -> {
2157 if (DEBUG_STANDBY) {
2158 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2159 }
2160 synchronized (mLock) {
2161 // TODO: update to be more efficient once we can slice by source UID
2162 mJobs.forEachJob((JobStatus job) -> {
2163 if (job.getSourceUid() == uid) {
2164 job.setStandbyBucket(bucketIndex);
2165 }
2166 });
2167 onControllerStateChanged();
2168 }
2169 });
2170 }
2171
2172 @Override
2173 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002174 if (DEBUG_STANDBY) {
2175 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2176 }
2177 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002178 }
2179 }
2180
2181 public static int standbyBucketToBucketIndex(int bucket) {
2182 // Normalize AppStandby constants to indices into our bookkeeping
Amith Yamasaniafbccb72017-11-27 10:44:24 -08002183 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return 4;
2184 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) return 3;
2185 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) return 2;
2186 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return 1;
Christopher Tatea732f012017-10-26 17:26:53 -07002187 else return 0;
2188 }
2189
2190 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2191 UsageStatsManagerInternal usageStats = LocalServices.getService(
2192 UsageStatsManagerInternal.class);
2193 int bucket = usageStats != null
2194 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2195 : 0;
2196
2197 bucket = standbyBucketToBucketIndex(bucket);
2198
2199 if (DEBUG_STANDBY) {
2200 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2201 }
2202 return bucket;
2203 }
2204
2205 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002206 * Binder stub trampoline implementation
2207 */
2208 final class JobSchedulerStub extends IJobScheduler.Stub {
2209 /** Cache determination of whether a given app can persist jobs
2210 * key is uid of the calling app; value is undetermined/true/false
2211 */
2212 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2213
2214 // Enforce that only the app itself (or shared uid participant) can schedule a
2215 // job that runs one of the app's services, as well as verifying that the
2216 // named service properly requires the BIND_JOB_SERVICE permission
2217 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002218 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002219 final ComponentName service = job.getService();
2220 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002221 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002222 PackageManager.MATCH_DIRECT_BOOT_AWARE
2223 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002224 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002225 if (si == null) {
2226 throw new IllegalArgumentException("No such service " + service);
2227 }
Christopher Tate7060b042014-06-09 19:50:00 -07002228 if (si.applicationInfo.uid != uid) {
2229 throw new IllegalArgumentException("uid " + uid +
2230 " cannot schedule job in " + service.getPackageName());
2231 }
2232 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2233 throw new IllegalArgumentException("Scheduled service " + service
2234 + " does not require android.permission.BIND_JOB_SERVICE permission");
2235 }
Christopher Tate5568f542014-06-18 13:53:31 -07002236 } catch (RemoteException e) {
2237 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002238 }
2239 }
2240
2241 private boolean canPersistJobs(int pid, int uid) {
2242 // If we get this far we're good to go; all we need to do now is check
2243 // whether the app is allowed to persist its scheduled work.
2244 final boolean canPersist;
2245 synchronized (mPersistCache) {
2246 Boolean cached = mPersistCache.get(uid);
2247 if (cached != null) {
2248 canPersist = cached.booleanValue();
2249 } else {
2250 // Persisting jobs is tantamount to running at boot, so we permit
2251 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2252 // permission
2253 int result = getContext().checkPermission(
2254 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2255 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2256 mPersistCache.put(uid, canPersist);
2257 }
2258 }
2259 return canPersist;
2260 }
2261
2262 // IJobScheduler implementation
2263 @Override
2264 public int schedule(JobInfo job) throws RemoteException {
2265 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002266 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002267 }
2268 final int pid = Binder.getCallingPid();
2269 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002270 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002271
2272 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002273 if (job.isPersisted()) {
2274 if (!canPersistJobs(pid, uid)) {
2275 throw new IllegalArgumentException("Error: requested job be persisted without"
2276 + " holding RECEIVE_BOOT_COMPLETED permission.");
2277 }
2278 }
Christopher Tate7060b042014-06-09 19:50:00 -07002279
Jeff Sharkey785f4942016-07-14 10:31:15 -06002280 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2281 getContext().enforceCallingOrSelfPermission(
2282 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2283 }
2284
Christopher Tate7060b042014-06-09 19:50:00 -07002285 long ident = Binder.clearCallingIdentity();
2286 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002287 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2288 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002289 } finally {
2290 Binder.restoreCallingIdentity(ident);
2291 }
2292 }
2293
2294 // IJobScheduler implementation
2295 @Override
2296 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2297 if (DEBUG) {
2298 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2299 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002300 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002301 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002302
2303 enforceValidJobRequest(uid, job);
2304 if (job.isPersisted()) {
2305 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2306 }
2307 if (work == null) {
2308 throw new NullPointerException("work is null");
2309 }
2310
2311 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2312 getContext().enforceCallingOrSelfPermission(
2313 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2314 }
2315
2316 long ident = Binder.clearCallingIdentity();
2317 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002318 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2319 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002320 } finally {
2321 Binder.restoreCallingIdentity(ident);
2322 }
2323 }
2324
2325 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002326 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002327 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002328 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002329 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002330 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002331 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002332 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002333
2334 if (packageName == null) {
2335 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002336 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002337
2338 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2339 android.Manifest.permission.UPDATE_DEVICE_STATS);
2340 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2341 throw new SecurityException("Caller uid " + callerUid
2342 + " not permitted to schedule jobs for other apps");
2343 }
2344
Jeff Sharkey4f100402016-05-03 17:44:23 -06002345 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2346 getContext().enforceCallingOrSelfPermission(
2347 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2348 }
2349
Shreyas Basarge968ac752016-01-11 23:09:26 +00002350 long ident = Binder.clearCallingIdentity();
2351 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002352 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002353 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002354 } finally {
2355 Binder.restoreCallingIdentity(ident);
2356 }
2357 }
2358
2359 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002360 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2361 final int uid = Binder.getCallingUid();
2362
2363 long ident = Binder.clearCallingIdentity();
2364 try {
2365 return JobSchedulerService.this.getPendingJobs(uid);
2366 } finally {
2367 Binder.restoreCallingIdentity(ident);
2368 }
2369 }
2370
2371 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002372 public JobInfo getPendingJob(int jobId) throws RemoteException {
2373 final int uid = Binder.getCallingUid();
2374
2375 long ident = Binder.clearCallingIdentity();
2376 try {
2377 return JobSchedulerService.this.getPendingJob(uid, jobId);
2378 } finally {
2379 Binder.restoreCallingIdentity(ident);
2380 }
2381 }
2382
2383 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002384 public void cancelAll() throws RemoteException {
2385 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002386 long ident = Binder.clearCallingIdentity();
2387 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002388 JobSchedulerService.this.cancelJobsForUid(uid,
2389 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002390 } finally {
2391 Binder.restoreCallingIdentity(ident);
2392 }
2393 }
2394
2395 @Override
2396 public void cancel(int jobId) throws RemoteException {
2397 final int uid = Binder.getCallingUid();
2398
2399 long ident = Binder.clearCallingIdentity();
2400 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002401 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002402 } finally {
2403 Binder.restoreCallingIdentity(ident);
2404 }
2405 }
2406
2407 /**
2408 * "dumpsys" infrastructure
2409 */
2410 @Override
2411 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002412 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002413
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002414 int filterUid = -1;
2415 boolean proto = false;
2416 if (!ArrayUtils.isEmpty(args)) {
2417 int opti = 0;
2418 while (opti < args.length) {
2419 String arg = args[opti];
2420 if ("-h".equals(arg)) {
2421 dumpHelp(pw);
2422 return;
2423 } else if ("-a".equals(arg)) {
2424 // Ignore, we always dump all.
2425 } else if ("--proto".equals(arg)) {
2426 proto = true;
2427 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2428 pw.println("Unknown option: " + arg);
2429 return;
2430 } else {
2431 break;
2432 }
2433 opti++;
2434 }
2435 if (opti < args.length) {
2436 String pkg = args[opti];
2437 try {
2438 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2439 PackageManager.MATCH_ANY_USER);
2440 } catch (NameNotFoundException ignored) {
2441 pw.println("Invalid package: " + pkg);
2442 return;
2443 }
2444 }
2445 }
2446
Christopher Tate7060b042014-06-09 19:50:00 -07002447 long identityToken = Binder.clearCallingIdentity();
2448 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002449 if (proto) {
2450 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2451 } else {
2452 JobSchedulerService.this.dumpInternal(pw, filterUid);
2453 }
Christopher Tate7060b042014-06-09 19:50:00 -07002454 } finally {
2455 Binder.restoreCallingIdentity(identityToken);
2456 }
2457 }
Christopher Tate5d346052016-03-08 12:56:08 -08002458
2459 @Override
2460 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002461 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002462 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002463 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002464 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002465 };
2466
Christopher Tate5d346052016-03-08 12:56:08 -08002467 // Shell command infrastructure: run the given job immediately
2468 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2469 if (DEBUG) {
2470 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2471 + " " + jobId + " f=" + force);
2472 }
2473
2474 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002475 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2476 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002477 if (uid < 0) {
2478 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2479 }
2480
2481 synchronized (mLock) {
2482 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2483 if (js == null) {
2484 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2485 }
2486
2487 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2488 if (!js.isConstraintsSatisfied()) {
2489 js.overrideState = 0;
2490 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2491 }
2492
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002493 queueReadyJobsForExecutionLocked();
2494 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002495 }
2496 } catch (RemoteException e) {
2497 // can't happen
2498 }
2499 return 0;
2500 }
2501
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002502 // Shell command infrastructure: immediately timeout currently executing jobs
2503 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2504 boolean hasJobId, int jobId) {
2505 if (DEBUG) {
2506 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2507 }
2508
2509 synchronized (mLock) {
2510 boolean foundSome = false;
2511 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002512 final JobServiceContext jc = mActiveServices.get(i);
2513 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002514 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002515 foundSome = true;
2516 pw.print("Timing out: ");
2517 js.printUniqueId(pw);
2518 pw.print(" ");
2519 pw.println(js.getServiceComponent().flattenToShortString());
2520 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002521 }
2522 if (!foundSome) {
2523 pw.println("No matching executing jobs found.");
2524 }
2525 }
2526 return 0;
2527 }
2528
Christopher Tate8c67d122017-09-29 16:54:26 -07002529 // Shell command infrastructure: cancel a scheduled job
2530 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2531 boolean hasJobId, int jobId) {
2532 if (DEBUG) {
2533 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2534 }
2535
2536 int pkgUid = -1;
2537 try {
2538 IPackageManager pm = AppGlobals.getPackageManager();
2539 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2540 } catch (RemoteException e) { /* can't happen */ }
2541
2542 if (pkgUid < 0) {
2543 pw.println("Package " + pkgName + " not found.");
2544 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2545 }
2546
2547 if (!hasJobId) {
2548 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2549 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2550 pw.println("No matching jobs found.");
2551 }
2552 } else {
2553 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002554 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002555 pw.println("No matching job found.");
2556 }
2557 }
2558
2559 return 0;
2560 }
2561
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002562 void setMonitorBattery(boolean enabled) {
2563 synchronized (mLock) {
2564 if (mBatteryController != null) {
2565 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2566 }
2567 }
2568 }
2569
2570 int getBatterySeq() {
2571 synchronized (mLock) {
2572 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2573 }
2574 }
2575
2576 boolean getBatteryCharging() {
2577 synchronized (mLock) {
2578 return mBatteryController != null
2579 ? mBatteryController.getTracker().isOnStablePower() : false;
2580 }
2581 }
2582
2583 boolean getBatteryNotLow() {
2584 synchronized (mLock) {
2585 return mBatteryController != null
2586 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2587 }
2588 }
2589
Dianne Hackborn532ea262017-03-17 17:50:55 -07002590 int getStorageSeq() {
2591 synchronized (mLock) {
2592 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2593 }
2594 }
2595
2596 boolean getStorageNotLow() {
2597 synchronized (mLock) {
2598 return mStorageController != null
2599 ? mStorageController.getTracker().isStorageNotLow() : false;
2600 }
2601 }
2602
Christopher Tatea732f012017-10-26 17:26:53 -07002603 long getCurrentHeartbeat() {
2604 synchronized (mLock) {
2605 return mHeartbeat;
2606 }
2607 }
2608
Dianne Hackborn6d068262017-05-16 13:14:37 -07002609 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2610 try {
2611 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2612 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2613 if (uid < 0) {
2614 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2615 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2616 }
2617
2618 synchronized (mLock) {
2619 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2620 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2621 if (js == null) {
2622 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2623 pw.print("/jid"); pw.print(jobId); pw.println(")");
2624 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2625 }
2626
2627 boolean printed = false;
2628 if (mPendingJobs.contains(js)) {
2629 pw.print("pending");
2630 printed = true;
2631 }
2632 if (isCurrentlyActiveLocked(js)) {
2633 if (printed) {
2634 pw.print(" ");
2635 }
2636 printed = true;
2637 pw.println("active");
2638 }
2639 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2640 if (printed) {
2641 pw.print(" ");
2642 }
2643 printed = true;
2644 pw.println("user-stopped");
2645 }
2646 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2647 if (printed) {
2648 pw.print(" ");
2649 }
2650 printed = true;
2651 pw.println("backing-up");
2652 }
2653 boolean componentPresent = false;
2654 try {
2655 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2656 js.getServiceComponent(),
2657 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2658 js.getUserId()) != null);
2659 } catch (RemoteException e) {
2660 }
2661 if (!componentPresent) {
2662 if (printed) {
2663 pw.print(" ");
2664 }
2665 printed = true;
2666 pw.println("no-component");
2667 }
2668 if (js.isReady()) {
2669 if (printed) {
2670 pw.print(" ");
2671 }
2672 printed = true;
2673 pw.println("ready");
2674 }
2675 if (!printed) {
2676 pw.print("waiting");
2677 }
2678 pw.println();
2679 }
2680 } catch (RemoteException e) {
2681 // can't happen
2682 }
2683 return 0;
2684 }
2685
Shreyas Basarge5db09082016-01-07 13:38:29 +00002686 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2687 StringBuilder s = new StringBuilder(initial + ": ");
2688 for (int i=0; i<map.length; i++) {
2689 s.append("(")
2690 .append(map[i] == null? -1: map[i].getJobId())
2691 .append(map[i] == null? -1: map[i].getUid())
2692 .append(")" );
2693 }
2694 return s.toString();
2695 }
2696
2697 private String printPendingQueue() {
2698 StringBuilder s = new StringBuilder("Pending queue: ");
2699 Iterator<JobStatus> it = mPendingJobs.iterator();
2700 while (it.hasNext()) {
2701 JobStatus js = it.next();
2702 s.append("(")
2703 .append(js.getJob().getId())
2704 .append(", ")
2705 .append(js.getUid())
2706 .append(") ");
2707 }
2708 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002709 }
Christopher Tate7060b042014-06-09 19:50:00 -07002710
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002711 static void dumpHelp(PrintWriter pw) {
2712 pw.println("Job Scheduler (jobscheduler) dump options:");
2713 pw.println(" [-h] [package] ...");
2714 pw.println(" -h: print this help");
2715 pw.println(" [package] is an optional package name to limit the output to.");
2716 }
2717
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002718 /** Sort jobs by caller UID, then by Job ID. */
2719 private static void sortJobs(List<JobStatus> jobs) {
2720 Collections.sort(jobs, new Comparator<JobStatus>() {
2721 @Override
2722 public int compare(JobStatus o1, JobStatus o2) {
2723 int uid1 = o1.getUid();
2724 int uid2 = o2.getUid();
2725 int id1 = o1.getJobId();
2726 int id2 = o2.getJobId();
2727 if (uid1 != uid2) {
2728 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002729 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002730 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002731 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002732 });
2733 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002734
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002735 void dumpInternal(final PrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002736 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07002737 final long nowElapsed = sElapsedRealtimeClock.millis();
2738 final long nowUptime = sUptimeMillisClock.millis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002739 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002740 mConstants.dump(pw);
2741 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002742 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002743 pw.print("Registered ");
2744 pw.print(mJobs.size());
2745 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002746 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002747 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002748 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002749 for (JobStatus job : jobs) {
2750 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2751 pw.println(job.toShortStringExceptUniqueId());
2752
2753 // Skip printing details if the caller requested a filter
2754 if (!job.shouldDump(filterUidFinal)) {
2755 continue;
2756 }
2757
Dianne Hackborn6d068262017-05-16 13:14:37 -07002758 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002759 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002760 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002761 pw.print(" (job=");
2762 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002763 pw.print(" user=");
2764 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002765 pw.print(" !pending=");
2766 pw.print(!mPendingJobs.contains(job));
2767 pw.print(" !active=");
2768 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002769 pw.print(" !backingup=");
2770 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002771 pw.print(" comp=");
2772 boolean componentPresent = false;
2773 try {
2774 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2775 job.getServiceComponent(),
2776 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2777 job.getUserId()) != null);
2778 } catch (RemoteException e) {
2779 }
2780 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002781 pw.println(")");
2782 }
Christopher Tate7060b042014-06-09 19:50:00 -07002783 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002784 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002785 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002786 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002787 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002788 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002789 }
2790 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002791 pw.println("Uid priority overrides:");
2792 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002793 int uid = mUidPriorityOverride.keyAt(i);
2794 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2795 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2796 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2797 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002798 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002799 if (mBackingUpUids.size() > 0) {
2800 pw.println();
2801 pw.println("Backing up uids:");
2802 boolean first = true;
2803 for (int i = 0; i < mBackingUpUids.size(); i++) {
2804 int uid = mBackingUpUids.keyAt(i);
2805 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2806 if (first) {
2807 pw.print(" ");
2808 first = false;
2809 } else {
2810 pw.print(", ");
2811 }
2812 pw.print(UserHandle.formatUid(uid));
2813 }
2814 }
2815 pw.println();
2816 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002817 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002818 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002819 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002820 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2821 pw.println();
2822 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002823 pw.println("Pending queue:");
2824 for (int i=0; i<mPendingJobs.size(); i++) {
2825 JobStatus job = mPendingJobs.get(i);
2826 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2827 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002828 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002829 int priority = evaluateJobPriorityLocked(job);
2830 if (priority != JobInfo.PRIORITY_DEFAULT) {
2831 pw.print(" Evaluated priority: "); pw.println(priority);
2832 }
2833 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002834 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002835 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002836 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002837 }
Christopher Tate7060b042014-06-09 19:50:00 -07002838 pw.println();
2839 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002840 for (int i=0; i<mActiveServices.size(); i++) {
2841 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002842 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002843 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002844 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002845 if (jsc.mStoppedReason != null) {
2846 pw.print("inactive since ");
2847 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2848 pw.print(", stopped because: ");
2849 pw.println(jsc.mStoppedReason);
2850 } else {
2851 pw.println("inactive");
2852 }
Christopher Tate7060b042014-06-09 19:50:00 -07002853 continue;
2854 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002855 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002856 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002857 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002858 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002859 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002860 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002861 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002862 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002863 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002864 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002865 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002866 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002867 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002868 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002869 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2870 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002871 }
2872 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002873 if (filterUid == -1) {
2874 pw.println();
2875 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2876 pw.print("mReportedActive="); pw.println(mReportedActive);
2877 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2878 }
Makoto Onukie7b02982017-08-24 14:23:36 -07002879 pw.println();
2880 pw.print("PersistStats: ");
2881 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07002882 }
2883 pw.println();
2884 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002885
2886 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
2887 ProtoOutputStream proto = new ProtoOutputStream(fd);
2888 final int filterUidFinal = UserHandle.getAppId(filterUid);
2889 final long nowElapsed = sElapsedRealtimeClock.millis();
2890 final long nowUptime = sUptimeMillisClock.millis();
2891
2892 synchronized (mLock) {
2893 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
2894 for (int u : mStartedUsers) {
2895 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
2896 }
2897 if (mJobs.size() > 0) {
2898 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2899 sortJobs(jobs);
2900 for (JobStatus job : jobs) {
2901 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
2902 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
2903
2904 // Skip printing details if the caller requested a filter
2905 if (!job.shouldDump(filterUidFinal)) {
2906 continue;
2907 }
2908
2909 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
2910
2911 // isReadyToBeExecuted
2912 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
2913 job.isReady());
2914 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
2915 ArrayUtils.contains(mStartedUsers, job.getUserId()));
2916 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
2917 mPendingJobs.contains(job));
2918 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
2919 isCurrentlyActiveLocked(job));
2920 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
2921 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
2922 boolean componentPresent = false;
2923 try {
2924 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2925 job.getServiceComponent(),
2926 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2927 job.getUserId()) != null);
2928 } catch (RemoteException e) {
2929 }
2930 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
2931 componentPresent);
2932
2933 proto.end(rjToken);
2934 }
2935 }
2936 for (StateController controller : mControllers) {
2937 controller.dumpControllerStateLocked(
2938 proto, JobSchedulerServiceDumpProto.CONTROLLERS, filterUidFinal);
2939 }
2940 for (int i=0; i< mUidPriorityOverride.size(); i++) {
2941 int uid = mUidPriorityOverride.keyAt(i);
2942 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2943 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
2944 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
2945 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
2946 mUidPriorityOverride.valueAt(i));
2947 proto.end(pToken);
2948 }
2949 }
2950 for (int i = 0; i < mBackingUpUids.size(); i++) {
2951 int uid = mBackingUpUids.keyAt(i);
2952 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2953 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
2954 }
2955 }
2956
2957 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
2958 filterUidFinal);
2959 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
2960 filterUidFinal);
2961
2962 for (JobStatus job : mPendingJobs) {
2963 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
2964
2965 job.writeToShortProto(proto, PendingJob.INFO);
2966 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
2967 int priority = evaluateJobPriorityLocked(job);
2968 if (priority != JobInfo.PRIORITY_DEFAULT) {
2969 proto.write(PendingJob.EVALUATED_PRIORITY, priority);
2970 }
2971 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
2972
2973 proto.end(pjToken);
2974 }
2975 for (JobServiceContext jsc : mActiveServices) {
2976 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
2977 final JobStatus job = jsc.getRunningJobLocked();
2978
2979 if (job == null) {
2980 final long ijToken = proto.start(ActiveJob.INACTIVE);
2981
2982 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
2983 nowElapsed - jsc.mStoppedTime);
2984 if (jsc.mStoppedReason != null) {
2985 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
2986 jsc.mStoppedReason);
2987 }
2988
2989 proto.end(ijToken);
2990 } else {
2991 final long rjToken = proto.start(ActiveJob.RUNNING);
2992
2993 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
2994
2995 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
2996 nowElapsed - jsc.getExecutionStartTimeElapsed());
2997 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
2998 jsc.getTimeoutElapsed() - nowElapsed);
2999
3000 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3001
3002 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
3003 if (priority != JobInfo.PRIORITY_DEFAULT) {
3004 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY, priority);
3005 }
3006
3007 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3008 nowUptime - job.madeActive);
3009 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3010 job.madeActive - job.madePending);
3011
3012 proto.end(rjToken);
3013 }
3014 proto.end(ajToken);
3015 }
3016 if (filterUid == -1) {
3017 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3018 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3019 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
3020 }
3021 }
3022
3023 proto.flush();
3024 }
Christopher Tate7060b042014-06-09 19:50:00 -07003025}