blob: 47a4fb24201c9af36ae68de4a0befe9ddd34807b [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 Tate435c2f42018-01-18 12:59:15 -080022import android.annotation.UserIdInt;
Christopher Tateee7805b2016-07-15 16:56:56 -070023import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070024import android.app.ActivityManager;
Makoto Onuki15407842018-01-19 14:23:11 -080025import android.app.ActivityManagerInternal;
Christopher Tate5568f542014-06-18 13:53:31 -070026import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070027import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070028import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000030import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070031import android.app.job.JobScheduler;
32import android.app.job.JobService;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070033import android.app.job.JobWorkItem;
Amith Yamasaniafbccb72017-11-27 10:44:24 -080034import android.app.usage.UsageStatsManager;
Christopher Tatea732f012017-10-26 17:26:53 -070035import android.app.usage.UsageStatsManagerInternal;
36import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
Christopher Tate7060b042014-06-09 19:50:00 -070037import android.content.BroadcastReceiver;
38import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070039import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070040import android.content.Context;
41import android.content.Intent;
42import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070043import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070044import android.content.pm.PackageManager;
Christopher Tatea732f012017-10-26 17:26:53 -070045import android.content.pm.PackageManagerInternal;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060046import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070047import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070048import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070049import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070050import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070051import android.os.Binder;
52import android.os.Handler;
53import android.os.Looper;
54import android.os.Message;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070055import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070056import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080057import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070058import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070059import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070060import android.os.SystemClock;
61import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070062import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070063import android.provider.Settings;
64import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070065import android.util.Slog;
66import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080067import android.util.SparseIntArray;
Tej Singhd5747a62018-01-08 20:57:35 -080068import android.util.StatsLog;
Dianne Hackborn970510b2016-02-24 16:56:42 -080069import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080070import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080071
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070072import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070073import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070074import com.android.internal.app.procstats.ProcessStats;
Christopher Tatea732f012017-10-26 17:26:53 -070075import com.android.internal.os.BackgroundThread;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070076import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060077import com.android.internal.util.DumpUtils;
Makoto Onuki15407842018-01-19 14:23:11 -080078import com.android.internal.util.Preconditions;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080079import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070080import com.android.server.FgThread;
Makoto Onukie4918212018-02-06 11:30:15 -080081import com.android.server.AppStateTracker;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080082import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080083import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
84import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Christopher Tate2f36fd62016-02-18 18:36:08 -080085import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080086import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070087import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070088import com.android.server.job.controllers.BatteryController;
89import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080090import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070091import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070092import com.android.server.job.controllers.IdleController;
93import com.android.server.job.controllers.JobStatus;
94import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070095import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070096import com.android.server.job.controllers.TimeController;
97
Jeff Sharkey822cbd12016-02-25 11:09:55 -070098import libcore.util.EmptyArray;
99
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700100import java.io.FileDescriptor;
101import java.io.PrintWriter;
102import java.time.Clock;
103import java.util.ArrayList;
104import java.util.Arrays;
105import java.util.Collections;
106import java.util.Comparator;
107import java.util.Iterator;
108import java.util.List;
Makoto Onuki15407842018-01-19 14:23:11 -0800109import java.util.function.Predicate;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700110
Christopher Tate7060b042014-06-09 19:50:00 -0700111/**
112 * Responsible for taking jobs representing work to be performed by a client app, and determining
113 * based on the criteria specified when that job should be run against the client application's
114 * endpoint.
115 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
116 * about constraints, or the state of active jobs. It receives callbacks from the various
117 * controllers and completed jobs and operates accordingly.
118 *
119 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
120 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
121 * @hide
122 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800123public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700124 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800125 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700126 public static final boolean DEBUG = false;
Christopher Tatea732f012017-10-26 17:26:53 -0700127 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800128
Dianne Hackborn970510b2016-02-24 16:56:42 -0800129 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700130 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800131 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800132 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800133 /** The maximum number of jobs that we allow an unprivileged app to schedule */
134 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700135
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700136 @VisibleForTesting
137 public static Clock sSystemClock = Clock.systemUTC();
138 @VisibleForTesting
139 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
140 @VisibleForTesting
141 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800142
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800143 /** Global local for all job scheduler state. */
144 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700145 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700146 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700147 /** Tracking the standby bucket state of each app */
148 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700149 /** Tracking amount of time each package runs for. */
150 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700151
152 static final int MSG_JOB_EXPIRED = 0;
153 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700154 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000155 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700156
Christopher Tate7060b042014-06-09 19:50:00 -0700157 /**
158 * Track Services that have currently active or pending jobs. The index is provided by
159 * {@link JobStatus#getServiceToken()}
160 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700161 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700162 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700163 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800164 /** Need direct access to this for testing. */
165 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700166 /** Need direct access to this for testing. */
167 StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700168 /** Need directly for sending uid state changes */
169 private BackgroundJobsController mBackgroundJobsController;
Suprabh Shukla106203b2017-11-02 21:23:44 -0700170 private DeviceIdleJobsController mDeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700171 /**
172 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
173 * when ready to execute them.
174 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700175 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700176
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700177 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700178
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700179 final JobHandler mHandler;
180 final JobSchedulerStub mJobSchedulerStub;
181
Christopher Tatea732f012017-10-26 17:26:53 -0700182 PackageManagerInternal mLocalPM;
Makoto Onuki15407842018-01-19 14:23:11 -0800183 ActivityManagerInternal mActivityManagerInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700184 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800185 DeviceIdleController.LocalService mLocalDeviceIdleController;
Makoto Onukie4918212018-02-06 11:30:15 -0800186 AppStateTracker mAppStateTracker;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700187
188 /**
189 * Set to true once we are allowed to run third party apps.
190 */
191 boolean mReadyToRock;
192
Christopher Tate7060b042014-06-09 19:50:00 -0700193 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800194 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800195 */
196 boolean mReportedActive;
197
198 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800199 * Are we currently in device-wide standby parole?
200 */
201 volatile boolean mInParole;
202
203 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800204 * Current limit on the number of concurrent JobServiceContext entries we want to
205 * keep actively running a job.
206 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700207 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800208
209 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800210 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800211 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800212 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
213
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700214 /**
215 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
216 */
217 final SparseIntArray mBackingUpUids = new SparseIntArray();
218
Christopher Tatea732f012017-10-26 17:26:53 -0700219 /**
220 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
221 * next become runnable. Index into this array is by normalized bucket:
222 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
223 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
224 * and NEVER apps don't get them at all.
225 */
226 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
227 long mHeartbeat = 0;
228 long mLastHeartbeatTime = 0;
229
Dianne Hackborn970510b2016-02-24 16:56:42 -0800230 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
231
232 /**
233 * This array essentially stores the state of mActiveServices array.
234 * The ith index stores the job present on the ith JobServiceContext.
235 * We manipulate this array until we arrive at what jobs should be running on
236 * what JobServiceContext.
237 */
238 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
239 /**
240 * Indicates whether we need to act on this jobContext id
241 */
242 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
243 /**
244 * The uid whose jobs we would like to assign to a context.
245 */
246 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800247
248 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700249 * All times are in milliseconds. These constants are kept synchronized with the system
250 * global Settings. Any access to this class or its fields should be done while
251 * holding the JobSchedulerService.mLock lock.
252 */
253 private final class Constants extends ContentObserver {
254 // Key names stored in the settings value.
255 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
256 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800257 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700258 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700259 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
260 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
261 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
262 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
263 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
264 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
265 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
266 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
267 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
268 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700269 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
270 = "max_standard_reschedule_count";
271 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
272 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
273 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700274 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
275 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
276 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
277 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700278
279 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
280 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800281 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700282 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700283 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
284 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
285 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
286 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
287 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
288 private static final int DEFAULT_FG_JOB_COUNT = 4;
289 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
290 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700291 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700292 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700293 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
294 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
295 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
296 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700297 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000298 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
299 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700300 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700301
302 /**
303 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
304 * early.
305 */
306 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
307 /**
308 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
309 * things early.
310 */
311 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
312 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800313 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
314 * schedule things early.
315 */
316 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
317 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700318 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
319 * schedule things early.
320 */
321 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
322 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700323 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
324 * things early. 1 == Run connectivity jobs as soon as ready.
325 */
326 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
327 /**
328 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
329 * schedule things early.
330 */
331 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
332 /**
333 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
334 * running some work early. This (and thus the other min counts) is now set to 1, to
335 * prevent any batching at this level. Since we now do batching through doze, that is
336 * a much better mechanism.
337 */
338 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
339 /**
340 * This is the job execution factor that is considered to be heavy use of the system.
341 */
342 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
343 /**
344 * This is the job execution factor that is considered to be moderate use of the system.
345 */
346 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
347 /**
348 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
349 */
350 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
351 /**
352 * The maximum number of background jobs we allow when the system is in a normal
353 * memory state.
354 */
355 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
356 /**
357 * The maximum number of background jobs we allow when the system is in a moderate
358 * memory state.
359 */
360 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
361 /**
362 * The maximum number of background jobs we allow when the system is in a low
363 * memory state.
364 */
365 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
366 /**
367 * The maximum number of background jobs we allow when the system is in a critical
368 * memory state.
369 */
370 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700371 /**
372 * The maximum number of times we allow a job to have itself rescheduled before
373 * giving up on it, for standard jobs.
374 */
375 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
376 /**
377 * The maximum number of times we allow a job to have itself rescheduled before
378 * giving up on it, for jobs that are executing work.
379 */
380 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
381 /**
382 * The minimum backoff time to allow for linear backoff.
383 */
384 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
385 /**
386 * The minimum backoff time to allow for exponential backoff.
387 */
388 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700389 /**
390 * How often we recalculate runnability based on apps' standby bucket assignment.
391 * This should be prime relative to common time interval lengths such as a quarter-
392 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
393 */
394 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
395
396 /**
397 * Mapping: standby bucket -> number of heartbeats between each sweep of that
398 * bucket's jobs.
399 *
400 * Bucket assignments as recorded in the JobStatus objects are normalized to be
401 * indices into this array, rather than the raw constants used
402 * by AppIdleHistory.
403 */
404 final int[] STANDBY_BEATS = {
405 0,
406 DEFAULT_STANDBY_WORKING_BEATS,
407 DEFAULT_STANDBY_FREQUENT_BEATS,
408 DEFAULT_STANDBY_RARE_BEATS
409 };
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700410
411 private ContentResolver mResolver;
412 private final KeyValueListParser mParser = new KeyValueListParser(',');
413
414 public Constants(Handler handler) {
415 super(handler);
416 }
417
418 public void start(ContentResolver resolver) {
419 mResolver = resolver;
420 mResolver.registerContentObserver(Settings.Global.getUriFor(
421 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
422 updateConstants();
423 }
424
425 @Override
426 public void onChange(boolean selfChange, Uri uri) {
427 updateConstants();
428 }
429
430 private void updateConstants() {
431 synchronized (mLock) {
432 try {
433 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000434 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700435 } catch (IllegalArgumentException e) {
436 // Failed to parse the settings string, log this and move on
437 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000438 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700439 }
440
441 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
442 DEFAULT_MIN_IDLE_COUNT);
443 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
444 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800445 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
446 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700447 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
448 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700449 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
450 DEFAULT_MIN_CONNECTIVITY_COUNT);
451 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
452 DEFAULT_MIN_CONTENT_COUNT);
453 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
454 DEFAULT_MIN_READY_JOBS_COUNT);
455 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
456 DEFAULT_HEAVY_USE_FACTOR);
457 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
458 DEFAULT_MODERATE_USE_FACTOR);
459 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
460 DEFAULT_FG_JOB_COUNT);
461 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
462 DEFAULT_BG_NORMAL_JOB_COUNT);
463 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
464 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
465 }
466 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
467 DEFAULT_BG_MODERATE_JOB_COUNT);
468 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
469 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
470 }
471 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
472 DEFAULT_BG_LOW_JOB_COUNT);
473 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
474 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
475 }
476 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
477 DEFAULT_BG_CRITICAL_JOB_COUNT);
478 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
479 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
480 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700481 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
482 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
483 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
484 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800485 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700486 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800487 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700488 DEFAULT_MIN_EXP_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800489 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
Christopher Tatea732f012017-10-26 17:26:53 -0700490 DEFAULT_STANDBY_HEARTBEAT_TIME);
491 STANDBY_BEATS[1] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
492 DEFAULT_STANDBY_WORKING_BEATS);
493 STANDBY_BEATS[2] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
494 DEFAULT_STANDBY_FREQUENT_BEATS);
495 STANDBY_BEATS[3] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
496 DEFAULT_STANDBY_RARE_BEATS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700497 }
498 }
499
500 void dump(PrintWriter pw) {
501 pw.println(" Settings:");
502
503 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
504 pw.print(MIN_IDLE_COUNT); pw.println();
505
506 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
507 pw.print(MIN_CHARGING_COUNT); pw.println();
508
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800509 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
510 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
511
Dianne Hackborn532ea262017-03-17 17:50:55 -0700512 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
513 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
514
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700515 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
516 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
517
518 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
519 pw.print(MIN_CONTENT_COUNT); pw.println();
520
521 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
522 pw.print(MIN_READY_JOBS_COUNT); pw.println();
523
524 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
525 pw.print(HEAVY_USE_FACTOR); pw.println();
526
527 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
528 pw.print(MODERATE_USE_FACTOR); pw.println();
529
530 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
531 pw.print(FG_JOB_COUNT); pw.println();
532
533 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
534 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
535
536 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
537 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
538
539 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
540 pw.print(BG_LOW_JOB_COUNT); pw.println();
541
542 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
543 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700544
545 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
546 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
547
548 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
549 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
550
551 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
552 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
553
554 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
555 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Christopher Tatea732f012017-10-26 17:26:53 -0700556
557 pw.print(" "); pw.print(KEY_STANDBY_HEARTBEAT_TIME); pw.print("=");
558 pw.print(STANDBY_HEARTBEAT_TIME); pw.println();
559
560 pw.print(" standby_beats={");
561 pw.print(STANDBY_BEATS[0]);
562 for (int i = 1; i < STANDBY_BEATS.length; i++) {
563 pw.print(", ");
564 pw.print(STANDBY_BEATS[i]);
565 }
566 pw.println('}');
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700567 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800568
569 void dump(ProtoOutputStream proto, long fieldId) {
570 final long token = proto.start(fieldId);
571
572 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
573 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
574 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
575 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
576 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
577 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
578 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
579 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
580 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
581 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
582 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
583 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
584 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
585 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
586 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
587 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
588 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
589 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
590 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
591
592 for (int period : STANDBY_BEATS) {
593 proto.write(ConstantsProto.STANDBY_BEATS, period);
594 }
595
596 proto.end(token);
597 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700598 }
599
600 final Constants mConstants;
601
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700602 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
603 if (o1.enqueueTime < o2.enqueueTime) {
604 return -1;
605 }
606 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
607 };
608
609 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
610 int where = Collections.binarySearch(array, newItem, comparator);
611 if (where < 0) {
612 where = ~where;
613 }
614 array.add(where, newItem);
615 }
616
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700617 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700618 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
619 * still clean up. On reinstall the package will have a new uid.
620 */
621 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
622 @Override
623 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700624 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700625 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700626 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700627 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700628 final String pkgName = getPackageName(intent);
629 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
630
Christopher Tateee7805b2016-07-15 16:56:56 -0700631 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700632 // Purge the app's jobs if the whole package was just disabled. When this is
633 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700634 if (pkgName != null && pkgUid != -1) {
635 final String[] changedComponents = intent.getStringArrayExtra(
636 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
637 if (changedComponents != null) {
638 for (String component : changedComponents) {
639 if (component.equals(pkgName)) {
640 if (DEBUG) {
641 Slog.d(TAG, "Package state change: " + pkgName);
642 }
643 try {
644 final int userId = UserHandle.getUserId(pkgUid);
645 IPackageManager pm = AppGlobals.getPackageManager();
646 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
647 if (state == COMPONENT_ENABLED_STATE_DISABLED
648 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
649 if (DEBUG) {
650 Slog.d(TAG, "Removing jobs for package " + pkgName
651 + " in user " + userId);
652 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700653 cancelJobsForPackageAndUid(pkgName, pkgUid,
654 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700655 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700656 } catch (RemoteException|IllegalArgumentException e) {
657 /*
658 * IllegalArgumentException means that the package doesn't exist.
659 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
660 * behind outright uninstall, so by the time we try to act it's gone.
661 * We don't need to act on this PACKAGE_CHANGED when this happens;
662 * we'll get a PACKAGE_REMOVED later and clean up then.
663 *
664 * RemoteException can't actually happen; the package manager is
665 * running in this same process.
666 */
667 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700668 break;
669 }
670 }
671 }
672 } else {
673 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
674 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700675 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700676 // If this is an outright uninstall rather than the first half of an
677 // app update sequence, cancel the jobs associated with the app.
678 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
679 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
680 if (DEBUG) {
681 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
682 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700683 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700684 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700685 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700686 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
687 if (DEBUG) {
688 Slog.d(TAG, "Removing jobs for user: " + userId);
689 }
690 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700691 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
692 // Has this package scheduled any jobs, such that we will take action
693 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700694 if (pkgUid != -1) {
695 List<JobStatus> jobsForUid;
696 synchronized (mLock) {
697 jobsForUid = mJobs.getJobsByUid(pkgUid);
698 }
699 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
700 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
701 if (DEBUG) {
702 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
703 + pkgUid + " has jobs");
704 }
705 setResultCode(Activity.RESULT_OK);
706 break;
707 }
708 }
709 }
710 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
711 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700712 if (pkgUid != -1) {
713 if (DEBUG) {
714 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
715 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700716 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700717 }
Christopher Tate7060b042014-06-09 19:50:00 -0700718 }
719 }
720 };
721
Christopher Tateb5c07882016-05-26 17:11:09 -0700722 private String getPackageName(Intent intent) {
723 Uri uri = intent.getData();
724 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
725 return pkg;
726 }
727
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700728 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700729 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800730 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700731 }
732
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700733 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800734 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800735 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700736 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800737 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700738 synchronized (mLock) {
739 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
740 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700741 }
742
743 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla106203b2017-11-02 21:23:44 -0700744 synchronized (mLock) {
745 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
746 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700747 }
748
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700749 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800750 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700751 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800752 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700753 synchronized (mLock) {
754 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
755 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700756 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700757
758 @Override public void onUidCachedChanged(int uid, boolean cached) {
759 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700760 };
761
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800762 public Object getLock() {
763 return mLock;
764 }
765
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700766 public JobStore getJobStore() {
767 return mJobs;
768 }
769
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700770 @Override
771 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700772 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
773 // Let's kick any outstanding jobs for this user.
774 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
775 }
776
777 @Override
778 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700779 // Let's kick any outstanding jobs for this user.
780 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
781 }
782
783 @Override
784 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700785 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700786 }
787
Makoto Onuki15407842018-01-19 14:23:11 -0800788 /**
Makoto Onukie4918212018-02-06 11:30:15 -0800789 * Return whether an UID is active or idle.
Makoto Onuki15407842018-01-19 14:23:11 -0800790 */
Makoto Onukie4918212018-02-06 11:30:15 -0800791 private boolean isUidActive(int uid) {
792 return mAppStateTracker.isUidActiveSynced(uid);
Makoto Onuki15407842018-01-19 14:23:11 -0800793 }
794
Makoto Onukie4918212018-02-06 11:30:15 -0800795 private final Predicate<Integer> mIsUidActivePredicate = this::isUidActive;
Makoto Onuki15407842018-01-19 14:23:11 -0800796
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700797 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
798 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700799 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800800 if (ActivityManager.getService().isAppStartModeDisabled(uId,
801 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700802 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
803 + " -- package not allowed to start");
804 return JobScheduler.RESULT_FAILURE;
805 }
806 } catch (RemoteException e) {
807 }
Christopher Tatea732f012017-10-26 17:26:53 -0700808
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800809 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700810 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
811
812 if (work != null && toCancel != null) {
813 // Fast path: we are adding work to an existing job, and the JobInfo is not
814 // changing. We can just directly enqueue this work in to the job.
815 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -0800816
Dianne Hackborn342e6032017-04-13 18:04:31 -0700817 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Makoto Onuki15407842018-01-19 14:23:11 -0800818
819 // If any of work item is enqueued when the source is in the foreground,
820 // exempt the entire job.
Makoto Onukie4918212018-02-06 11:30:15 -0800821 toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800822
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700823 return JobScheduler.RESULT_SUCCESS;
824 }
825 }
826
827 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -0800828
829 // Give exemption if the source is in the foreground just now.
830 // Note if it's a sync job, this method is called on the handler so it's not exactly
831 // the state when requestSync() was called, but that should be fine because of the
832 // 1 minute foreground grace period.
Makoto Onukie4918212018-02-06 11:30:15 -0800833 jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800834
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700835 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800836 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800837 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800838 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
839 Slog.w(TAG, "Too many jobs for uid " + uId);
840 throw new IllegalStateException("Apps may not schedule more than "
841 + MAX_JOBS_PER_APP + " distinct jobs");
842 }
843 }
844
Dianne Hackborna47223f2017-03-30 13:49:13 -0700845 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700846 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700847
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700848 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700849 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700850 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700851 if (work != null) {
852 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700853 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700854 }
855 startTrackingJobLocked(jobStatus, toCancel);
Tej Singhd5747a62018-01-08 20:57:35 -0800856 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -0800857 uId, null, jobStatus.getBatteryName(),
858 StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700859
860 // If the job is immediately ready to run, then we can just immediately
861 // put it in the pending list and try to schedule it. This is especially
862 // important for jobs with a 0 deadline constraint, since they will happen a fair
863 // amount, we want to handle them as quickly as possible, and semantically we want to
864 // make sure we have started holding the wake lock for the job before returning to
865 // the caller.
866 // If the job is not yet ready to run, there is nothing more to do -- we are
867 // now just waiting for one of its controllers to change state and schedule
868 // the job appropriately.
869 if (isReadyToBeExecutedLocked(jobStatus)) {
870 // This is a new job, we can just immediately put it on the pending
871 // list and try to run it.
872 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700873 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700874 maybeRunPendingJobsLocked();
875 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800876 }
Christopher Tate7060b042014-06-09 19:50:00 -0700877 return JobScheduler.RESULT_SUCCESS;
878 }
879
880 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800881 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800882 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
883 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
884 for (int i = jobs.size() - 1; i >= 0; i--) {
885 JobStatus job = jobs.get(i);
886 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700887 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800888 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700889 }
Christopher Tate7060b042014-06-09 19:50:00 -0700890 }
891
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600892 public JobInfo getPendingJob(int uid, int jobId) {
893 synchronized (mLock) {
894 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
895 for (int i = jobs.size() - 1; i >= 0; i--) {
896 JobStatus job = jobs.get(i);
897 if (job.getJobId() == jobId) {
898 return job.getJob();
899 }
900 }
901 return null;
902 }
903 }
904
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700905 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800906 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700907 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
908 for (int i=0; i<jobsForUser.size(); i++) {
909 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700910 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700911 }
Christopher Tate7060b042014-06-09 19:50:00 -0700912 }
913 }
914
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700915 private void cancelJobsForNonExistentUsers() {
916 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
917 synchronized (mLock) {
918 mJobs.removeJobsOfNonUsers(umi.getUserIds());
919 }
920 }
921
Makoto Onukie7b96182017-08-30 14:53:16 -0700922 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
923 if ("android".equals(pkgName)) {
924 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
925 return;
926 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700927 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700928 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
929 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
930 final JobStatus job = jobsForUid.get(i);
931 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700932 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700933 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700934 }
935 }
936 }
937
Christopher Tate7060b042014-06-09 19:50:00 -0700938 /**
939 * Entry point from client to cancel all jobs originating from their uid.
940 * This will remove the job from the master list, and cancel the job if it was staged for
941 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700942 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800943 *
Christopher Tate7060b042014-06-09 19:50:00 -0700944 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700945 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700946 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700947 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700948 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700949 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700950
951 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800952 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700953 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
954 for (int i=0; i<jobsForUid.size(); i++) {
955 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700956 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700957 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700958 }
Christopher Tate7060b042014-06-09 19:50:00 -0700959 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700960 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700961 }
962
963 /**
964 * Entry point from client to cancel the job corresponding to the jobId provided.
965 * This will remove the job from the master list, and cancel the job if it was staged for
966 * execution or being executed.
967 * @param uid Uid of the calling client.
968 * @param jobId Id of the job, provided at schedule-time.
969 */
Makoto Onukid2bfec62018-01-12 13:58:01 -0800970 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -0700971 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800972 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700973 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700974 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -0800975 cancelJobImplLocked(toCancel, null,
976 "cancel() called by app, callingUid=" + callingUid
977 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700978 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700979 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -0700980 }
981 }
982
Dianne Hackborn729a3282017-06-09 16:06:01 -0700983 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700984 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
985 cancelled.unprepareLocked(ActivityManager.getService());
986 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
987 // Remove from pending queue.
988 if (mPendingJobs.remove(cancelled)) {
989 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700990 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700991 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700992 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700993 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700994 }
995
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800996 void updateUidState(int uid, int procState) {
997 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800998 if (procState == ActivityManager.PROCESS_STATE_TOP) {
999 // Only use this if we are exactly the top app. All others can live
1000 // with just the foreground priority. This means that persistent processes
1001 // can never be the top app priority... that is fine.
1002 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001003 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001004 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001005 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001006 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001007 }
1008 }
1009 }
1010
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001011 @Override
1012 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001013 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001014 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001015 // When becoming idle, make sure no jobs are actively running,
1016 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001017 for (int i=0; i<mActiveServices.size(); i++) {
1018 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001019 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001020 if (executing != null
1021 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001022 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1023 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001024 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001025 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001026 } else {
1027 // When coming out of idle, allow thing to start back up.
1028 if (mReadyToRock) {
1029 if (mLocalDeviceIdleController != null) {
1030 if (!mReportedActive) {
1031 mReportedActive = true;
1032 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001033 }
1034 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001035 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001036 }
1037 }
1038 }
1039 }
1040
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001041 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001042 // active is true if pending queue contains jobs OR some job is running.
1043 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001044 if (mPendingJobs.size() <= 0) {
1045 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001046 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001047 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001048 if (job != null
1049 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
1050 && !job.dozeWhitelisted) {
1051 // We will report active if we have a job running and it is not an exception
1052 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001053 active = true;
1054 break;
1055 }
1056 }
1057 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001058
1059 if (mReportedActive != active) {
1060 mReportedActive = active;
1061 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001062 mLocalDeviceIdleController.setJobsActive(active);
1063 }
1064 }
1065 }
1066
Christopher Tated117b292018-01-05 17:32:36 -08001067 void reportAppUsage(String packageName, int userId) {
1068 // This app just transitioned into interactive use or near equivalent, so we should
1069 // take a look at its job state for feedback purposes.
1070 }
1071
Christopher Tate7060b042014-06-09 19:50:00 -07001072 /**
1073 * Initializes the system service.
1074 * <p>
1075 * Subclasses must define a single argument constructor that accepts the context
1076 * and passes it to super.
1077 * </p>
1078 *
1079 * @param context The system server context.
1080 */
1081 public JobSchedulerService(Context context) {
1082 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001083
1084 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Makoto Onuki15407842018-01-19 14:23:11 -08001085 mActivityManagerInternal = Preconditions.checkNotNull(
1086 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001087
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001088 mHandler = new JobHandler(context.getMainLooper());
1089 mConstants = new Constants(mHandler);
1090 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001091
1092 // Set up the app standby bucketing tracker
1093 UsageStatsManagerInternal usageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1094 mStandbyTracker = new StandbyTracker(usageStats);
1095 usageStats.addAppIdleStateChangeListener(mStandbyTracker);
1096
1097 // The job store needs to call back
1098 publishLocalService(JobSchedulerInternal.class, new LocalService());
1099
1100 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001101 mJobs = JobStore.initAndGet(this);
1102
Christopher Tate7060b042014-06-09 19:50:00 -07001103 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001104 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -07001105 mControllers.add(ConnectivityController.get(this));
1106 mControllers.add(TimeController.get(this));
1107 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001108 mBatteryController = BatteryController.get(this);
1109 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001110 mStorageController = StorageController.get(this);
1111 mControllers.add(mStorageController);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001112 mControllers.add(BackgroundJobsController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -08001113 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001114 mControllers.add(ContentObserverController.get(this));
Suprabh Shukla106203b2017-11-02 21:23:44 -07001115 mDeviceIdleJobsController = DeviceIdleJobsController.get(this);
1116 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001117
1118 // If the job store determined that it can't yet reschedule persisted jobs,
1119 // we need to start watching the clock.
1120 if (!mJobs.jobTimesInflatedValid()) {
1121 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1122 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1123 }
Christopher Tate7060b042014-06-09 19:50:00 -07001124 }
1125
Christopher Tate616541d2017-07-26 14:27:38 -07001126 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1127 @Override
1128 public void onReceive(Context context, Intent intent) {
1129 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1130 // When we reach clock sanity, recalculate the temporal windows
1131 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001132 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001133 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1134
1135 // We've done our job now, so stop watching the time.
1136 context.unregisterReceiver(this);
1137
1138 // And kick off the work to update the affected jobs, using a secondary
1139 // thread instead of chugging away here on the main looper thread.
1140 FgThread.getHandler().post(mJobTimeUpdater);
1141 }
1142 }
1143 }
1144 };
1145
1146 private final Runnable mJobTimeUpdater = () -> {
1147 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1148 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1149 synchronized (mLock) {
1150 // Note: we intentionally both look up the existing affected jobs and replace them
1151 // with recalculated ones inside the same lock lifetime.
1152 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1153
1154 // Now, at each position [i], we have both the existing JobStatus
1155 // and the one that replaces it.
1156 final int N = toAdd.size();
1157 for (int i = 0; i < N; i++) {
1158 final JobStatus oldJob = toRemove.get(i);
1159 final JobStatus newJob = toAdd.get(i);
1160 if (DEBUG) {
1161 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1162 }
1163 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1164 }
1165 }
1166 };
1167
Christopher Tate7060b042014-06-09 19:50:00 -07001168 @Override
1169 public void onStart() {
1170 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1171 }
1172
1173 @Override
1174 public void onBootPhase(int phase) {
1175 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001176 mConstants.start(getContext().getContentResolver());
Makoto Onuki15407842018-01-19 14:23:11 -08001177
Makoto Onukie4918212018-02-06 11:30:15 -08001178 mAppStateTracker = Preconditions.checkNotNull(
1179 LocalServices.getService(AppStateTracker.class));
Makoto Onuki15407842018-01-19 14:23:11 -08001180
Shreyas Basarge5db09082016-01-07 13:38:29 +00001181 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001182 final IntentFilter filter = new IntentFilter();
1183 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1184 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001185 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1186 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001187 filter.addDataScheme("package");
1188 getContext().registerReceiverAsUser(
1189 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1190 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1191 getContext().registerReceiverAsUser(
1192 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001193 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001194 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001195 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001196 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1197 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001198 } catch (RemoteException e) {
1199 // ignored; both services live in system_server
1200 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001201 // Remove any jobs that are not associated with any of the current users.
1202 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001203 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001204 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001205 // Let's go!
1206 mReadyToRock = true;
1207 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1208 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001209 mLocalDeviceIdleController
1210 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001211 // Create the "runners".
1212 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1213 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001214 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001215 getContext().getMainLooper()));
1216 }
1217 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001218 mJobs.forEachJob(new JobStatusFunctor() {
1219 @Override
1220 public void process(JobStatus job) {
1221 for (int controller = 0; controller < mControllers.size(); controller++) {
1222 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001223 sc.maybeStartTrackingJobLocked(job, null);
1224 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001225 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001226 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001227 // GO GO GO!
1228 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1229 }
Christopher Tate7060b042014-06-09 19:50:00 -07001230 }
1231 }
1232
1233 /**
1234 * Called when we have a job status object that we need to insert in our
1235 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1236 * about.
1237 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001238 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1239 if (!jobStatus.isPreparedLocked()) {
1240 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1241 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001242 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001243 final boolean update = mJobs.add(jobStatus);
1244 if (mReadyToRock) {
1245 for (int i = 0; i < mControllers.size(); i++) {
1246 StateController controller = mControllers.get(i);
1247 if (update) {
1248 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001249 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001250 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001251 }
Christopher Tate7060b042014-06-09 19:50:00 -07001252 }
1253 }
1254
1255 /**
1256 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1257 * object removed.
1258 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001259 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001260 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001261 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001262 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001263
1264 // Remove from store as well as controllers.
1265 final boolean removed = mJobs.remove(jobStatus, writeBack);
1266 if (removed && mReadyToRock) {
1267 for (int i=0; i<mControllers.size(); i++) {
1268 StateController controller = mControllers.get(i);
1269 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001270 }
1271 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001272 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001273 }
1274
Dianne Hackborn729a3282017-06-09 16:06:01 -07001275 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001276 for (int i=0; i<mActiveServices.size(); i++) {
1277 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001278 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001279 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001280 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001281 return true;
1282 }
1283 }
1284 return false;
1285 }
1286
1287 /**
1288 * @param job JobStatus we are querying against.
1289 * @return Whether or not the job represented by the status object is currently being run or
1290 * is pending.
1291 */
1292 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001293 for (int i=0; i<mActiveServices.size(); i++) {
1294 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001295 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001296 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1297 return true;
1298 }
1299 }
1300 return false;
1301 }
1302
Dianne Hackborn807de782016-04-07 17:54:41 -07001303 void noteJobsPending(List<JobStatus> jobs) {
1304 for (int i = jobs.size() - 1; i >= 0; i--) {
1305 JobStatus job = jobs.get(i);
1306 mJobPackageTracker.notePending(job);
1307 }
1308 }
1309
1310 void noteJobsNonpending(List<JobStatus> jobs) {
1311 for (int i = jobs.size() - 1; i >= 0; i--) {
1312 JobStatus job = jobs.get(i);
1313 mJobPackageTracker.noteNonpending(job);
1314 }
1315 }
1316
Christopher Tate7060b042014-06-09 19:50:00 -07001317 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001318 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1319 * specify an override deadline on a failed job (the failed job will run even though it's not
1320 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1321 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1322 *
Christopher Tate7060b042014-06-09 19:50:00 -07001323 * @param failureToReschedule Provided job status that we will reschedule.
1324 * @return A newly instantiated JobStatus with the same constraints as the last job except
1325 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001326 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001327 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001328 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001329 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001330 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001331 final JobInfo job = failureToReschedule.getJob();
1332
1333 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001334 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1335 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001336
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001337 if (failureToReschedule.hasWorkLocked()) {
1338 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1339 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1340 + backoffAttempts + " > work limit "
1341 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1342 return null;
1343 }
1344 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1345 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1346 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1347 return null;
1348 }
1349
Christopher Tate7060b042014-06-09 19:50:00 -07001350 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001351 case JobInfo.BACKOFF_POLICY_LINEAR: {
1352 long backoff = initialBackoffMillis;
1353 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1354 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1355 }
1356 delayMillis = backoff * backoffAttempts;
1357 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001358 default:
1359 if (DEBUG) {
1360 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1361 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001362 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1363 long backoff = initialBackoffMillis;
1364 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1365 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1366 }
1367 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1368 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001369 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001370 delayMillis =
1371 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001372 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1373 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001374 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001375 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001376 for (int ic=0; ic<mControllers.size(); ic++) {
1377 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001378 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001379 }
1380 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001381 }
1382
1383 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001384 * Called after a periodic has executed so we can reschedule it. We take the last execution
1385 * time of the job to be the time of completion (i.e. the time at which this function is
1386 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001387 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001388 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1389 * to underscheduling at least, rather than if we had taken the last execution time to be the
1390 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001391 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1392 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001393 * @return A new job representing the execution criteria for this instantiation of the
1394 * recurring job.
1395 */
1396 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001397 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001398 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001399 long runEarly = 0L;
1400
1401 // If this periodic was rescheduled it won't have a deadline.
1402 if (periodicToReschedule.hasDeadlineConstraint()) {
1403 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1404 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001405 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001406 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001407 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1408 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001409
1410 if (DEBUG) {
1411 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1412 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1413 }
Christopher Tatea732f012017-10-26 17:26:53 -07001414 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1415 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1416 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001417 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001418 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001419 }
1420
1421 // JobCompletedListener implementations.
1422
1423 /**
1424 * A job just finished executing. We fetch the
1425 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1426 * whether we want to reschedule we readd it to the controllers.
1427 * @param jobStatus Completed job.
1428 * @param needsReschedule Whether the implementing class should reschedule this job.
1429 */
1430 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001431 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001432 if (DEBUG) {
1433 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1434 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001435
1436 // If the job wants to be rescheduled, we first need to make the next upcoming
1437 // job so we can transfer any appropriate state over from the previous job when
1438 // we stop it.
1439 final JobStatus rescheduledJob = needsReschedule
1440 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1441
Shreyas Basarge73f10252016-02-11 17:06:13 +00001442 // Do not write back immediately if this is a periodic job. The job may get lost if system
1443 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001444 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001445 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001446 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001447 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001448 // We still want to check for jobs to execute, because this job may have
1449 // scheduled a new job under the same job id, and now we can run it.
1450 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001451 return;
1452 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001453
1454 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001455 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001456 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001457 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001458 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001459 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001460 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001461 } else if (jobStatus.getJob().isPeriodic()) {
1462 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001463 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001464 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001465 } catch (SecurityException e) {
1466 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1467 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001468 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001469 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001470 jobStatus.unprepareLocked(ActivityManager.getService());
1471 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001472 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001473 }
1474
1475 // StateChangedListener implementations.
1476
1477 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001478 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1479 * some controller's state has changed, so as to run through the list of jobs and start/stop
1480 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001481 */
1482 @Override
1483 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001484 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001485 }
1486
1487 @Override
1488 public void onRunJobNow(JobStatus jobStatus) {
1489 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1490 }
1491
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001492 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001493
1494 public JobHandler(Looper looper) {
1495 super(looper);
1496 }
1497
1498 @Override
1499 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001500 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001501 if (!mReadyToRock) {
1502 return;
1503 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001504 switch (message.what) {
1505 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001506 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001507 // runNow can be null, which is a controller's way of indicating that its
1508 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001509 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001510 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001511 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001512 } else {
1513 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001514 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001515 } break;
1516 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001517 if (mReportedActive) {
1518 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001519 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001520 } else {
1521 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001522 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001523 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001524 break;
1525 case MSG_CHECK_JOB_GREEDY:
1526 queueReadyJobsForExecutionLocked();
1527 break;
1528 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001529 cancelJobImplLocked((JobStatus) message.obj, null,
1530 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001531 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001532 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001533 maybeRunPendingJobsLocked();
1534 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1535 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001536 }
1537 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001538 }
Christopher Tate7060b042014-06-09 19:50:00 -07001539
Dianne Hackborn6d068262017-05-16 13:14:37 -07001540 private void stopNonReadyActiveJobsLocked() {
1541 for (int i=0; i<mActiveServices.size(); i++) {
1542 JobServiceContext serviceContext = mActiveServices.get(i);
1543 final JobStatus running = serviceContext.getRunningJobLocked();
1544 if (running != null && !running.isReady()) {
1545 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001546 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1547 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001548 }
1549 }
1550 }
1551
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001552 /**
1553 * Run through list of jobs and execute all possible - at least one is expired so we do
1554 * as many as we can.
1555 */
1556 private void queueReadyJobsForExecutionLocked() {
1557 if (DEBUG) {
1558 Slog.d(TAG, "queuing all ready jobs for execution:");
1559 }
1560 noteJobsNonpending(mPendingJobs);
1561 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001562 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001563 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001564 mJobs.forEachJob(mReadyQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001565 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001566 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001567
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001568 if (DEBUG) {
1569 final int queuedJobs = mPendingJobs.size();
1570 if (queuedJobs == 0) {
1571 Slog.d(TAG, "No jobs pending.");
1572 } else {
1573 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001574 }
1575 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001576 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001577
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001578 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1579 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001580
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001581 @Override
1582 public void process(JobStatus job) {
1583 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001584 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001585 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001586 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001587 if (newReadyJobs == null) {
1588 newReadyJobs = new ArrayList<JobStatus>();
1589 }
1590 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001591 }
1592 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001593
1594 public void postProcess() {
1595 if (newReadyJobs != null) {
1596 noteJobsPending(newReadyJobs);
1597 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001598 if (mPendingJobs.size() > 1) {
1599 mPendingJobs.sort(mEnqueueTimeComparator);
1600 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001601 }
1602 newReadyJobs = null;
1603 }
1604 }
1605 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1606
1607 /**
1608 * The state of at least one job has changed. Here is where we could enforce various
1609 * policies on when we want to execute jobs.
1610 * Right now the policy is such:
1611 * If >1 of the ready jobs is idle mode we send all of them off
1612 * if more than 2 network connectivity jobs are ready we send them all off.
1613 * If more than 4 jobs total are ready we send them all off.
1614 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1615 */
1616 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1617 int chargingCount;
1618 int batteryNotLowCount;
1619 int storageNotLowCount;
1620 int idleCount;
1621 int backoffCount;
1622 int connectivityCount;
1623 int contentCount;
1624 List<JobStatus> runnableJobs;
1625
1626 public MaybeReadyJobQueueFunctor() {
1627 reset();
1628 }
1629
1630 // Functor method invoked for each job via JobStore.forEachJob()
1631 @Override
1632 public void process(JobStatus job) {
1633 if (isReadyToBeExecutedLocked(job)) {
1634 try {
1635 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1636 job.getJob().getService().getPackageName())) {
1637 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1638 + job.getJob().toString() + " -- package not allowed to start");
1639 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1640 return;
1641 }
1642 } catch (RemoteException e) {
1643 }
1644 if (job.getNumFailures() > 0) {
1645 backoffCount++;
1646 }
1647 if (job.hasIdleConstraint()) {
1648 idleCount++;
1649 }
1650 if (job.hasConnectivityConstraint()) {
1651 connectivityCount++;
1652 }
1653 if (job.hasChargingConstraint()) {
1654 chargingCount++;
1655 }
1656 if (job.hasBatteryNotLowConstraint()) {
1657 batteryNotLowCount++;
1658 }
1659 if (job.hasStorageNotLowConstraint()) {
1660 storageNotLowCount++;
1661 }
1662 if (job.hasContentTriggerConstraint()) {
1663 contentCount++;
1664 }
1665 if (runnableJobs == null) {
1666 runnableJobs = new ArrayList<>();
1667 }
1668 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001669 }
1670 }
1671
1672 public void postProcess() {
1673 if (backoffCount > 0 ||
1674 idleCount >= mConstants.MIN_IDLE_COUNT ||
1675 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1676 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1677 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1678 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1679 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1680 (runnableJobs != null
1681 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1682 if (DEBUG) {
1683 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1684 }
1685 noteJobsPending(runnableJobs);
1686 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001687 if (mPendingJobs.size() > 1) {
1688 mPendingJobs.sort(mEnqueueTimeComparator);
1689 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001690 } else {
1691 if (DEBUG) {
1692 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1693 }
1694 }
1695
1696 // Be ready for next time
1697 reset();
1698 }
1699
1700 private void reset() {
1701 chargingCount = 0;
1702 idleCount = 0;
1703 backoffCount = 0;
1704 connectivityCount = 0;
1705 batteryNotLowCount = 0;
1706 storageNotLowCount = 0;
1707 contentCount = 0;
1708 runnableJobs = null;
1709 }
1710 }
1711 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1712
1713 private void maybeQueueReadyJobsForExecutionLocked() {
1714 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1715
1716 noteJobsNonpending(mPendingJobs);
1717 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001718 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001719 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001720 mJobs.forEachJob(mMaybeQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001721 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001722 mMaybeQueueFunctor.postProcess();
1723 }
1724
Christopher Tatea732f012017-10-26 17:26:53 -07001725 private boolean updateStandbyHeartbeatLocked() {
1726 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1727 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1728 if (beatsElapsed > 0) {
1729 mHeartbeat += beatsElapsed;
1730 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1731 if (DEBUG_STANDBY) {
1732 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed + " to " + mHeartbeat);
1733 }
1734 return true;
1735 }
1736 return false;
1737 }
1738
1739 private void updateNextStandbyHeartbeatsLocked() {
1740 // don't update ACTIVE or NEVER bucket milestones
1741 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
1742 while (mHeartbeat >= mNextBucketHeartbeat[i]) {
1743 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1744 }
1745 if (DEBUG_STANDBY) {
1746 Slog.v(TAG, " Bucket " + i + " next heartbeat " + mNextBucketHeartbeat[i]);
1747 }
1748 }
1749 }
1750
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001751 /**
1752 * Criteria for moving a job into the pending queue:
1753 * - It's ready.
1754 * - It's not pending.
1755 * - It's not already running on a JSC.
1756 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001757 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001758 * - The component is enabled and runnable.
1759 */
1760 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001761 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001762
1763 if (DEBUG) {
1764 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1765 + " ready=" + jobReady);
1766 }
1767
1768 // This is a condition that is very likely to be false (most jobs that are
1769 // scheduled are sitting there, not ready yet) and very cheap to check (just
1770 // a few conditions on data in JobStatus).
1771 if (!jobReady) {
1772 return false;
1773 }
1774
1775 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001776
1777 final int userId = job.getUserId();
1778 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1779
1780 if (DEBUG) {
1781 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001782 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001783 }
1784
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001785 // These are also fairly cheap to check, though they typically will not
1786 // be conditions we fail.
1787 if (!jobExists || !userStarted) {
1788 return false;
1789 }
1790
1791 final boolean jobPending = mPendingJobs.contains(job);
1792 final boolean jobActive = isCurrentlyActiveLocked(job);
1793
1794 if (DEBUG) {
1795 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1796 + " pending=" + jobPending + " active=" + jobActive);
1797 }
1798
1799 // These can be a little more expensive (especially jobActive, since we need to
1800 // go through the array of all potentially active jobs), so we are doing them
1801 // later... but still before checking with the package manager!
1802 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001803 return false;
1804 }
1805
Christopher Tatea732f012017-10-26 17:26:53 -07001806 // If the app is in a non-active standby bucket, make sure we've waited
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001807 // an appropriate amount of time since the last invocation. During device-
1808 // wide parole, standby bucketing is ignored.
Makoto Onuki959acb52018-01-26 14:10:03 -08001809 //
1810 // But if a job has FLAG_EXEMPT_FROM_APP_STANDBY, don't check it.
1811 if (!mInParole && !job.getJob().isExemptedFromAppStandby()) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001812 final int bucket = job.getStandbyBucket();
1813 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
1814 // Only skip this job if it's still waiting for the end of its (initial) nominal
1815 // bucket interval. Once it's waited that long, we let it go ahead and clear.
1816 // The final (NEVER) bucket is special; we never age those apps' jobs into
1817 // runnability.
1818 if (bucket >= mConstants.STANDBY_BEATS.length
1819 || (mHeartbeat < job.getBaseHeartbeat() + mConstants.STANDBY_BEATS[bucket])) {
1820 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
1821 if (job.getWhenStandbyDeferred() == 0) {
1822 if (DEBUG_STANDBY) {
1823 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
1824 + mNextBucketHeartbeat[job.getStandbyBucket()] + " for " + job);
1825 }
1826 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tate0c4d7682017-12-06 15:10:22 -08001827 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001828 return false;
1829 } else {
1830 if (DEBUG_STANDBY) {
1831 Slog.v(TAG, "Bucket deferred job aged into runnability at "
1832 + mHeartbeat + " : " + job);
1833 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08001834 }
Christopher Tatea732f012017-10-26 17:26:53 -07001835 }
Christopher Tatea732f012017-10-26 17:26:53 -07001836 }
1837
1838 // The expensive check last: validate that the defined package+service is
1839 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001840 final boolean componentPresent;
1841 try {
1842 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1843 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1844 userId) != null);
1845 } catch (RemoteException e) {
1846 throw e.rethrowAsRuntimeException();
1847 }
1848
1849 if (DEBUG) {
1850 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1851 + " componentPresent=" + componentPresent);
1852 }
1853
1854 // Everything else checked out so far, so this is the final yes/no check
1855 return componentPresent;
1856 }
1857
1858 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001859 * Reconcile jobs in the pending queue against available execution contexts.
1860 * A controller can force a job into the pending queue even if it's already running, but
1861 * here is where we decide whether to actually execute it.
1862 */
1863 private void maybeRunPendingJobsLocked() {
1864 if (DEBUG) {
1865 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1866 }
1867 assignJobsToContextsLocked();
1868 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001869 }
1870
Dianne Hackborn807de782016-04-07 17:54:41 -07001871 private int adjustJobPriority(int curPriority, JobStatus job) {
1872 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1873 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001874 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001875 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001876 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001877 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1878 }
1879 }
1880 return curPriority;
1881 }
1882
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001883 private int evaluateJobPriorityLocked(JobStatus job) {
1884 int priority = job.getPriority();
1885 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001886 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001887 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001888 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1889 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001890 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001891 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001892 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001893 }
1894
Christopher Tate7060b042014-06-09 19:50:00 -07001895 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001896 * Takes jobs from pending queue and runs them on available contexts.
1897 * If no contexts are available, preempts lower priority jobs to
1898 * run higher priority ones.
1899 * Lock on mJobs before calling this function.
1900 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001901 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001902 if (DEBUG) {
1903 Slog.d(TAG, printPendingQueue());
1904 }
1905
Dianne Hackborn970510b2016-02-24 16:56:42 -08001906 int memLevel;
1907 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001908 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001909 } catch (RemoteException e) {
1910 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1911 }
1912 switch (memLevel) {
1913 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001914 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001915 break;
1916 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001917 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001918 break;
1919 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001920 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001921 break;
1922 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001923 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001924 break;
1925 }
1926
1927 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1928 boolean[] act = mTmpAssignAct;
1929 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1930 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001931 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001932 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1933 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001934 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001935 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001936 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001937 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1938 numForeground++;
1939 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001940 }
1941 act[i] = false;
1942 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001943 }
1944 if (DEBUG) {
1945 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1946 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001947 for (int i=0; i<mPendingJobs.size(); i++) {
1948 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001949
1950 // If job is already running, go to next job.
1951 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1952 if (jobRunningContext != -1) {
1953 continue;
1954 }
1955
Dianne Hackborn970510b2016-02-24 16:56:42 -08001956 final int priority = evaluateJobPriorityLocked(nextPending);
1957 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001958
Shreyas Basarge5db09082016-01-07 13:38:29 +00001959 // Find a context for nextPending. The context should be available OR
1960 // it should have lowest priority among all running jobs
1961 // (sharing the same Uid as nextPending)
1962 int minPriority = Integer.MAX_VALUE;
1963 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001964 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1965 JobStatus job = contextIdToJobMap[j];
1966 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001967 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001968 if ((numActive < mMaxActiveJobs ||
1969 (priority >= JobInfo.PRIORITY_TOP_APP &&
1970 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001971 (preferredUid == nextPending.getUid() ||
1972 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1973 // This slot is free, and we haven't yet hit the limit on
1974 // concurrent jobs... we can just throw the job in to here.
1975 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001976 break;
1977 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001978 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001979 // the context has a preferred Uid or we have reached the limit on
1980 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001981 continue;
1982 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001983 if (job.getUid() != nextPending.getUid()) {
1984 continue;
1985 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001986 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001987 continue;
1988 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001989 if (minPriority > nextPending.lastEvaluatedPriority) {
1990 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001991 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001992 }
1993 }
1994 if (minPriorityContextId != -1) {
1995 contextIdToJobMap[minPriorityContextId] = nextPending;
1996 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001997 numActive++;
1998 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1999 numForeground++;
2000 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002001 }
2002 }
2003 if (DEBUG) {
2004 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
2005 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002006 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002007 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002008 boolean preservePreferredUid = false;
2009 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002010 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002011 if (js != null) {
2012 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002013 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00002014 }
2015 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07002016 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002017 preservePreferredUid = true;
2018 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002019 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00002020 if (DEBUG) {
2021 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002022 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002023 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002024 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002025 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002026 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002027 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
2028 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002029 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002030 if (mPendingJobs.remove(pendingJob)) {
2031 mJobPackageTracker.noteNonpending(pendingJob);
2032 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002033 }
2034 }
2035 if (!preservePreferredUid) {
2036 mActiveServices.get(i).clearPreferredUid();
2037 }
2038 }
2039 }
2040
2041 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
2042 for (int i=0; i<map.length; i++) {
2043 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
2044 return i;
2045 }
2046 }
2047 return -1;
2048 }
2049
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002050 final class LocalService implements JobSchedulerInternal {
2051
2052 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002053 * The current bucket heartbeat ordinal
2054 */
2055 public long currentHeartbeat() {
2056 return getCurrentHeartbeat();
2057 }
2058
2059 /**
2060 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2061 */
2062 public long nextHeartbeatForBucket(int bucket) {
2063 synchronized (mLock) {
2064 return mNextBucketHeartbeat[bucket];
2065 }
2066 }
2067
2068 /**
Christopher Tate435c2f42018-01-18 12:59:15 -08002069 * Heartbeat ordinal for the given app. This is typically the heartbeat at which
2070 * the app last ran jobs, so that a newly-scheduled job in an app that hasn't run
2071 * jobs in a long time is immediately runnable even if the app is bucketed into
2072 * an infrequent time allocation.
2073 */
2074 public long baseHeartbeatForApp(String packageName, @UserIdInt int userId,
2075 final int appStandbyBucket) {
2076 if (appStandbyBucket == 0 ||
2077 appStandbyBucket >= mConstants.STANDBY_BEATS.length) {
2078 // ACTIVE => everything can be run right away
2079 // NEVER => we won't run them anyway, so let them go in the future
2080 // as soon as the app enters normal use
2081 return 0;
2082 }
2083
2084 final long timeSinceLastJob = mStandbyTracker.getTimeSinceLastJobRun(
2085 packageName, userId);
2086 final long bucketLength = mConstants.STANDBY_BEATS[appStandbyBucket];
2087 final long bucketsAgo = timeSinceLastJob / bucketLength;
2088
2089 // If we haven't run any jobs for more than the app's current bucket period, just
2090 // consider anything new to be immediately runnable. Otherwise, base it on the
2091 // bucket at which we last ran jobs.
2092 return (bucketsAgo > bucketLength) ? 0 : (getCurrentHeartbeat() - bucketsAgo);
2093 }
2094
2095 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002096 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2097 * jobs are always considered pending.
2098 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002099 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002100 public List<JobInfo> getSystemScheduledPendingJobs() {
2101 synchronized (mLock) {
2102 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
2103 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
2104 @Override
2105 public void process(JobStatus job) {
2106 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2107 pendingJobs.add(job.getJob());
2108 }
2109 }
2110 });
2111 return pendingJobs;
2112 }
2113 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002114
2115 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002116 public void cancelJobsForUid(int uid, String reason) {
2117 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2118 }
2119
2120 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002121 public void addBackingUpUid(int uid) {
2122 synchronized (mLock) {
2123 // No need to actually do anything here, since for a full backup the
2124 // activity manager will kill the process which will kill the job (and
2125 // cause it to restart, but now it can't run).
2126 mBackingUpUids.put(uid, uid);
2127 }
2128 }
2129
2130 @Override
2131 public void removeBackingUpUid(int uid) {
2132 synchronized (mLock) {
2133 mBackingUpUids.delete(uid);
2134 // If there are any jobs for this uid, we need to rebuild the pending list
2135 // in case they are now ready to run.
2136 if (mJobs.countJobsForUid(uid) > 0) {
2137 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2138 }
2139 }
2140 }
2141
2142 @Override
2143 public void clearAllBackingUpUids() {
2144 synchronized (mLock) {
2145 if (mBackingUpUids.size() > 0) {
2146 mBackingUpUids.clear();
2147 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2148 }
2149 }
2150 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002151
2152 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002153 public void reportAppUsage(String packageName, int userId) {
2154 JobSchedulerService.this.reportAppUsage(packageName, userId);
2155 }
2156
2157 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002158 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002159 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002160 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002161 }
2162 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002163 }
2164
Shreyas Basarge5db09082016-01-07 13:38:29 +00002165 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002166 * Tracking of app assignments to standby buckets
2167 */
2168 final class StandbyTracker extends AppIdleStateChangeListener {
2169 final UsageStatsManagerInternal mUsageStats;
2170
2171 StandbyTracker(UsageStatsManagerInternal usageStats) {
2172 mUsageStats = usageStats;
2173 }
2174
Christopher Tate435c2f42018-01-18 12:59:15 -08002175 public long getTimeSinceLastJobRun(String packageName, final @UserIdInt int userId) {
2176 return mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2177 }
2178
Christopher Tatea732f012017-10-26 17:26:53 -07002179 // AppIdleStateChangeListener interface for live updates
2180
2181 @Override
Christopher Tate435c2f42018-01-18 12:59:15 -08002182 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Christopher Tatea732f012017-10-26 17:26:53 -07002183 boolean idle, int bucket) {
2184 final int uid = mLocalPM.getPackageUid(packageName,
2185 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2186 if (uid < 0) {
2187 if (DEBUG_STANDBY) {
2188 Slog.i(TAG, "App idle state change for unknown app "
2189 + packageName + "/" + userId);
2190 }
2191 return;
2192 }
2193
2194 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2195 // update job bookkeeping out of band
2196 BackgroundThread.getHandler().post(() -> {
2197 if (DEBUG_STANDBY) {
2198 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2199 }
2200 synchronized (mLock) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08002201 mJobs.forEachJobForSourceUid(uid, job -> job.setStandbyBucket(bucketIndex));
Christopher Tatea732f012017-10-26 17:26:53 -07002202 onControllerStateChanged();
2203 }
2204 });
2205 }
2206
2207 @Override
2208 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002209 if (DEBUG_STANDBY) {
2210 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2211 }
2212 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002213 }
Christopher Tated117b292018-01-05 17:32:36 -08002214
2215 @Override
2216 public void onUserInteractionStarted(String packageName, int userId) {
2217 final int uid = mLocalPM.getPackageUid(packageName,
2218 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2219 if (uid < 0) {
2220 // Quietly ignore; the case is already logged elsewhere
2221 return;
2222 }
2223
2224 final long sinceLast = sElapsedRealtimeClock.millis() -
2225 mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2226 final DeferredJobCounter counter = new DeferredJobCounter();
2227 synchronized (mLock) {
2228 mJobs.forEachJobForSourceUid(uid, counter);
2229 }
2230
2231 mUsageStats.reportAppJobState(packageName, userId, counter.numDeferred(), sinceLast);
2232 }
2233 }
2234
2235 static class DeferredJobCounter implements JobStatusFunctor {
2236 private int mDeferred = 0;
2237
2238 public int numDeferred() {
2239 return mDeferred;
2240 }
2241
2242 @Override
2243 public void process(JobStatus job) {
2244 if (job.getWhenStandbyDeferred() > 0) {
2245 mDeferred++;
2246 }
2247 }
Christopher Tatea732f012017-10-26 17:26:53 -07002248 }
2249
2250 public static int standbyBucketToBucketIndex(int bucket) {
2251 // Normalize AppStandby constants to indices into our bookkeeping
Amith Yamasaniafbccb72017-11-27 10:44:24 -08002252 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return 4;
2253 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) return 3;
2254 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) return 2;
2255 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return 1;
Christopher Tatea732f012017-10-26 17:26:53 -07002256 else return 0;
2257 }
2258
2259 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2260 UsageStatsManagerInternal usageStats = LocalServices.getService(
2261 UsageStatsManagerInternal.class);
2262 int bucket = usageStats != null
2263 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2264 : 0;
2265
2266 bucket = standbyBucketToBucketIndex(bucket);
2267
2268 if (DEBUG_STANDBY) {
2269 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2270 }
2271 return bucket;
2272 }
2273
2274 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002275 * Binder stub trampoline implementation
2276 */
2277 final class JobSchedulerStub extends IJobScheduler.Stub {
2278 /** Cache determination of whether a given app can persist jobs
2279 * key is uid of the calling app; value is undetermined/true/false
2280 */
2281 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2282
2283 // Enforce that only the app itself (or shared uid participant) can schedule a
2284 // job that runs one of the app's services, as well as verifying that the
2285 // named service properly requires the BIND_JOB_SERVICE permission
2286 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002287 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002288 final ComponentName service = job.getService();
2289 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002290 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002291 PackageManager.MATCH_DIRECT_BOOT_AWARE
2292 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002293 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002294 if (si == null) {
2295 throw new IllegalArgumentException("No such service " + service);
2296 }
Christopher Tate7060b042014-06-09 19:50:00 -07002297 if (si.applicationInfo.uid != uid) {
2298 throw new IllegalArgumentException("uid " + uid +
2299 " cannot schedule job in " + service.getPackageName());
2300 }
2301 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2302 throw new IllegalArgumentException("Scheduled service " + service
2303 + " does not require android.permission.BIND_JOB_SERVICE permission");
2304 }
Christopher Tate5568f542014-06-18 13:53:31 -07002305 } catch (RemoteException e) {
2306 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002307 }
2308 }
2309
2310 private boolean canPersistJobs(int pid, int uid) {
2311 // If we get this far we're good to go; all we need to do now is check
2312 // whether the app is allowed to persist its scheduled work.
2313 final boolean canPersist;
2314 synchronized (mPersistCache) {
2315 Boolean cached = mPersistCache.get(uid);
2316 if (cached != null) {
2317 canPersist = cached.booleanValue();
2318 } else {
2319 // Persisting jobs is tantamount to running at boot, so we permit
2320 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2321 // permission
2322 int result = getContext().checkPermission(
2323 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2324 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2325 mPersistCache.put(uid, canPersist);
2326 }
2327 }
2328 return canPersist;
2329 }
2330
Makoto Onuki959acb52018-01-26 14:10:03 -08002331 private void validateJobFlags(JobInfo job, int callingUid) {
2332 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2333 getContext().enforceCallingOrSelfPermission(
2334 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2335 }
2336 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
2337 if (callingUid != Process.SYSTEM_UID) {
2338 throw new SecurityException("Job has invalid flags");
2339 }
2340 if (job.hasLateConstraint() || job.hasEarlyConstraint()) {
2341 Slog.wtf(TAG, "Jobs with time-constraints mustn't have"
2342 +" FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
2343 }
2344 }
2345 }
2346
Christopher Tate7060b042014-06-09 19:50:00 -07002347 // IJobScheduler implementation
2348 @Override
2349 public int schedule(JobInfo job) throws RemoteException {
2350 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002351 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002352 }
2353 final int pid = Binder.getCallingPid();
2354 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002355 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002356
2357 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002358 if (job.isPersisted()) {
2359 if (!canPersistJobs(pid, uid)) {
2360 throw new IllegalArgumentException("Error: requested job be persisted without"
2361 + " holding RECEIVE_BOOT_COMPLETED permission.");
2362 }
2363 }
Christopher Tate7060b042014-06-09 19:50:00 -07002364
Makoto Onuki959acb52018-01-26 14:10:03 -08002365 validateJobFlags(job, uid);
Jeff Sharkey785f4942016-07-14 10:31:15 -06002366
Christopher Tate7060b042014-06-09 19:50:00 -07002367 long ident = Binder.clearCallingIdentity();
2368 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002369 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2370 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002371 } finally {
2372 Binder.restoreCallingIdentity(ident);
2373 }
2374 }
2375
2376 // IJobScheduler implementation
2377 @Override
2378 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2379 if (DEBUG) {
2380 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2381 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002382 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002383 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002384
2385 enforceValidJobRequest(uid, job);
2386 if (job.isPersisted()) {
2387 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2388 }
2389 if (work == null) {
2390 throw new NullPointerException("work is null");
2391 }
2392
Makoto Onuki959acb52018-01-26 14:10:03 -08002393 validateJobFlags(job, uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002394
2395 long ident = Binder.clearCallingIdentity();
2396 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002397 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2398 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002399 } finally {
2400 Binder.restoreCallingIdentity(ident);
2401 }
2402 }
2403
2404 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002405 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002406 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002407 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002408 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002409 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002410 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002411 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002412
2413 if (packageName == null) {
2414 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002415 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002416
2417 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2418 android.Manifest.permission.UPDATE_DEVICE_STATS);
2419 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2420 throw new SecurityException("Caller uid " + callerUid
2421 + " not permitted to schedule jobs for other apps");
2422 }
2423
Makoto Onuki959acb52018-01-26 14:10:03 -08002424 validateJobFlags(job, callerUid);
Jeff Sharkey4f100402016-05-03 17:44:23 -06002425
Shreyas Basarge968ac752016-01-11 23:09:26 +00002426 long ident = Binder.clearCallingIdentity();
2427 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002428 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002429 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002430 } finally {
2431 Binder.restoreCallingIdentity(ident);
2432 }
2433 }
2434
2435 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002436 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2437 final int uid = Binder.getCallingUid();
2438
2439 long ident = Binder.clearCallingIdentity();
2440 try {
2441 return JobSchedulerService.this.getPendingJobs(uid);
2442 } finally {
2443 Binder.restoreCallingIdentity(ident);
2444 }
2445 }
2446
2447 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002448 public JobInfo getPendingJob(int jobId) throws RemoteException {
2449 final int uid = Binder.getCallingUid();
2450
2451 long ident = Binder.clearCallingIdentity();
2452 try {
2453 return JobSchedulerService.this.getPendingJob(uid, jobId);
2454 } finally {
2455 Binder.restoreCallingIdentity(ident);
2456 }
2457 }
2458
2459 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002460 public void cancelAll() throws RemoteException {
2461 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002462 long ident = Binder.clearCallingIdentity();
2463 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002464 JobSchedulerService.this.cancelJobsForUid(uid,
2465 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002466 } finally {
2467 Binder.restoreCallingIdentity(ident);
2468 }
2469 }
2470
2471 @Override
2472 public void cancel(int jobId) throws RemoteException {
2473 final int uid = Binder.getCallingUid();
2474
2475 long ident = Binder.clearCallingIdentity();
2476 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002477 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002478 } finally {
2479 Binder.restoreCallingIdentity(ident);
2480 }
2481 }
2482
2483 /**
2484 * "dumpsys" infrastructure
2485 */
2486 @Override
2487 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002488 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002489
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002490 int filterUid = -1;
2491 boolean proto = false;
2492 if (!ArrayUtils.isEmpty(args)) {
2493 int opti = 0;
2494 while (opti < args.length) {
2495 String arg = args[opti];
2496 if ("-h".equals(arg)) {
2497 dumpHelp(pw);
2498 return;
2499 } else if ("-a".equals(arg)) {
2500 // Ignore, we always dump all.
2501 } else if ("--proto".equals(arg)) {
2502 proto = true;
2503 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2504 pw.println("Unknown option: " + arg);
2505 return;
2506 } else {
2507 break;
2508 }
2509 opti++;
2510 }
2511 if (opti < args.length) {
2512 String pkg = args[opti];
2513 try {
2514 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2515 PackageManager.MATCH_ANY_USER);
2516 } catch (NameNotFoundException ignored) {
2517 pw.println("Invalid package: " + pkg);
2518 return;
2519 }
2520 }
2521 }
2522
Christopher Tate7060b042014-06-09 19:50:00 -07002523 long identityToken = Binder.clearCallingIdentity();
2524 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002525 if (proto) {
2526 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2527 } else {
2528 JobSchedulerService.this.dumpInternal(pw, filterUid);
2529 }
Christopher Tate7060b042014-06-09 19:50:00 -07002530 } finally {
2531 Binder.restoreCallingIdentity(identityToken);
2532 }
2533 }
Christopher Tate5d346052016-03-08 12:56:08 -08002534
2535 @Override
2536 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002537 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002538 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002539 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002540 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002541 };
2542
Christopher Tate5d346052016-03-08 12:56:08 -08002543 // Shell command infrastructure: run the given job immediately
2544 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2545 if (DEBUG) {
2546 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2547 + " " + jobId + " f=" + force);
2548 }
2549
2550 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002551 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2552 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002553 if (uid < 0) {
2554 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2555 }
2556
2557 synchronized (mLock) {
2558 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2559 if (js == null) {
2560 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2561 }
2562
2563 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2564 if (!js.isConstraintsSatisfied()) {
2565 js.overrideState = 0;
2566 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2567 }
2568
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002569 queueReadyJobsForExecutionLocked();
2570 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002571 }
2572 } catch (RemoteException e) {
2573 // can't happen
2574 }
2575 return 0;
2576 }
2577
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002578 // Shell command infrastructure: immediately timeout currently executing jobs
2579 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2580 boolean hasJobId, int jobId) {
2581 if (DEBUG) {
2582 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2583 }
2584
2585 synchronized (mLock) {
2586 boolean foundSome = false;
2587 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002588 final JobServiceContext jc = mActiveServices.get(i);
2589 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002590 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002591 foundSome = true;
2592 pw.print("Timing out: ");
2593 js.printUniqueId(pw);
2594 pw.print(" ");
2595 pw.println(js.getServiceComponent().flattenToShortString());
2596 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002597 }
2598 if (!foundSome) {
2599 pw.println("No matching executing jobs found.");
2600 }
2601 }
2602 return 0;
2603 }
2604
Christopher Tate8c67d122017-09-29 16:54:26 -07002605 // Shell command infrastructure: cancel a scheduled job
2606 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2607 boolean hasJobId, int jobId) {
2608 if (DEBUG) {
2609 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2610 }
2611
2612 int pkgUid = -1;
2613 try {
2614 IPackageManager pm = AppGlobals.getPackageManager();
2615 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2616 } catch (RemoteException e) { /* can't happen */ }
2617
2618 if (pkgUid < 0) {
2619 pw.println("Package " + pkgName + " not found.");
2620 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2621 }
2622
2623 if (!hasJobId) {
2624 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2625 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2626 pw.println("No matching jobs found.");
2627 }
2628 } else {
2629 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002630 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002631 pw.println("No matching job found.");
2632 }
2633 }
2634
2635 return 0;
2636 }
2637
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002638 void setMonitorBattery(boolean enabled) {
2639 synchronized (mLock) {
2640 if (mBatteryController != null) {
2641 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2642 }
2643 }
2644 }
2645
2646 int getBatterySeq() {
2647 synchronized (mLock) {
2648 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2649 }
2650 }
2651
2652 boolean getBatteryCharging() {
2653 synchronized (mLock) {
2654 return mBatteryController != null
2655 ? mBatteryController.getTracker().isOnStablePower() : false;
2656 }
2657 }
2658
2659 boolean getBatteryNotLow() {
2660 synchronized (mLock) {
2661 return mBatteryController != null
2662 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2663 }
2664 }
2665
Dianne Hackborn532ea262017-03-17 17:50:55 -07002666 int getStorageSeq() {
2667 synchronized (mLock) {
2668 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2669 }
2670 }
2671
2672 boolean getStorageNotLow() {
2673 synchronized (mLock) {
2674 return mStorageController != null
2675 ? mStorageController.getTracker().isStorageNotLow() : false;
2676 }
2677 }
2678
Christopher Tatea732f012017-10-26 17:26:53 -07002679 long getCurrentHeartbeat() {
2680 synchronized (mLock) {
2681 return mHeartbeat;
2682 }
2683 }
2684
Dianne Hackborn6d068262017-05-16 13:14:37 -07002685 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2686 try {
2687 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2688 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2689 if (uid < 0) {
2690 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2691 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2692 }
2693
2694 synchronized (mLock) {
2695 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2696 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2697 if (js == null) {
2698 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2699 pw.print("/jid"); pw.print(jobId); pw.println(")");
2700 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2701 }
2702
2703 boolean printed = false;
2704 if (mPendingJobs.contains(js)) {
2705 pw.print("pending");
2706 printed = true;
2707 }
2708 if (isCurrentlyActiveLocked(js)) {
2709 if (printed) {
2710 pw.print(" ");
2711 }
2712 printed = true;
2713 pw.println("active");
2714 }
2715 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2716 if (printed) {
2717 pw.print(" ");
2718 }
2719 printed = true;
2720 pw.println("user-stopped");
2721 }
2722 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2723 if (printed) {
2724 pw.print(" ");
2725 }
2726 printed = true;
2727 pw.println("backing-up");
2728 }
2729 boolean componentPresent = false;
2730 try {
2731 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2732 js.getServiceComponent(),
2733 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2734 js.getUserId()) != null);
2735 } catch (RemoteException e) {
2736 }
2737 if (!componentPresent) {
2738 if (printed) {
2739 pw.print(" ");
2740 }
2741 printed = true;
2742 pw.println("no-component");
2743 }
2744 if (js.isReady()) {
2745 if (printed) {
2746 pw.print(" ");
2747 }
2748 printed = true;
2749 pw.println("ready");
2750 }
2751 if (!printed) {
2752 pw.print("waiting");
2753 }
2754 pw.println();
2755 }
2756 } catch (RemoteException e) {
2757 // can't happen
2758 }
2759 return 0;
2760 }
2761
Shreyas Basarge5db09082016-01-07 13:38:29 +00002762 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2763 StringBuilder s = new StringBuilder(initial + ": ");
2764 for (int i=0; i<map.length; i++) {
2765 s.append("(")
2766 .append(map[i] == null? -1: map[i].getJobId())
2767 .append(map[i] == null? -1: map[i].getUid())
2768 .append(")" );
2769 }
2770 return s.toString();
2771 }
2772
2773 private String printPendingQueue() {
2774 StringBuilder s = new StringBuilder("Pending queue: ");
2775 Iterator<JobStatus> it = mPendingJobs.iterator();
2776 while (it.hasNext()) {
2777 JobStatus js = it.next();
2778 s.append("(")
2779 .append(js.getJob().getId())
2780 .append(", ")
2781 .append(js.getUid())
2782 .append(") ");
2783 }
2784 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002785 }
Christopher Tate7060b042014-06-09 19:50:00 -07002786
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002787 static void dumpHelp(PrintWriter pw) {
2788 pw.println("Job Scheduler (jobscheduler) dump options:");
2789 pw.println(" [-h] [package] ...");
2790 pw.println(" -h: print this help");
2791 pw.println(" [package] is an optional package name to limit the output to.");
2792 }
2793
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002794 /** Sort jobs by caller UID, then by Job ID. */
2795 private static void sortJobs(List<JobStatus> jobs) {
2796 Collections.sort(jobs, new Comparator<JobStatus>() {
2797 @Override
2798 public int compare(JobStatus o1, JobStatus o2) {
2799 int uid1 = o1.getUid();
2800 int uid2 = o2.getUid();
2801 int id1 = o1.getJobId();
2802 int id2 = o2.getJobId();
2803 if (uid1 != uid2) {
2804 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002805 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002806 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002807 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002808 });
2809 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002810
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002811 void dumpInternal(final PrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002812 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07002813 final long nowElapsed = sElapsedRealtimeClock.millis();
2814 final long nowUptime = sUptimeMillisClock.millis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002815 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002816 mConstants.dump(pw);
2817 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002818 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002819 pw.print("Registered ");
2820 pw.print(mJobs.size());
2821 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002822 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002823 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002824 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002825 for (JobStatus job : jobs) {
2826 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2827 pw.println(job.toShortStringExceptUniqueId());
2828
2829 // Skip printing details if the caller requested a filter
2830 if (!job.shouldDump(filterUidFinal)) {
2831 continue;
2832 }
2833
Dianne Hackborn6d068262017-05-16 13:14:37 -07002834 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002835 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002836 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002837 pw.print(" (job=");
2838 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002839 pw.print(" user=");
2840 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002841 pw.print(" !pending=");
2842 pw.print(!mPendingJobs.contains(job));
2843 pw.print(" !active=");
2844 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002845 pw.print(" !backingup=");
2846 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002847 pw.print(" comp=");
2848 boolean componentPresent = false;
2849 try {
2850 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2851 job.getServiceComponent(),
2852 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2853 job.getUserId()) != null);
2854 } catch (RemoteException e) {
2855 }
2856 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002857 pw.println(")");
2858 }
Christopher Tate7060b042014-06-09 19:50:00 -07002859 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002860 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002861 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002862 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002863 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002864 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002865 }
2866 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002867 pw.println("Uid priority overrides:");
2868 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002869 int uid = mUidPriorityOverride.keyAt(i);
2870 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2871 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2872 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2873 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002874 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002875 if (mBackingUpUids.size() > 0) {
2876 pw.println();
2877 pw.println("Backing up uids:");
2878 boolean first = true;
2879 for (int i = 0; i < mBackingUpUids.size(); i++) {
2880 int uid = mBackingUpUids.keyAt(i);
2881 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2882 if (first) {
2883 pw.print(" ");
2884 first = false;
2885 } else {
2886 pw.print(", ");
2887 }
2888 pw.print(UserHandle.formatUid(uid));
2889 }
2890 }
2891 pw.println();
2892 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002893 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002894 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002895 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002896 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2897 pw.println();
2898 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002899 pw.println("Pending queue:");
2900 for (int i=0; i<mPendingJobs.size(); i++) {
2901 JobStatus job = mPendingJobs.get(i);
2902 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2903 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002904 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002905 int priority = evaluateJobPriorityLocked(job);
2906 if (priority != JobInfo.PRIORITY_DEFAULT) {
2907 pw.print(" Evaluated priority: "); pw.println(priority);
2908 }
2909 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002910 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002911 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002912 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002913 }
Christopher Tate7060b042014-06-09 19:50:00 -07002914 pw.println();
2915 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002916 for (int i=0; i<mActiveServices.size(); i++) {
2917 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002918 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002919 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002920 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002921 if (jsc.mStoppedReason != null) {
2922 pw.print("inactive since ");
2923 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2924 pw.print(", stopped because: ");
2925 pw.println(jsc.mStoppedReason);
2926 } else {
2927 pw.println("inactive");
2928 }
Christopher Tate7060b042014-06-09 19:50:00 -07002929 continue;
2930 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002931 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002932 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002933 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002934 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002935 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002936 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002937 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002938 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002939 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002940 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002941 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002942 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002943 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002944 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002945 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2946 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002947 }
2948 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002949 if (filterUid == -1) {
2950 pw.println();
2951 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2952 pw.print("mReportedActive="); pw.println(mReportedActive);
2953 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2954 }
Makoto Onukie7b02982017-08-24 14:23:36 -07002955 pw.println();
2956 pw.print("PersistStats: ");
2957 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07002958 }
2959 pw.println();
2960 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002961
2962 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
2963 ProtoOutputStream proto = new ProtoOutputStream(fd);
2964 final int filterUidFinal = UserHandle.getAppId(filterUid);
2965 final long nowElapsed = sElapsedRealtimeClock.millis();
2966 final long nowUptime = sUptimeMillisClock.millis();
2967
2968 synchronized (mLock) {
2969 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
2970 for (int u : mStartedUsers) {
2971 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
2972 }
2973 if (mJobs.size() > 0) {
2974 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2975 sortJobs(jobs);
2976 for (JobStatus job : jobs) {
2977 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
2978 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
2979
2980 // Skip printing details if the caller requested a filter
2981 if (!job.shouldDump(filterUidFinal)) {
2982 continue;
2983 }
2984
2985 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
2986
2987 // isReadyToBeExecuted
2988 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
2989 job.isReady());
2990 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
2991 ArrayUtils.contains(mStartedUsers, job.getUserId()));
2992 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
2993 mPendingJobs.contains(job));
2994 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
2995 isCurrentlyActiveLocked(job));
2996 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
2997 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
2998 boolean componentPresent = false;
2999 try {
3000 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3001 job.getServiceComponent(),
3002 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3003 job.getUserId()) != null);
3004 } catch (RemoteException e) {
3005 }
3006 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
3007 componentPresent);
3008
3009 proto.end(rjToken);
3010 }
3011 }
3012 for (StateController controller : mControllers) {
3013 controller.dumpControllerStateLocked(
3014 proto, JobSchedulerServiceDumpProto.CONTROLLERS, filterUidFinal);
3015 }
3016 for (int i=0; i< mUidPriorityOverride.size(); i++) {
3017 int uid = mUidPriorityOverride.keyAt(i);
3018 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3019 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3020 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3021 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3022 mUidPriorityOverride.valueAt(i));
3023 proto.end(pToken);
3024 }
3025 }
3026 for (int i = 0; i < mBackingUpUids.size(); i++) {
3027 int uid = mBackingUpUids.keyAt(i);
3028 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3029 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3030 }
3031 }
3032
3033 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3034 filterUidFinal);
3035 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3036 filterUidFinal);
3037
3038 for (JobStatus job : mPendingJobs) {
3039 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3040
3041 job.writeToShortProto(proto, PendingJob.INFO);
3042 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
3043 int priority = evaluateJobPriorityLocked(job);
3044 if (priority != JobInfo.PRIORITY_DEFAULT) {
3045 proto.write(PendingJob.EVALUATED_PRIORITY, priority);
3046 }
3047 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
3048
3049 proto.end(pjToken);
3050 }
3051 for (JobServiceContext jsc : mActiveServices) {
3052 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
3053 final JobStatus job = jsc.getRunningJobLocked();
3054
3055 if (job == null) {
3056 final long ijToken = proto.start(ActiveJob.INACTIVE);
3057
3058 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
3059 nowElapsed - jsc.mStoppedTime);
3060 if (jsc.mStoppedReason != null) {
3061 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
3062 jsc.mStoppedReason);
3063 }
3064
3065 proto.end(ijToken);
3066 } else {
3067 final long rjToken = proto.start(ActiveJob.RUNNING);
3068
3069 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
3070
3071 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
3072 nowElapsed - jsc.getExecutionStartTimeElapsed());
3073 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
3074 jsc.getTimeoutElapsed() - nowElapsed);
3075
3076 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3077
3078 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
3079 if (priority != JobInfo.PRIORITY_DEFAULT) {
3080 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY, priority);
3081 }
3082
3083 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3084 nowUptime - job.madeActive);
3085 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3086 job.madeActive - job.madePending);
3087
3088 proto.end(rjToken);
3089 }
3090 proto.end(ajToken);
3091 }
3092 if (filterUid == -1) {
3093 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3094 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3095 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
3096 }
3097 }
3098
3099 proto.flush();
3100 }
Christopher Tate7060b042014-06-09 19:50:00 -07003101}