blob: 8eb70bfd079d109120904c914ce3850c597e4ce9 [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;
Makoto Onuki2f0b0312018-02-08 02:30:27 +000043import android.content.Intent.UriFlags;
Christopher Tate5568f542014-06-18 13:53:31 -070044import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070045import android.content.pm.PackageManager;
Christopher Tatea732f012017-10-26 17:26:53 -070046import android.content.pm.PackageManagerInternal;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060047import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070048import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070049import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070050import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070051import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070052import android.os.Binder;
53import android.os.Handler;
54import android.os.Looper;
55import android.os.Message;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070056import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070057import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080058import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070059import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070060import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070061import android.os.SystemClock;
62import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070063import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070064import android.provider.Settings;
65import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070066import android.util.Slog;
67import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080068import android.util.SparseIntArray;
Tej Singhd5747a62018-01-08 20:57:35 -080069import android.util.StatsLog;
Dianne Hackborn970510b2016-02-24 16:56:42 -080070import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080071import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080072
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070073import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070074import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070075import com.android.internal.app.procstats.ProcessStats;
Christopher Tatea732f012017-10-26 17:26:53 -070076import com.android.internal.os.BackgroundThread;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070077import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060078import com.android.internal.util.DumpUtils;
Makoto Onuki15407842018-01-19 14:23:11 -080079import com.android.internal.util.Preconditions;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080080import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070081import com.android.server.FgThread;
Makoto Onuki2f0b0312018-02-08 02:30:27 +000082import com.android.server.ForceAppStandbyTracker;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080083import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080084import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
85import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Christopher Tate2f36fd62016-02-18 18:36:08 -080086import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080087import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070088import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070089import com.android.server.job.controllers.BatteryController;
90import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080091import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070092import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070093import com.android.server.job.controllers.IdleController;
94import com.android.server.job.controllers.JobStatus;
95import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070096import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070097import com.android.server.job.controllers.TimeController;
98
Jeff Sharkey822cbd12016-02-25 11:09:55 -070099import libcore.util.EmptyArray;
100
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700101import java.io.FileDescriptor;
102import java.io.PrintWriter;
103import java.time.Clock;
104import java.util.ArrayList;
105import java.util.Arrays;
106import java.util.Collections;
107import java.util.Comparator;
108import java.util.Iterator;
109import java.util.List;
Makoto Onuki15407842018-01-19 14:23:11 -0800110import java.util.function.Predicate;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700111
Christopher Tate7060b042014-06-09 19:50:00 -0700112/**
113 * Responsible for taking jobs representing work to be performed by a client app, and determining
114 * based on the criteria specified when that job should be run against the client application's
115 * endpoint.
116 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
117 * about constraints, or the state of active jobs. It receives callbacks from the various
118 * controllers and completed jobs and operates accordingly.
119 *
120 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
121 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
122 * @hide
123 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800124public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700125 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800126 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700127 public static final boolean DEBUG = false;
Christopher Tatea732f012017-10-26 17:26:53 -0700128 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800129
Dianne Hackborn970510b2016-02-24 16:56:42 -0800130 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700131 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800132 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800133 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800134 /** The maximum number of jobs that we allow an unprivileged app to schedule */
135 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700136
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700137 @VisibleForTesting
138 public static Clock sSystemClock = Clock.systemUTC();
139 @VisibleForTesting
140 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
141 @VisibleForTesting
142 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800143
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800144 /** Global local for all job scheduler state. */
145 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700146 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700147 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700148 /** Tracking the standby bucket state of each app */
149 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700150 /** Tracking amount of time each package runs for. */
151 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700152
153 static final int MSG_JOB_EXPIRED = 0;
154 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700155 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000156 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700157
Christopher Tate7060b042014-06-09 19:50:00 -0700158 /**
159 * Track Services that have currently active or pending jobs. The index is provided by
160 * {@link JobStatus#getServiceToken()}
161 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700162 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700163 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700164 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800165 /** Need direct access to this for testing. */
166 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700167 /** Need direct access to this for testing. */
168 StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700169 /** Need directly for sending uid state changes */
170 private BackgroundJobsController mBackgroundJobsController;
Suprabh Shukla106203b2017-11-02 21:23:44 -0700171 private DeviceIdleJobsController mDeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700172 /**
173 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
174 * when ready to execute them.
175 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700176 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700177
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700178 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700179
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700180 final JobHandler mHandler;
181 final JobSchedulerStub mJobSchedulerStub;
182
Christopher Tatea732f012017-10-26 17:26:53 -0700183 PackageManagerInternal mLocalPM;
Makoto Onuki15407842018-01-19 14:23:11 -0800184 ActivityManagerInternal mActivityManagerInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700185 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800186 DeviceIdleController.LocalService mLocalDeviceIdleController;
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000187 final ForceAppStandbyTracker mForceAppStandbyTracker;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700188
189 /**
190 * Set to true once we are allowed to run third party apps.
191 */
192 boolean mReadyToRock;
193
Christopher Tate7060b042014-06-09 19:50:00 -0700194 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800195 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800196 */
197 boolean mReportedActive;
198
199 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800200 * Are we currently in device-wide standby parole?
201 */
202 volatile boolean mInParole;
203
204 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800205 * Current limit on the number of concurrent JobServiceContext entries we want to
206 * keep actively running a job.
207 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700208 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800209
210 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800211 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800212 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800213 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
214
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700215 /**
216 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
217 */
218 final SparseIntArray mBackingUpUids = new SparseIntArray();
219
Christopher Tatea732f012017-10-26 17:26:53 -0700220 /**
221 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
222 * next become runnable. Index into this array is by normalized bucket:
223 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
224 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
225 * and NEVER apps don't get them at all.
226 */
227 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
228 long mHeartbeat = 0;
229 long mLastHeartbeatTime = 0;
230
Dianne Hackborn970510b2016-02-24 16:56:42 -0800231 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
232
233 /**
234 * This array essentially stores the state of mActiveServices array.
235 * The ith index stores the job present on the ith JobServiceContext.
236 * We manipulate this array until we arrive at what jobs should be running on
237 * what JobServiceContext.
238 */
239 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
240 /**
241 * Indicates whether we need to act on this jobContext id
242 */
243 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
244 /**
245 * The uid whose jobs we would like to assign to a context.
246 */
247 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800248
249 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700250 * All times are in milliseconds. These constants are kept synchronized with the system
251 * global Settings. Any access to this class or its fields should be done while
252 * holding the JobSchedulerService.mLock lock.
253 */
254 private final class Constants extends ContentObserver {
255 // Key names stored in the settings value.
256 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
257 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800258 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700259 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700260 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
261 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
262 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
263 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
264 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
265 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
266 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
267 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
268 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
269 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700270 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
271 = "max_standard_reschedule_count";
272 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
273 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
274 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700275 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
276 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
277 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
278 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700279
280 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
281 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800282 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700283 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700284 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
285 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
286 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
287 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
288 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
289 private static final int DEFAULT_FG_JOB_COUNT = 4;
290 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
291 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700292 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700293 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700294 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
295 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
296 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
297 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700298 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000299 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
300 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700301 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700302
303 /**
304 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
305 * early.
306 */
307 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
308 /**
309 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
310 * things early.
311 */
312 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
313 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800314 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
315 * schedule things early.
316 */
317 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
318 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700319 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
320 * schedule things early.
321 */
322 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
323 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700324 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
325 * things early. 1 == Run connectivity jobs as soon as ready.
326 */
327 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
328 /**
329 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
330 * schedule things early.
331 */
332 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
333 /**
334 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
335 * running some work early. This (and thus the other min counts) is now set to 1, to
336 * prevent any batching at this level. Since we now do batching through doze, that is
337 * a much better mechanism.
338 */
339 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
340 /**
341 * This is the job execution factor that is considered to be heavy use of the system.
342 */
343 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
344 /**
345 * This is the job execution factor that is considered to be moderate use of the system.
346 */
347 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
348 /**
349 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
350 */
351 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
352 /**
353 * The maximum number of background jobs we allow when the system is in a normal
354 * memory state.
355 */
356 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
357 /**
358 * The maximum number of background jobs we allow when the system is in a moderate
359 * memory state.
360 */
361 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
362 /**
363 * The maximum number of background jobs we allow when the system is in a low
364 * memory state.
365 */
366 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
367 /**
368 * The maximum number of background jobs we allow when the system is in a critical
369 * memory state.
370 */
371 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700372 /**
373 * The maximum number of times we allow a job to have itself rescheduled before
374 * giving up on it, for standard jobs.
375 */
376 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
377 /**
378 * The maximum number of times we allow a job to have itself rescheduled before
379 * giving up on it, for jobs that are executing work.
380 */
381 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
382 /**
383 * The minimum backoff time to allow for linear backoff.
384 */
385 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
386 /**
387 * The minimum backoff time to allow for exponential backoff.
388 */
389 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700390 /**
391 * How often we recalculate runnability based on apps' standby bucket assignment.
392 * This should be prime relative to common time interval lengths such as a quarter-
393 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
394 */
395 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
396
397 /**
398 * Mapping: standby bucket -> number of heartbeats between each sweep of that
399 * bucket's jobs.
400 *
401 * Bucket assignments as recorded in the JobStatus objects are normalized to be
402 * indices into this array, rather than the raw constants used
403 * by AppIdleHistory.
404 */
405 final int[] STANDBY_BEATS = {
406 0,
407 DEFAULT_STANDBY_WORKING_BEATS,
408 DEFAULT_STANDBY_FREQUENT_BEATS,
409 DEFAULT_STANDBY_RARE_BEATS
410 };
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700411
412 private ContentResolver mResolver;
413 private final KeyValueListParser mParser = new KeyValueListParser(',');
414
415 public Constants(Handler handler) {
416 super(handler);
417 }
418
419 public void start(ContentResolver resolver) {
420 mResolver = resolver;
421 mResolver.registerContentObserver(Settings.Global.getUriFor(
422 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
423 updateConstants();
424 }
425
426 @Override
427 public void onChange(boolean selfChange, Uri uri) {
428 updateConstants();
429 }
430
431 private void updateConstants() {
432 synchronized (mLock) {
433 try {
434 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000435 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700436 } catch (IllegalArgumentException e) {
437 // Failed to parse the settings string, log this and move on
438 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000439 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700440 }
441
442 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
443 DEFAULT_MIN_IDLE_COUNT);
444 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
445 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800446 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
447 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700448 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
449 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700450 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
451 DEFAULT_MIN_CONNECTIVITY_COUNT);
452 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
453 DEFAULT_MIN_CONTENT_COUNT);
454 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
455 DEFAULT_MIN_READY_JOBS_COUNT);
456 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
457 DEFAULT_HEAVY_USE_FACTOR);
458 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
459 DEFAULT_MODERATE_USE_FACTOR);
460 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
461 DEFAULT_FG_JOB_COUNT);
462 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
463 DEFAULT_BG_NORMAL_JOB_COUNT);
464 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
465 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
466 }
467 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
468 DEFAULT_BG_MODERATE_JOB_COUNT);
469 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
470 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
471 }
472 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
473 DEFAULT_BG_LOW_JOB_COUNT);
474 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
475 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
476 }
477 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
478 DEFAULT_BG_CRITICAL_JOB_COUNT);
479 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
480 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
481 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700482 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
483 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
484 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
485 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800486 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700487 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800488 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700489 DEFAULT_MIN_EXP_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800490 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
Christopher Tatea732f012017-10-26 17:26:53 -0700491 DEFAULT_STANDBY_HEARTBEAT_TIME);
492 STANDBY_BEATS[1] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
493 DEFAULT_STANDBY_WORKING_BEATS);
494 STANDBY_BEATS[2] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
495 DEFAULT_STANDBY_FREQUENT_BEATS);
496 STANDBY_BEATS[3] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
497 DEFAULT_STANDBY_RARE_BEATS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700498 }
499 }
500
501 void dump(PrintWriter pw) {
502 pw.println(" Settings:");
503
504 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
505 pw.print(MIN_IDLE_COUNT); pw.println();
506
507 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
508 pw.print(MIN_CHARGING_COUNT); pw.println();
509
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800510 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
511 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
512
Dianne Hackborn532ea262017-03-17 17:50:55 -0700513 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
514 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
515
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700516 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
517 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
518
519 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
520 pw.print(MIN_CONTENT_COUNT); pw.println();
521
522 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
523 pw.print(MIN_READY_JOBS_COUNT); pw.println();
524
525 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
526 pw.print(HEAVY_USE_FACTOR); pw.println();
527
528 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
529 pw.print(MODERATE_USE_FACTOR); pw.println();
530
531 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
532 pw.print(FG_JOB_COUNT); pw.println();
533
534 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
535 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
536
537 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
538 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
539
540 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
541 pw.print(BG_LOW_JOB_COUNT); pw.println();
542
543 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
544 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700545
546 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
547 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
548
549 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
550 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
551
552 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
553 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
554
555 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
556 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Christopher Tatea732f012017-10-26 17:26:53 -0700557
558 pw.print(" "); pw.print(KEY_STANDBY_HEARTBEAT_TIME); pw.print("=");
559 pw.print(STANDBY_HEARTBEAT_TIME); pw.println();
560
561 pw.print(" standby_beats={");
562 pw.print(STANDBY_BEATS[0]);
563 for (int i = 1; i < STANDBY_BEATS.length; i++) {
564 pw.print(", ");
565 pw.print(STANDBY_BEATS[i]);
566 }
567 pw.println('}');
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700568 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800569
570 void dump(ProtoOutputStream proto, long fieldId) {
571 final long token = proto.start(fieldId);
572
573 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
574 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
575 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
576 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
577 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
578 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
579 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
580 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
581 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
582 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
583 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
584 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
585 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
586 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
587 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
588 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
589 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
590 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
591 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
592
593 for (int period : STANDBY_BEATS) {
594 proto.write(ConstantsProto.STANDBY_BEATS, period);
595 }
596
597 proto.end(token);
598 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700599 }
600
601 final Constants mConstants;
602
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700603 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
604 if (o1.enqueueTime < o2.enqueueTime) {
605 return -1;
606 }
607 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
608 };
609
610 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
611 int where = Collections.binarySearch(array, newItem, comparator);
612 if (where < 0) {
613 where = ~where;
614 }
615 array.add(where, newItem);
616 }
617
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700618 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700619 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
620 * still clean up. On reinstall the package will have a new uid.
621 */
622 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
623 @Override
624 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700625 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700626 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700627 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700628 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700629 final String pkgName = getPackageName(intent);
630 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
631
Christopher Tateee7805b2016-07-15 16:56:56 -0700632 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700633 // Purge the app's jobs if the whole package was just disabled. When this is
634 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700635 if (pkgName != null && pkgUid != -1) {
636 final String[] changedComponents = intent.getStringArrayExtra(
637 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
638 if (changedComponents != null) {
639 for (String component : changedComponents) {
640 if (component.equals(pkgName)) {
641 if (DEBUG) {
642 Slog.d(TAG, "Package state change: " + pkgName);
643 }
644 try {
645 final int userId = UserHandle.getUserId(pkgUid);
646 IPackageManager pm = AppGlobals.getPackageManager();
647 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
648 if (state == COMPONENT_ENABLED_STATE_DISABLED
649 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
650 if (DEBUG) {
651 Slog.d(TAG, "Removing jobs for package " + pkgName
652 + " in user " + userId);
653 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700654 cancelJobsForPackageAndUid(pkgName, pkgUid,
655 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700656 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700657 } catch (RemoteException|IllegalArgumentException e) {
658 /*
659 * IllegalArgumentException means that the package doesn't exist.
660 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
661 * behind outright uninstall, so by the time we try to act it's gone.
662 * We don't need to act on this PACKAGE_CHANGED when this happens;
663 * we'll get a PACKAGE_REMOVED later and clean up then.
664 *
665 * RemoteException can't actually happen; the package manager is
666 * running in this same process.
667 */
668 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700669 break;
670 }
671 }
672 }
673 } else {
674 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
675 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700676 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700677 // If this is an outright uninstall rather than the first half of an
678 // app update sequence, cancel the jobs associated with the app.
679 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
680 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
681 if (DEBUG) {
682 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
683 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700684 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700685 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700686 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700687 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
688 if (DEBUG) {
689 Slog.d(TAG, "Removing jobs for user: " + userId);
690 }
691 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700692 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
693 // Has this package scheduled any jobs, such that we will take action
694 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700695 if (pkgUid != -1) {
696 List<JobStatus> jobsForUid;
697 synchronized (mLock) {
698 jobsForUid = mJobs.getJobsByUid(pkgUid);
699 }
700 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
701 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
702 if (DEBUG) {
703 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
704 + pkgUid + " has jobs");
705 }
706 setResultCode(Activity.RESULT_OK);
707 break;
708 }
709 }
710 }
711 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
712 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700713 if (pkgUid != -1) {
714 if (DEBUG) {
715 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
716 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700717 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700718 }
Christopher Tate7060b042014-06-09 19:50:00 -0700719 }
720 }
721 };
722
Christopher Tateb5c07882016-05-26 17:11:09 -0700723 private String getPackageName(Intent intent) {
724 Uri uri = intent.getData();
725 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
726 return pkg;
727 }
728
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700729 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700730 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800731 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700732 }
733
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700734 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800735 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800736 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700737 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800738 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700739 synchronized (mLock) {
740 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
741 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700742 }
743
744 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla106203b2017-11-02 21:23:44 -0700745 synchronized (mLock) {
746 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
747 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700748 }
749
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700750 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800751 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700752 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800753 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700754 synchronized (mLock) {
755 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
756 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700757 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700758
759 @Override public void onUidCachedChanged(int uid, boolean cached) {
760 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700761 };
762
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800763 public Object getLock() {
764 return mLock;
765 }
766
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700767 public JobStore getJobStore() {
768 return mJobs;
769 }
770
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700771 @Override
772 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700773 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
774 // Let's kick any outstanding jobs for this user.
775 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
776 }
777
778 @Override
779 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700780 // Let's kick any outstanding jobs for this user.
781 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
782 }
783
784 @Override
785 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700786 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700787 }
788
Makoto Onuki15407842018-01-19 14:23:11 -0800789 /**
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000790 * Return whether an UID is in the foreground or not.
Makoto Onuki15407842018-01-19 14:23:11 -0800791 */
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000792 private boolean isUidInForeground(int uid) {
793 synchronized (mLock) {
794 if (mUidPriorityOverride.get(uid, 0) > 0) {
795 return true;
796 }
797 }
798 // Note UID observer may not be called in time, so we always check with the AM.
799 return mActivityManagerInternal.getUidProcessState(uid)
800 <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
Makoto Onuki15407842018-01-19 14:23:11 -0800801 }
802
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000803 private final Predicate<Integer> mIsUidInForegroundPredicate = this::isUidInForeground;
Makoto Onuki15407842018-01-19 14:23:11 -0800804
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700805 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
806 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700807 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800808 if (ActivityManager.getService().isAppStartModeDisabled(uId,
809 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700810 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
811 + " -- package not allowed to start");
812 return JobScheduler.RESULT_FAILURE;
813 }
814 } catch (RemoteException e) {
815 }
Christopher Tatea732f012017-10-26 17:26:53 -0700816
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800817 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700818 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
819
820 if (work != null && toCancel != null) {
821 // Fast path: we are adding work to an existing job, and the JobInfo is not
822 // changing. We can just directly enqueue this work in to the job.
823 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -0800824
Dianne Hackborn342e6032017-04-13 18:04:31 -0700825 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Makoto Onuki15407842018-01-19 14:23:11 -0800826
827 // If any of work item is enqueued when the source is in the foreground,
828 // exempt the entire job.
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000829 toCancel.maybeAddForegroundExemption(mIsUidInForegroundPredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800830
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700831 return JobScheduler.RESULT_SUCCESS;
832 }
833 }
834
835 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -0800836
837 // Give exemption if the source is in the foreground just now.
838 // Note if it's a sync job, this method is called on the handler so it's not exactly
839 // the state when requestSync() was called, but that should be fine because of the
840 // 1 minute foreground grace period.
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000841 jobStatus.maybeAddForegroundExemption(mIsUidInForegroundPredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800842
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700843 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800844 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800845 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800846 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
847 Slog.w(TAG, "Too many jobs for uid " + uId);
848 throw new IllegalStateException("Apps may not schedule more than "
849 + MAX_JOBS_PER_APP + " distinct jobs");
850 }
851 }
852
Dianne Hackborna47223f2017-03-30 13:49:13 -0700853 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700854 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700855
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700856 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700857 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700858 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700859 if (work != null) {
860 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700861 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700862 }
863 startTrackingJobLocked(jobStatus, toCancel);
Tej Singhd5747a62018-01-08 20:57:35 -0800864 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -0800865 uId, null, jobStatus.getBatteryName(),
866 StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700867
868 // If the job is immediately ready to run, then we can just immediately
869 // put it in the pending list and try to schedule it. This is especially
870 // important for jobs with a 0 deadline constraint, since they will happen a fair
871 // amount, we want to handle them as quickly as possible, and semantically we want to
872 // make sure we have started holding the wake lock for the job before returning to
873 // the caller.
874 // If the job is not yet ready to run, there is nothing more to do -- we are
875 // now just waiting for one of its controllers to change state and schedule
876 // the job appropriately.
877 if (isReadyToBeExecutedLocked(jobStatus)) {
878 // This is a new job, we can just immediately put it on the pending
879 // list and try to run it.
880 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700881 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700882 maybeRunPendingJobsLocked();
883 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800884 }
Christopher Tate7060b042014-06-09 19:50:00 -0700885 return JobScheduler.RESULT_SUCCESS;
886 }
887
888 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800889 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800890 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
891 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
892 for (int i = jobs.size() - 1; i >= 0; i--) {
893 JobStatus job = jobs.get(i);
894 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700895 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800896 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700897 }
Christopher Tate7060b042014-06-09 19:50:00 -0700898 }
899
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600900 public JobInfo getPendingJob(int uid, int jobId) {
901 synchronized (mLock) {
902 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
903 for (int i = jobs.size() - 1; i >= 0; i--) {
904 JobStatus job = jobs.get(i);
905 if (job.getJobId() == jobId) {
906 return job.getJob();
907 }
908 }
909 return null;
910 }
911 }
912
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700913 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800914 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700915 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
916 for (int i=0; i<jobsForUser.size(); i++) {
917 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700918 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700919 }
Christopher Tate7060b042014-06-09 19:50:00 -0700920 }
921 }
922
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700923 private void cancelJobsForNonExistentUsers() {
924 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
925 synchronized (mLock) {
926 mJobs.removeJobsOfNonUsers(umi.getUserIds());
927 }
928 }
929
Makoto Onukie7b96182017-08-30 14:53:16 -0700930 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
931 if ("android".equals(pkgName)) {
932 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
933 return;
934 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700935 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700936 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
937 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
938 final JobStatus job = jobsForUid.get(i);
939 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700940 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700941 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700942 }
943 }
944 }
945
Christopher Tate7060b042014-06-09 19:50:00 -0700946 /**
947 * Entry point from client to cancel all jobs originating from their uid.
948 * This will remove the job from the master list, and cancel the job if it was staged for
949 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700950 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800951 *
Christopher Tate7060b042014-06-09 19:50:00 -0700952 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700953 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700954 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700955 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700956 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700957 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700958
959 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800960 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700961 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
962 for (int i=0; i<jobsForUid.size(); i++) {
963 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700964 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700965 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700966 }
Christopher Tate7060b042014-06-09 19:50:00 -0700967 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700968 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700969 }
970
971 /**
972 * Entry point from client to cancel the job corresponding to the jobId provided.
973 * This will remove the job from the master list, and cancel the job if it was staged for
974 * execution or being executed.
975 * @param uid Uid of the calling client.
976 * @param jobId Id of the job, provided at schedule-time.
977 */
Makoto Onukid2bfec62018-01-12 13:58:01 -0800978 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -0700979 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800980 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700981 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700982 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -0800983 cancelJobImplLocked(toCancel, null,
984 "cancel() called by app, callingUid=" + callingUid
985 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700986 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700987 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -0700988 }
989 }
990
Dianne Hackborn729a3282017-06-09 16:06:01 -0700991 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700992 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
993 cancelled.unprepareLocked(ActivityManager.getService());
994 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
995 // Remove from pending queue.
996 if (mPendingJobs.remove(cancelled)) {
997 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700998 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700999 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -07001000 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001001 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001002 }
1003
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001004 void updateUidState(int uid, int procState) {
1005 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001006 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1007 // Only use this if we are exactly the top app. All others can live
1008 // with just the foreground priority. This means that persistent processes
1009 // can never be the top app priority... that is fine.
1010 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001011 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001012 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001013 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001014 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001015 }
1016 }
1017 }
1018
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001019 @Override
1020 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001021 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001022 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001023 // When becoming idle, make sure no jobs are actively running,
1024 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001025 for (int i=0; i<mActiveServices.size(); i++) {
1026 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001027 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001028 if (executing != null
1029 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001030 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1031 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001032 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001033 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001034 } else {
1035 // When coming out of idle, allow thing to start back up.
1036 if (mReadyToRock) {
1037 if (mLocalDeviceIdleController != null) {
1038 if (!mReportedActive) {
1039 mReportedActive = true;
1040 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001041 }
1042 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001043 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001044 }
1045 }
1046 }
1047 }
1048
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001049 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001050 // active is true if pending queue contains jobs OR some job is running.
1051 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001052 if (mPendingJobs.size() <= 0) {
1053 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001054 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001055 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001056 if (job != null
1057 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
1058 && !job.dozeWhitelisted) {
1059 // We will report active if we have a job running and it is not an exception
1060 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001061 active = true;
1062 break;
1063 }
1064 }
1065 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001066
1067 if (mReportedActive != active) {
1068 mReportedActive = active;
1069 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001070 mLocalDeviceIdleController.setJobsActive(active);
1071 }
1072 }
1073 }
1074
Christopher Tated117b292018-01-05 17:32:36 -08001075 void reportAppUsage(String packageName, int userId) {
1076 // This app just transitioned into interactive use or near equivalent, so we should
1077 // take a look at its job state for feedback purposes.
1078 }
1079
Christopher Tate7060b042014-06-09 19:50:00 -07001080 /**
1081 * Initializes the system service.
1082 * <p>
1083 * Subclasses must define a single argument constructor that accepts the context
1084 * and passes it to super.
1085 * </p>
1086 *
1087 * @param context The system server context.
1088 */
1089 public JobSchedulerService(Context context) {
1090 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001091
1092 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Makoto Onuki15407842018-01-19 14:23:11 -08001093 mActivityManagerInternal = Preconditions.checkNotNull(
1094 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001095
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001096 mHandler = new JobHandler(context.getMainLooper());
1097 mConstants = new Constants(mHandler);
1098 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001099
1100 // Set up the app standby bucketing tracker
1101 UsageStatsManagerInternal usageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1102 mStandbyTracker = new StandbyTracker(usageStats);
1103 usageStats.addAppIdleStateChangeListener(mStandbyTracker);
1104
1105 // The job store needs to call back
1106 publishLocalService(JobSchedulerInternal.class, new LocalService());
1107
1108 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001109 mJobs = JobStore.initAndGet(this);
1110
Christopher Tate7060b042014-06-09 19:50:00 -07001111 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001112 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -07001113 mControllers.add(ConnectivityController.get(this));
1114 mControllers.add(TimeController.get(this));
1115 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001116 mBatteryController = BatteryController.get(this);
1117 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001118 mStorageController = StorageController.get(this);
1119 mControllers.add(mStorageController);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001120 mControllers.add(BackgroundJobsController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -08001121 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001122 mControllers.add(ContentObserverController.get(this));
Suprabh Shukla106203b2017-11-02 21:23:44 -07001123 mDeviceIdleJobsController = DeviceIdleJobsController.get(this);
1124 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001125
Makoto Onuki2f0b0312018-02-08 02:30:27 +00001126 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
1127
Christopher Tate616541d2017-07-26 14:27:38 -07001128 // If the job store determined that it can't yet reschedule persisted jobs,
1129 // we need to start watching the clock.
1130 if (!mJobs.jobTimesInflatedValid()) {
1131 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1132 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1133 }
Christopher Tate7060b042014-06-09 19:50:00 -07001134 }
1135
Christopher Tate616541d2017-07-26 14:27:38 -07001136 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1137 @Override
1138 public void onReceive(Context context, Intent intent) {
1139 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1140 // When we reach clock sanity, recalculate the temporal windows
1141 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001142 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001143 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1144
1145 // We've done our job now, so stop watching the time.
1146 context.unregisterReceiver(this);
1147
1148 // And kick off the work to update the affected jobs, using a secondary
1149 // thread instead of chugging away here on the main looper thread.
1150 FgThread.getHandler().post(mJobTimeUpdater);
1151 }
1152 }
1153 }
1154 };
1155
1156 private final Runnable mJobTimeUpdater = () -> {
1157 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1158 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1159 synchronized (mLock) {
1160 // Note: we intentionally both look up the existing affected jobs and replace them
1161 // with recalculated ones inside the same lock lifetime.
1162 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1163
1164 // Now, at each position [i], we have both the existing JobStatus
1165 // and the one that replaces it.
1166 final int N = toAdd.size();
1167 for (int i = 0; i < N; i++) {
1168 final JobStatus oldJob = toRemove.get(i);
1169 final JobStatus newJob = toAdd.get(i);
1170 if (DEBUG) {
1171 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1172 }
1173 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1174 }
1175 }
1176 };
1177
Christopher Tate7060b042014-06-09 19:50:00 -07001178 @Override
1179 public void onStart() {
1180 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1181 }
1182
1183 @Override
1184 public void onBootPhase(int phase) {
1185 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001186 mConstants.start(getContext().getContentResolver());
Makoto Onuki15407842018-01-19 14:23:11 -08001187
Makoto Onuki2f0b0312018-02-08 02:30:27 +00001188 mForceAppStandbyTracker.start();
Makoto Onuki15407842018-01-19 14:23:11 -08001189
Shreyas Basarge5db09082016-01-07 13:38:29 +00001190 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001191 final IntentFilter filter = new IntentFilter();
1192 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1193 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001194 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1195 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001196 filter.addDataScheme("package");
1197 getContext().registerReceiverAsUser(
1198 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1199 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1200 getContext().registerReceiverAsUser(
1201 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001202 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001203 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001204 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001205 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1206 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001207 } catch (RemoteException e) {
1208 // ignored; both services live in system_server
1209 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001210 // Remove any jobs that are not associated with any of the current users.
1211 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001212 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001213 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001214 // Let's go!
1215 mReadyToRock = true;
1216 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1217 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001218 mLocalDeviceIdleController
1219 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001220 // Create the "runners".
1221 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1222 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001223 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001224 getContext().getMainLooper()));
1225 }
1226 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001227 mJobs.forEachJob(new JobStatusFunctor() {
1228 @Override
1229 public void process(JobStatus job) {
1230 for (int controller = 0; controller < mControllers.size(); controller++) {
1231 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001232 sc.maybeStartTrackingJobLocked(job, null);
1233 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001234 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001235 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001236 // GO GO GO!
1237 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1238 }
Christopher Tate7060b042014-06-09 19:50:00 -07001239 }
1240 }
1241
1242 /**
1243 * Called when we have a job status object that we need to insert in our
1244 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1245 * about.
1246 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001247 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1248 if (!jobStatus.isPreparedLocked()) {
1249 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1250 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001251 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001252 final boolean update = mJobs.add(jobStatus);
1253 if (mReadyToRock) {
1254 for (int i = 0; i < mControllers.size(); i++) {
1255 StateController controller = mControllers.get(i);
1256 if (update) {
1257 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001258 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001259 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001260 }
Christopher Tate7060b042014-06-09 19:50:00 -07001261 }
1262 }
1263
1264 /**
1265 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1266 * object removed.
1267 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001268 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001269 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001270 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001271 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001272
1273 // Remove from store as well as controllers.
1274 final boolean removed = mJobs.remove(jobStatus, writeBack);
1275 if (removed && mReadyToRock) {
1276 for (int i=0; i<mControllers.size(); i++) {
1277 StateController controller = mControllers.get(i);
1278 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001279 }
1280 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001281 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001282 }
1283
Dianne Hackborn729a3282017-06-09 16:06:01 -07001284 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001285 for (int i=0; i<mActiveServices.size(); i++) {
1286 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001287 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001288 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001289 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001290 return true;
1291 }
1292 }
1293 return false;
1294 }
1295
1296 /**
1297 * @param job JobStatus we are querying against.
1298 * @return Whether or not the job represented by the status object is currently being run or
1299 * is pending.
1300 */
1301 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001302 for (int i=0; i<mActiveServices.size(); i++) {
1303 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001304 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001305 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1306 return true;
1307 }
1308 }
1309 return false;
1310 }
1311
Dianne Hackborn807de782016-04-07 17:54:41 -07001312 void noteJobsPending(List<JobStatus> jobs) {
1313 for (int i = jobs.size() - 1; i >= 0; i--) {
1314 JobStatus job = jobs.get(i);
1315 mJobPackageTracker.notePending(job);
1316 }
1317 }
1318
1319 void noteJobsNonpending(List<JobStatus> jobs) {
1320 for (int i = jobs.size() - 1; i >= 0; i--) {
1321 JobStatus job = jobs.get(i);
1322 mJobPackageTracker.noteNonpending(job);
1323 }
1324 }
1325
Christopher Tate7060b042014-06-09 19:50:00 -07001326 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001327 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1328 * specify an override deadline on a failed job (the failed job will run even though it's not
1329 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1330 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1331 *
Christopher Tate7060b042014-06-09 19:50:00 -07001332 * @param failureToReschedule Provided job status that we will reschedule.
1333 * @return A newly instantiated JobStatus with the same constraints as the last job except
1334 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001335 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001336 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001337 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001338 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001339 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001340 final JobInfo job = failureToReschedule.getJob();
1341
1342 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001343 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1344 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001345
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001346 if (failureToReschedule.hasWorkLocked()) {
1347 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1348 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1349 + backoffAttempts + " > work limit "
1350 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1351 return null;
1352 }
1353 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1354 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1355 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1356 return null;
1357 }
1358
Christopher Tate7060b042014-06-09 19:50:00 -07001359 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001360 case JobInfo.BACKOFF_POLICY_LINEAR: {
1361 long backoff = initialBackoffMillis;
1362 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1363 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1364 }
1365 delayMillis = backoff * backoffAttempts;
1366 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001367 default:
1368 if (DEBUG) {
1369 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1370 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001371 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1372 long backoff = initialBackoffMillis;
1373 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1374 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1375 }
1376 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1377 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001378 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001379 delayMillis =
1380 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001381 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1382 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001383 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001384 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001385 for (int ic=0; ic<mControllers.size(); ic++) {
1386 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001387 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001388 }
1389 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001390 }
1391
1392 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001393 * Called after a periodic has executed so we can reschedule it. We take the last execution
1394 * time of the job to be the time of completion (i.e. the time at which this function is
1395 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001396 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001397 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1398 * to underscheduling at least, rather than if we had taken the last execution time to be the
1399 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001400 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1401 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001402 * @return A new job representing the execution criteria for this instantiation of the
1403 * recurring job.
1404 */
1405 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001406 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001407 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001408 long runEarly = 0L;
1409
1410 // If this periodic was rescheduled it won't have a deadline.
1411 if (periodicToReschedule.hasDeadlineConstraint()) {
1412 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1413 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001414 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001415 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001416 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1417 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001418
1419 if (DEBUG) {
1420 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1421 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1422 }
Christopher Tatea732f012017-10-26 17:26:53 -07001423 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1424 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1425 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001426 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001427 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001428 }
1429
1430 // JobCompletedListener implementations.
1431
1432 /**
1433 * A job just finished executing. We fetch the
1434 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1435 * whether we want to reschedule we readd it to the controllers.
1436 * @param jobStatus Completed job.
1437 * @param needsReschedule Whether the implementing class should reschedule this job.
1438 */
1439 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001440 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001441 if (DEBUG) {
1442 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1443 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001444
1445 // If the job wants to be rescheduled, we first need to make the next upcoming
1446 // job so we can transfer any appropriate state over from the previous job when
1447 // we stop it.
1448 final JobStatus rescheduledJob = needsReschedule
1449 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1450
Shreyas Basarge73f10252016-02-11 17:06:13 +00001451 // Do not write back immediately if this is a periodic job. The job may get lost if system
1452 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001453 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001454 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001455 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001456 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001457 // We still want to check for jobs to execute, because this job may have
1458 // scheduled a new job under the same job id, and now we can run it.
1459 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001460 return;
1461 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001462
1463 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001464 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001465 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001466 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001467 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001468 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001469 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001470 } else if (jobStatus.getJob().isPeriodic()) {
1471 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001472 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001473 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001474 } catch (SecurityException e) {
1475 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1476 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001477 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001478 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001479 jobStatus.unprepareLocked(ActivityManager.getService());
1480 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001481 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001482 }
1483
1484 // StateChangedListener implementations.
1485
1486 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001487 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1488 * some controller's state has changed, so as to run through the list of jobs and start/stop
1489 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001490 */
1491 @Override
1492 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001493 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001494 }
1495
1496 @Override
1497 public void onRunJobNow(JobStatus jobStatus) {
1498 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1499 }
1500
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001501 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001502
1503 public JobHandler(Looper looper) {
1504 super(looper);
1505 }
1506
1507 @Override
1508 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001509 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001510 if (!mReadyToRock) {
1511 return;
1512 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001513 switch (message.what) {
1514 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001515 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001516 // runNow can be null, which is a controller's way of indicating that its
1517 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001518 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001519 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001520 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001521 } else {
1522 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001523 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001524 } break;
1525 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001526 if (mReportedActive) {
1527 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001528 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001529 } else {
1530 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001531 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001532 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001533 break;
1534 case MSG_CHECK_JOB_GREEDY:
1535 queueReadyJobsForExecutionLocked();
1536 break;
1537 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001538 cancelJobImplLocked((JobStatus) message.obj, null,
1539 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001540 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001541 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001542 maybeRunPendingJobsLocked();
1543 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1544 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001545 }
1546 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001547 }
Christopher Tate7060b042014-06-09 19:50:00 -07001548
Dianne Hackborn6d068262017-05-16 13:14:37 -07001549 private void stopNonReadyActiveJobsLocked() {
1550 for (int i=0; i<mActiveServices.size(); i++) {
1551 JobServiceContext serviceContext = mActiveServices.get(i);
1552 final JobStatus running = serviceContext.getRunningJobLocked();
1553 if (running != null && !running.isReady()) {
1554 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001555 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1556 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001557 }
1558 }
1559 }
1560
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001561 /**
1562 * Run through list of jobs and execute all possible - at least one is expired so we do
1563 * as many as we can.
1564 */
1565 private void queueReadyJobsForExecutionLocked() {
1566 if (DEBUG) {
1567 Slog.d(TAG, "queuing all ready jobs for execution:");
1568 }
1569 noteJobsNonpending(mPendingJobs);
1570 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001571 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001572 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001573 mJobs.forEachJob(mReadyQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001574 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001575 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001576
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001577 if (DEBUG) {
1578 final int queuedJobs = mPendingJobs.size();
1579 if (queuedJobs == 0) {
1580 Slog.d(TAG, "No jobs pending.");
1581 } else {
1582 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001583 }
1584 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001585 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001586
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001587 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1588 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001589
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001590 @Override
1591 public void process(JobStatus job) {
1592 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001593 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001594 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001595 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001596 if (newReadyJobs == null) {
1597 newReadyJobs = new ArrayList<JobStatus>();
1598 }
1599 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001600 }
1601 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001602
1603 public void postProcess() {
1604 if (newReadyJobs != null) {
1605 noteJobsPending(newReadyJobs);
1606 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001607 if (mPendingJobs.size() > 1) {
1608 mPendingJobs.sort(mEnqueueTimeComparator);
1609 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001610 }
1611 newReadyJobs = null;
1612 }
1613 }
1614 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1615
1616 /**
1617 * The state of at least one job has changed. Here is where we could enforce various
1618 * policies on when we want to execute jobs.
1619 * Right now the policy is such:
1620 * If >1 of the ready jobs is idle mode we send all of them off
1621 * if more than 2 network connectivity jobs are ready we send them all off.
1622 * If more than 4 jobs total are ready we send them all off.
1623 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1624 */
1625 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1626 int chargingCount;
1627 int batteryNotLowCount;
1628 int storageNotLowCount;
1629 int idleCount;
1630 int backoffCount;
1631 int connectivityCount;
1632 int contentCount;
1633 List<JobStatus> runnableJobs;
1634
1635 public MaybeReadyJobQueueFunctor() {
1636 reset();
1637 }
1638
1639 // Functor method invoked for each job via JobStore.forEachJob()
1640 @Override
1641 public void process(JobStatus job) {
1642 if (isReadyToBeExecutedLocked(job)) {
1643 try {
1644 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1645 job.getJob().getService().getPackageName())) {
1646 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1647 + job.getJob().toString() + " -- package not allowed to start");
1648 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1649 return;
1650 }
1651 } catch (RemoteException e) {
1652 }
1653 if (job.getNumFailures() > 0) {
1654 backoffCount++;
1655 }
1656 if (job.hasIdleConstraint()) {
1657 idleCount++;
1658 }
1659 if (job.hasConnectivityConstraint()) {
1660 connectivityCount++;
1661 }
1662 if (job.hasChargingConstraint()) {
1663 chargingCount++;
1664 }
1665 if (job.hasBatteryNotLowConstraint()) {
1666 batteryNotLowCount++;
1667 }
1668 if (job.hasStorageNotLowConstraint()) {
1669 storageNotLowCount++;
1670 }
1671 if (job.hasContentTriggerConstraint()) {
1672 contentCount++;
1673 }
1674 if (runnableJobs == null) {
1675 runnableJobs = new ArrayList<>();
1676 }
1677 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001678 }
1679 }
1680
1681 public void postProcess() {
1682 if (backoffCount > 0 ||
1683 idleCount >= mConstants.MIN_IDLE_COUNT ||
1684 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1685 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1686 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1687 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1688 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1689 (runnableJobs != null
1690 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1691 if (DEBUG) {
1692 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1693 }
1694 noteJobsPending(runnableJobs);
1695 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001696 if (mPendingJobs.size() > 1) {
1697 mPendingJobs.sort(mEnqueueTimeComparator);
1698 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001699 } else {
1700 if (DEBUG) {
1701 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1702 }
1703 }
1704
1705 // Be ready for next time
1706 reset();
1707 }
1708
1709 private void reset() {
1710 chargingCount = 0;
1711 idleCount = 0;
1712 backoffCount = 0;
1713 connectivityCount = 0;
1714 batteryNotLowCount = 0;
1715 storageNotLowCount = 0;
1716 contentCount = 0;
1717 runnableJobs = null;
1718 }
1719 }
1720 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1721
1722 private void maybeQueueReadyJobsForExecutionLocked() {
1723 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1724
1725 noteJobsNonpending(mPendingJobs);
1726 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001727 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001728 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001729 mJobs.forEachJob(mMaybeQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001730 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001731 mMaybeQueueFunctor.postProcess();
1732 }
1733
Christopher Tatea732f012017-10-26 17:26:53 -07001734 private boolean updateStandbyHeartbeatLocked() {
1735 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1736 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1737 if (beatsElapsed > 0) {
1738 mHeartbeat += beatsElapsed;
1739 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1740 if (DEBUG_STANDBY) {
1741 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed + " to " + mHeartbeat);
1742 }
1743 return true;
1744 }
1745 return false;
1746 }
1747
1748 private void updateNextStandbyHeartbeatsLocked() {
1749 // don't update ACTIVE or NEVER bucket milestones
1750 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
1751 while (mHeartbeat >= mNextBucketHeartbeat[i]) {
1752 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1753 }
1754 if (DEBUG_STANDBY) {
1755 Slog.v(TAG, " Bucket " + i + " next heartbeat " + mNextBucketHeartbeat[i]);
1756 }
1757 }
1758 }
1759
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001760 /**
1761 * Criteria for moving a job into the pending queue:
1762 * - It's ready.
1763 * - It's not pending.
1764 * - It's not already running on a JSC.
1765 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001766 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001767 * - The component is enabled and runnable.
1768 */
1769 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001770 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001771
1772 if (DEBUG) {
1773 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1774 + " ready=" + jobReady);
1775 }
1776
1777 // This is a condition that is very likely to be false (most jobs that are
1778 // scheduled are sitting there, not ready yet) and very cheap to check (just
1779 // a few conditions on data in JobStatus).
1780 if (!jobReady) {
1781 return false;
1782 }
1783
1784 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001785
1786 final int userId = job.getUserId();
1787 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1788
1789 if (DEBUG) {
1790 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001791 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001792 }
1793
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001794 // These are also fairly cheap to check, though they typically will not
1795 // be conditions we fail.
1796 if (!jobExists || !userStarted) {
1797 return false;
1798 }
1799
1800 final boolean jobPending = mPendingJobs.contains(job);
1801 final boolean jobActive = isCurrentlyActiveLocked(job);
1802
1803 if (DEBUG) {
1804 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1805 + " pending=" + jobPending + " active=" + jobActive);
1806 }
1807
1808 // These can be a little more expensive (especially jobActive, since we need to
1809 // go through the array of all potentially active jobs), so we are doing them
1810 // later... but still before checking with the package manager!
1811 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001812 return false;
1813 }
1814
Christopher Tatea732f012017-10-26 17:26:53 -07001815 // If the app is in a non-active standby bucket, make sure we've waited
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001816 // an appropriate amount of time since the last invocation. During device-
1817 // wide parole, standby bucketing is ignored.
Makoto Onuki959acb52018-01-26 14:10:03 -08001818 //
1819 // But if a job has FLAG_EXEMPT_FROM_APP_STANDBY, don't check it.
1820 if (!mInParole && !job.getJob().isExemptedFromAppStandby()) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001821 final int bucket = job.getStandbyBucket();
1822 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
1823 // Only skip this job if it's still waiting for the end of its (initial) nominal
1824 // bucket interval. Once it's waited that long, we let it go ahead and clear.
1825 // The final (NEVER) bucket is special; we never age those apps' jobs into
1826 // runnability.
1827 if (bucket >= mConstants.STANDBY_BEATS.length
1828 || (mHeartbeat < job.getBaseHeartbeat() + mConstants.STANDBY_BEATS[bucket])) {
1829 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
1830 if (job.getWhenStandbyDeferred() == 0) {
1831 if (DEBUG_STANDBY) {
1832 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
1833 + mNextBucketHeartbeat[job.getStandbyBucket()] + " for " + job);
1834 }
1835 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tate0c4d7682017-12-06 15:10:22 -08001836 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001837 return false;
1838 } else {
1839 if (DEBUG_STANDBY) {
1840 Slog.v(TAG, "Bucket deferred job aged into runnability at "
1841 + mHeartbeat + " : " + job);
1842 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08001843 }
Christopher Tatea732f012017-10-26 17:26:53 -07001844 }
Christopher Tatea732f012017-10-26 17:26:53 -07001845 }
1846
1847 // The expensive check last: validate that the defined package+service is
1848 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001849 final boolean componentPresent;
1850 try {
1851 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1852 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1853 userId) != null);
1854 } catch (RemoteException e) {
1855 throw e.rethrowAsRuntimeException();
1856 }
1857
1858 if (DEBUG) {
1859 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1860 + " componentPresent=" + componentPresent);
1861 }
1862
1863 // Everything else checked out so far, so this is the final yes/no check
1864 return componentPresent;
1865 }
1866
1867 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001868 * Reconcile jobs in the pending queue against available execution contexts.
1869 * A controller can force a job into the pending queue even if it's already running, but
1870 * here is where we decide whether to actually execute it.
1871 */
1872 private void maybeRunPendingJobsLocked() {
1873 if (DEBUG) {
1874 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1875 }
1876 assignJobsToContextsLocked();
1877 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001878 }
1879
Dianne Hackborn807de782016-04-07 17:54:41 -07001880 private int adjustJobPriority(int curPriority, JobStatus job) {
1881 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1882 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001883 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001884 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001885 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001886 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1887 }
1888 }
1889 return curPriority;
1890 }
1891
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001892 private int evaluateJobPriorityLocked(JobStatus job) {
1893 int priority = job.getPriority();
1894 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001895 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001896 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001897 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1898 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001899 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001900 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001901 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001902 }
1903
Christopher Tate7060b042014-06-09 19:50:00 -07001904 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001905 * Takes jobs from pending queue and runs them on available contexts.
1906 * If no contexts are available, preempts lower priority jobs to
1907 * run higher priority ones.
1908 * Lock on mJobs before calling this function.
1909 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001910 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001911 if (DEBUG) {
1912 Slog.d(TAG, printPendingQueue());
1913 }
1914
Dianne Hackborn970510b2016-02-24 16:56:42 -08001915 int memLevel;
1916 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001917 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001918 } catch (RemoteException e) {
1919 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1920 }
1921 switch (memLevel) {
1922 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001923 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001924 break;
1925 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001926 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001927 break;
1928 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001929 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001930 break;
1931 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001932 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001933 break;
1934 }
1935
1936 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1937 boolean[] act = mTmpAssignAct;
1938 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1939 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001940 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001941 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1942 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001943 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001944 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001945 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001946 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1947 numForeground++;
1948 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001949 }
1950 act[i] = false;
1951 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001952 }
1953 if (DEBUG) {
1954 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1955 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001956 for (int i=0; i<mPendingJobs.size(); i++) {
1957 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001958
1959 // If job is already running, go to next job.
1960 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1961 if (jobRunningContext != -1) {
1962 continue;
1963 }
1964
Dianne Hackborn970510b2016-02-24 16:56:42 -08001965 final int priority = evaluateJobPriorityLocked(nextPending);
1966 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001967
Shreyas Basarge5db09082016-01-07 13:38:29 +00001968 // Find a context for nextPending. The context should be available OR
1969 // it should have lowest priority among all running jobs
1970 // (sharing the same Uid as nextPending)
1971 int minPriority = Integer.MAX_VALUE;
1972 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001973 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1974 JobStatus job = contextIdToJobMap[j];
1975 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001976 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001977 if ((numActive < mMaxActiveJobs ||
1978 (priority >= JobInfo.PRIORITY_TOP_APP &&
1979 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001980 (preferredUid == nextPending.getUid() ||
1981 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1982 // This slot is free, and we haven't yet hit the limit on
1983 // concurrent jobs... we can just throw the job in to here.
1984 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001985 break;
1986 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001987 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001988 // the context has a preferred Uid or we have reached the limit on
1989 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001990 continue;
1991 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001992 if (job.getUid() != nextPending.getUid()) {
1993 continue;
1994 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001995 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001996 continue;
1997 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001998 if (minPriority > nextPending.lastEvaluatedPriority) {
1999 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002000 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00002001 }
2002 }
2003 if (minPriorityContextId != -1) {
2004 contextIdToJobMap[minPriorityContextId] = nextPending;
2005 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002006 numActive++;
2007 if (priority >= JobInfo.PRIORITY_TOP_APP) {
2008 numForeground++;
2009 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002010 }
2011 }
2012 if (DEBUG) {
2013 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
2014 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002015 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002016 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002017 boolean preservePreferredUid = false;
2018 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002019 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002020 if (js != null) {
2021 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002022 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00002023 }
2024 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07002025 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002026 preservePreferredUid = true;
2027 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002028 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00002029 if (DEBUG) {
2030 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002031 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002032 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002033 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002034 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002035 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002036 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
2037 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002038 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002039 if (mPendingJobs.remove(pendingJob)) {
2040 mJobPackageTracker.noteNonpending(pendingJob);
2041 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002042 }
2043 }
2044 if (!preservePreferredUid) {
2045 mActiveServices.get(i).clearPreferredUid();
2046 }
2047 }
2048 }
2049
2050 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
2051 for (int i=0; i<map.length; i++) {
2052 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
2053 return i;
2054 }
2055 }
2056 return -1;
2057 }
2058
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002059 final class LocalService implements JobSchedulerInternal {
2060
2061 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002062 * The current bucket heartbeat ordinal
2063 */
2064 public long currentHeartbeat() {
2065 return getCurrentHeartbeat();
2066 }
2067
2068 /**
2069 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2070 */
2071 public long nextHeartbeatForBucket(int bucket) {
2072 synchronized (mLock) {
2073 return mNextBucketHeartbeat[bucket];
2074 }
2075 }
2076
2077 /**
Christopher Tate435c2f42018-01-18 12:59:15 -08002078 * Heartbeat ordinal for the given app. This is typically the heartbeat at which
2079 * the app last ran jobs, so that a newly-scheduled job in an app that hasn't run
2080 * jobs in a long time is immediately runnable even if the app is bucketed into
2081 * an infrequent time allocation.
2082 */
2083 public long baseHeartbeatForApp(String packageName, @UserIdInt int userId,
2084 final int appStandbyBucket) {
2085 if (appStandbyBucket == 0 ||
2086 appStandbyBucket >= mConstants.STANDBY_BEATS.length) {
2087 // ACTIVE => everything can be run right away
2088 // NEVER => we won't run them anyway, so let them go in the future
2089 // as soon as the app enters normal use
2090 return 0;
2091 }
2092
2093 final long timeSinceLastJob = mStandbyTracker.getTimeSinceLastJobRun(
2094 packageName, userId);
2095 final long bucketLength = mConstants.STANDBY_BEATS[appStandbyBucket];
2096 final long bucketsAgo = timeSinceLastJob / bucketLength;
2097
2098 // If we haven't run any jobs for more than the app's current bucket period, just
2099 // consider anything new to be immediately runnable. Otherwise, base it on the
2100 // bucket at which we last ran jobs.
2101 return (bucketsAgo > bucketLength) ? 0 : (getCurrentHeartbeat() - bucketsAgo);
2102 }
2103
2104 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002105 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2106 * jobs are always considered pending.
2107 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002108 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002109 public List<JobInfo> getSystemScheduledPendingJobs() {
2110 synchronized (mLock) {
2111 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
2112 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
2113 @Override
2114 public void process(JobStatus job) {
2115 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2116 pendingJobs.add(job.getJob());
2117 }
2118 }
2119 });
2120 return pendingJobs;
2121 }
2122 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002123
2124 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002125 public void cancelJobsForUid(int uid, String reason) {
2126 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2127 }
2128
2129 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002130 public void addBackingUpUid(int uid) {
2131 synchronized (mLock) {
2132 // No need to actually do anything here, since for a full backup the
2133 // activity manager will kill the process which will kill the job (and
2134 // cause it to restart, but now it can't run).
2135 mBackingUpUids.put(uid, uid);
2136 }
2137 }
2138
2139 @Override
2140 public void removeBackingUpUid(int uid) {
2141 synchronized (mLock) {
2142 mBackingUpUids.delete(uid);
2143 // If there are any jobs for this uid, we need to rebuild the pending list
2144 // in case they are now ready to run.
2145 if (mJobs.countJobsForUid(uid) > 0) {
2146 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2147 }
2148 }
2149 }
2150
2151 @Override
2152 public void clearAllBackingUpUids() {
2153 synchronized (mLock) {
2154 if (mBackingUpUids.size() > 0) {
2155 mBackingUpUids.clear();
2156 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2157 }
2158 }
2159 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002160
2161 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002162 public void reportAppUsage(String packageName, int userId) {
2163 JobSchedulerService.this.reportAppUsage(packageName, userId);
2164 }
2165
2166 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002167 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002168 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002169 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002170 }
2171 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002172 }
2173
Shreyas Basarge5db09082016-01-07 13:38:29 +00002174 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002175 * Tracking of app assignments to standby buckets
2176 */
2177 final class StandbyTracker extends AppIdleStateChangeListener {
2178 final UsageStatsManagerInternal mUsageStats;
2179
2180 StandbyTracker(UsageStatsManagerInternal usageStats) {
2181 mUsageStats = usageStats;
2182 }
2183
Christopher Tate435c2f42018-01-18 12:59:15 -08002184 public long getTimeSinceLastJobRun(String packageName, final @UserIdInt int userId) {
2185 return mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2186 }
2187
Christopher Tatea732f012017-10-26 17:26:53 -07002188 // AppIdleStateChangeListener interface for live updates
2189
2190 @Override
Christopher Tate435c2f42018-01-18 12:59:15 -08002191 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Christopher Tatea732f012017-10-26 17:26:53 -07002192 boolean idle, int bucket) {
2193 final int uid = mLocalPM.getPackageUid(packageName,
2194 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2195 if (uid < 0) {
2196 if (DEBUG_STANDBY) {
2197 Slog.i(TAG, "App idle state change for unknown app "
2198 + packageName + "/" + userId);
2199 }
2200 return;
2201 }
2202
2203 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2204 // update job bookkeeping out of band
2205 BackgroundThread.getHandler().post(() -> {
2206 if (DEBUG_STANDBY) {
2207 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2208 }
2209 synchronized (mLock) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08002210 mJobs.forEachJobForSourceUid(uid, job -> job.setStandbyBucket(bucketIndex));
Christopher Tatea732f012017-10-26 17:26:53 -07002211 onControllerStateChanged();
2212 }
2213 });
2214 }
2215
2216 @Override
2217 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002218 if (DEBUG_STANDBY) {
2219 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2220 }
2221 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002222 }
Christopher Tated117b292018-01-05 17:32:36 -08002223
2224 @Override
2225 public void onUserInteractionStarted(String packageName, int userId) {
2226 final int uid = mLocalPM.getPackageUid(packageName,
2227 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2228 if (uid < 0) {
2229 // Quietly ignore; the case is already logged elsewhere
2230 return;
2231 }
2232
2233 final long sinceLast = sElapsedRealtimeClock.millis() -
2234 mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2235 final DeferredJobCounter counter = new DeferredJobCounter();
2236 synchronized (mLock) {
2237 mJobs.forEachJobForSourceUid(uid, counter);
2238 }
2239
2240 mUsageStats.reportAppJobState(packageName, userId, counter.numDeferred(), sinceLast);
2241 }
2242 }
2243
2244 static class DeferredJobCounter implements JobStatusFunctor {
2245 private int mDeferred = 0;
2246
2247 public int numDeferred() {
2248 return mDeferred;
2249 }
2250
2251 @Override
2252 public void process(JobStatus job) {
2253 if (job.getWhenStandbyDeferred() > 0) {
2254 mDeferred++;
2255 }
2256 }
Christopher Tatea732f012017-10-26 17:26:53 -07002257 }
2258
2259 public static int standbyBucketToBucketIndex(int bucket) {
2260 // Normalize AppStandby constants to indices into our bookkeeping
Amith Yamasaniafbccb72017-11-27 10:44:24 -08002261 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return 4;
2262 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) return 3;
2263 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) return 2;
2264 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return 1;
Christopher Tatea732f012017-10-26 17:26:53 -07002265 else return 0;
2266 }
2267
2268 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2269 UsageStatsManagerInternal usageStats = LocalServices.getService(
2270 UsageStatsManagerInternal.class);
2271 int bucket = usageStats != null
2272 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2273 : 0;
2274
2275 bucket = standbyBucketToBucketIndex(bucket);
2276
2277 if (DEBUG_STANDBY) {
2278 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2279 }
2280 return bucket;
2281 }
2282
2283 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002284 * Binder stub trampoline implementation
2285 */
2286 final class JobSchedulerStub extends IJobScheduler.Stub {
2287 /** Cache determination of whether a given app can persist jobs
2288 * key is uid of the calling app; value is undetermined/true/false
2289 */
2290 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2291
2292 // Enforce that only the app itself (or shared uid participant) can schedule a
2293 // job that runs one of the app's services, as well as verifying that the
2294 // named service properly requires the BIND_JOB_SERVICE permission
2295 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002296 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002297 final ComponentName service = job.getService();
2298 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002299 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002300 PackageManager.MATCH_DIRECT_BOOT_AWARE
2301 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002302 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002303 if (si == null) {
2304 throw new IllegalArgumentException("No such service " + service);
2305 }
Christopher Tate7060b042014-06-09 19:50:00 -07002306 if (si.applicationInfo.uid != uid) {
2307 throw new IllegalArgumentException("uid " + uid +
2308 " cannot schedule job in " + service.getPackageName());
2309 }
2310 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2311 throw new IllegalArgumentException("Scheduled service " + service
2312 + " does not require android.permission.BIND_JOB_SERVICE permission");
2313 }
Christopher Tate5568f542014-06-18 13:53:31 -07002314 } catch (RemoteException e) {
2315 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002316 }
2317 }
2318
2319 private boolean canPersistJobs(int pid, int uid) {
2320 // If we get this far we're good to go; all we need to do now is check
2321 // whether the app is allowed to persist its scheduled work.
2322 final boolean canPersist;
2323 synchronized (mPersistCache) {
2324 Boolean cached = mPersistCache.get(uid);
2325 if (cached != null) {
2326 canPersist = cached.booleanValue();
2327 } else {
2328 // Persisting jobs is tantamount to running at boot, so we permit
2329 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2330 // permission
2331 int result = getContext().checkPermission(
2332 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2333 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2334 mPersistCache.put(uid, canPersist);
2335 }
2336 }
2337 return canPersist;
2338 }
2339
Makoto Onuki959acb52018-01-26 14:10:03 -08002340 private void validateJobFlags(JobInfo job, int callingUid) {
2341 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2342 getContext().enforceCallingOrSelfPermission(
2343 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2344 }
2345 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
2346 if (callingUid != Process.SYSTEM_UID) {
2347 throw new SecurityException("Job has invalid flags");
2348 }
Makoto Onuki2b5811a2018-02-08 11:09:42 -08002349 if (job.isPeriodic()) {
2350 Slog.wtf(TAG, "Periodic jobs mustn't have"
2351 + " FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
Makoto Onuki959acb52018-01-26 14:10:03 -08002352 }
2353 }
2354 }
2355
Christopher Tate7060b042014-06-09 19:50:00 -07002356 // IJobScheduler implementation
2357 @Override
2358 public int schedule(JobInfo job) throws RemoteException {
2359 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002360 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002361 }
2362 final int pid = Binder.getCallingPid();
2363 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002364 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002365
2366 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002367 if (job.isPersisted()) {
2368 if (!canPersistJobs(pid, uid)) {
2369 throw new IllegalArgumentException("Error: requested job be persisted without"
2370 + " holding RECEIVE_BOOT_COMPLETED permission.");
2371 }
2372 }
Christopher Tate7060b042014-06-09 19:50:00 -07002373
Makoto Onuki959acb52018-01-26 14:10:03 -08002374 validateJobFlags(job, uid);
Jeff Sharkey785f4942016-07-14 10:31:15 -06002375
Christopher Tate7060b042014-06-09 19:50:00 -07002376 long ident = Binder.clearCallingIdentity();
2377 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002378 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2379 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002380 } finally {
2381 Binder.restoreCallingIdentity(ident);
2382 }
2383 }
2384
2385 // IJobScheduler implementation
2386 @Override
2387 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2388 if (DEBUG) {
2389 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2390 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002391 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002392 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002393
2394 enforceValidJobRequest(uid, job);
2395 if (job.isPersisted()) {
2396 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2397 }
2398 if (work == null) {
2399 throw new NullPointerException("work is null");
2400 }
2401
Makoto Onuki959acb52018-01-26 14:10:03 -08002402 validateJobFlags(job, uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002403
2404 long ident = Binder.clearCallingIdentity();
2405 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002406 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2407 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002408 } finally {
2409 Binder.restoreCallingIdentity(ident);
2410 }
2411 }
2412
2413 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002414 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002415 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002416 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002417 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002418 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002419 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002420 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002421
2422 if (packageName == null) {
2423 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002424 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002425
2426 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2427 android.Manifest.permission.UPDATE_DEVICE_STATS);
2428 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2429 throw new SecurityException("Caller uid " + callerUid
2430 + " not permitted to schedule jobs for other apps");
2431 }
2432
Makoto Onuki959acb52018-01-26 14:10:03 -08002433 validateJobFlags(job, callerUid);
Jeff Sharkey4f100402016-05-03 17:44:23 -06002434
Shreyas Basarge968ac752016-01-11 23:09:26 +00002435 long ident = Binder.clearCallingIdentity();
2436 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002437 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002438 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002439 } finally {
2440 Binder.restoreCallingIdentity(ident);
2441 }
2442 }
2443
2444 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002445 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2446 final int uid = Binder.getCallingUid();
2447
2448 long ident = Binder.clearCallingIdentity();
2449 try {
2450 return JobSchedulerService.this.getPendingJobs(uid);
2451 } finally {
2452 Binder.restoreCallingIdentity(ident);
2453 }
2454 }
2455
2456 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002457 public JobInfo getPendingJob(int jobId) throws RemoteException {
2458 final int uid = Binder.getCallingUid();
2459
2460 long ident = Binder.clearCallingIdentity();
2461 try {
2462 return JobSchedulerService.this.getPendingJob(uid, jobId);
2463 } finally {
2464 Binder.restoreCallingIdentity(ident);
2465 }
2466 }
2467
2468 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002469 public void cancelAll() throws RemoteException {
2470 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002471 long ident = Binder.clearCallingIdentity();
2472 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002473 JobSchedulerService.this.cancelJobsForUid(uid,
2474 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002475 } finally {
2476 Binder.restoreCallingIdentity(ident);
2477 }
2478 }
2479
2480 @Override
2481 public void cancel(int jobId) throws RemoteException {
2482 final int uid = Binder.getCallingUid();
2483
2484 long ident = Binder.clearCallingIdentity();
2485 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002486 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002487 } finally {
2488 Binder.restoreCallingIdentity(ident);
2489 }
2490 }
2491
2492 /**
2493 * "dumpsys" infrastructure
2494 */
2495 @Override
2496 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002497 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002498
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002499 int filterUid = -1;
2500 boolean proto = false;
2501 if (!ArrayUtils.isEmpty(args)) {
2502 int opti = 0;
2503 while (opti < args.length) {
2504 String arg = args[opti];
2505 if ("-h".equals(arg)) {
2506 dumpHelp(pw);
2507 return;
2508 } else if ("-a".equals(arg)) {
2509 // Ignore, we always dump all.
2510 } else if ("--proto".equals(arg)) {
2511 proto = true;
2512 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2513 pw.println("Unknown option: " + arg);
2514 return;
2515 } else {
2516 break;
2517 }
2518 opti++;
2519 }
2520 if (opti < args.length) {
2521 String pkg = args[opti];
2522 try {
2523 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2524 PackageManager.MATCH_ANY_USER);
2525 } catch (NameNotFoundException ignored) {
2526 pw.println("Invalid package: " + pkg);
2527 return;
2528 }
2529 }
2530 }
2531
Christopher Tate7060b042014-06-09 19:50:00 -07002532 long identityToken = Binder.clearCallingIdentity();
2533 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002534 if (proto) {
2535 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2536 } else {
2537 JobSchedulerService.this.dumpInternal(pw, filterUid);
2538 }
Christopher Tate7060b042014-06-09 19:50:00 -07002539 } finally {
2540 Binder.restoreCallingIdentity(identityToken);
2541 }
2542 }
Christopher Tate5d346052016-03-08 12:56:08 -08002543
2544 @Override
2545 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002546 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002547 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002548 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002549 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002550 };
2551
Christopher Tate5d346052016-03-08 12:56:08 -08002552 // Shell command infrastructure: run the given job immediately
2553 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2554 if (DEBUG) {
2555 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2556 + " " + jobId + " f=" + force);
2557 }
2558
2559 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002560 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2561 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002562 if (uid < 0) {
2563 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2564 }
2565
2566 synchronized (mLock) {
2567 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2568 if (js == null) {
2569 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2570 }
2571
2572 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2573 if (!js.isConstraintsSatisfied()) {
2574 js.overrideState = 0;
2575 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2576 }
2577
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002578 queueReadyJobsForExecutionLocked();
2579 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002580 }
2581 } catch (RemoteException e) {
2582 // can't happen
2583 }
2584 return 0;
2585 }
2586
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002587 // Shell command infrastructure: immediately timeout currently executing jobs
2588 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2589 boolean hasJobId, int jobId) {
2590 if (DEBUG) {
2591 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2592 }
2593
2594 synchronized (mLock) {
2595 boolean foundSome = false;
2596 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002597 final JobServiceContext jc = mActiveServices.get(i);
2598 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002599 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002600 foundSome = true;
2601 pw.print("Timing out: ");
2602 js.printUniqueId(pw);
2603 pw.print(" ");
2604 pw.println(js.getServiceComponent().flattenToShortString());
2605 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002606 }
2607 if (!foundSome) {
2608 pw.println("No matching executing jobs found.");
2609 }
2610 }
2611 return 0;
2612 }
2613
Christopher Tate8c67d122017-09-29 16:54:26 -07002614 // Shell command infrastructure: cancel a scheduled job
2615 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2616 boolean hasJobId, int jobId) {
2617 if (DEBUG) {
2618 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2619 }
2620
2621 int pkgUid = -1;
2622 try {
2623 IPackageManager pm = AppGlobals.getPackageManager();
2624 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2625 } catch (RemoteException e) { /* can't happen */ }
2626
2627 if (pkgUid < 0) {
2628 pw.println("Package " + pkgName + " not found.");
2629 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2630 }
2631
2632 if (!hasJobId) {
2633 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2634 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2635 pw.println("No matching jobs found.");
2636 }
2637 } else {
2638 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002639 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002640 pw.println("No matching job found.");
2641 }
2642 }
2643
2644 return 0;
2645 }
2646
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002647 void setMonitorBattery(boolean enabled) {
2648 synchronized (mLock) {
2649 if (mBatteryController != null) {
2650 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2651 }
2652 }
2653 }
2654
2655 int getBatterySeq() {
2656 synchronized (mLock) {
2657 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2658 }
2659 }
2660
2661 boolean getBatteryCharging() {
2662 synchronized (mLock) {
2663 return mBatteryController != null
2664 ? mBatteryController.getTracker().isOnStablePower() : false;
2665 }
2666 }
2667
2668 boolean getBatteryNotLow() {
2669 synchronized (mLock) {
2670 return mBatteryController != null
2671 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2672 }
2673 }
2674
Dianne Hackborn532ea262017-03-17 17:50:55 -07002675 int getStorageSeq() {
2676 synchronized (mLock) {
2677 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2678 }
2679 }
2680
2681 boolean getStorageNotLow() {
2682 synchronized (mLock) {
2683 return mStorageController != null
2684 ? mStorageController.getTracker().isStorageNotLow() : false;
2685 }
2686 }
2687
Christopher Tatea732f012017-10-26 17:26:53 -07002688 long getCurrentHeartbeat() {
2689 synchronized (mLock) {
2690 return mHeartbeat;
2691 }
2692 }
2693
Dianne Hackborn6d068262017-05-16 13:14:37 -07002694 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2695 try {
2696 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2697 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2698 if (uid < 0) {
2699 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2700 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2701 }
2702
2703 synchronized (mLock) {
2704 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2705 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2706 if (js == null) {
2707 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2708 pw.print("/jid"); pw.print(jobId); pw.println(")");
2709 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2710 }
2711
2712 boolean printed = false;
2713 if (mPendingJobs.contains(js)) {
2714 pw.print("pending");
2715 printed = true;
2716 }
2717 if (isCurrentlyActiveLocked(js)) {
2718 if (printed) {
2719 pw.print(" ");
2720 }
2721 printed = true;
2722 pw.println("active");
2723 }
2724 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2725 if (printed) {
2726 pw.print(" ");
2727 }
2728 printed = true;
2729 pw.println("user-stopped");
2730 }
2731 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2732 if (printed) {
2733 pw.print(" ");
2734 }
2735 printed = true;
2736 pw.println("backing-up");
2737 }
2738 boolean componentPresent = false;
2739 try {
2740 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2741 js.getServiceComponent(),
2742 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2743 js.getUserId()) != null);
2744 } catch (RemoteException e) {
2745 }
2746 if (!componentPresent) {
2747 if (printed) {
2748 pw.print(" ");
2749 }
2750 printed = true;
2751 pw.println("no-component");
2752 }
2753 if (js.isReady()) {
2754 if (printed) {
2755 pw.print(" ");
2756 }
2757 printed = true;
2758 pw.println("ready");
2759 }
2760 if (!printed) {
2761 pw.print("waiting");
2762 }
2763 pw.println();
2764 }
2765 } catch (RemoteException e) {
2766 // can't happen
2767 }
2768 return 0;
2769 }
2770
Shreyas Basarge5db09082016-01-07 13:38:29 +00002771 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2772 StringBuilder s = new StringBuilder(initial + ": ");
2773 for (int i=0; i<map.length; i++) {
2774 s.append("(")
2775 .append(map[i] == null? -1: map[i].getJobId())
2776 .append(map[i] == null? -1: map[i].getUid())
2777 .append(")" );
2778 }
2779 return s.toString();
2780 }
2781
2782 private String printPendingQueue() {
2783 StringBuilder s = new StringBuilder("Pending queue: ");
2784 Iterator<JobStatus> it = mPendingJobs.iterator();
2785 while (it.hasNext()) {
2786 JobStatus js = it.next();
2787 s.append("(")
2788 .append(js.getJob().getId())
2789 .append(", ")
2790 .append(js.getUid())
2791 .append(") ");
2792 }
2793 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002794 }
Christopher Tate7060b042014-06-09 19:50:00 -07002795
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002796 static void dumpHelp(PrintWriter pw) {
2797 pw.println("Job Scheduler (jobscheduler) dump options:");
2798 pw.println(" [-h] [package] ...");
2799 pw.println(" -h: print this help");
2800 pw.println(" [package] is an optional package name to limit the output to.");
2801 }
2802
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002803 /** Sort jobs by caller UID, then by Job ID. */
2804 private static void sortJobs(List<JobStatus> jobs) {
2805 Collections.sort(jobs, new Comparator<JobStatus>() {
2806 @Override
2807 public int compare(JobStatus o1, JobStatus o2) {
2808 int uid1 = o1.getUid();
2809 int uid2 = o2.getUid();
2810 int id1 = o1.getJobId();
2811 int id2 = o2.getJobId();
2812 if (uid1 != uid2) {
2813 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002814 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002815 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002816 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002817 });
2818 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002819
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002820 void dumpInternal(final PrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002821 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07002822 final long nowElapsed = sElapsedRealtimeClock.millis();
2823 final long nowUptime = sUptimeMillisClock.millis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002824 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002825 mConstants.dump(pw);
2826 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002827 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002828 pw.print("Registered ");
2829 pw.print(mJobs.size());
2830 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002831 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002832 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002833 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002834 for (JobStatus job : jobs) {
2835 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2836 pw.println(job.toShortStringExceptUniqueId());
2837
2838 // Skip printing details if the caller requested a filter
2839 if (!job.shouldDump(filterUidFinal)) {
2840 continue;
2841 }
2842
Dianne Hackborn6d068262017-05-16 13:14:37 -07002843 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002844 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002845 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002846 pw.print(" (job=");
2847 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002848 pw.print(" user=");
2849 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002850 pw.print(" !pending=");
2851 pw.print(!mPendingJobs.contains(job));
2852 pw.print(" !active=");
2853 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002854 pw.print(" !backingup=");
2855 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002856 pw.print(" comp=");
2857 boolean componentPresent = false;
2858 try {
2859 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2860 job.getServiceComponent(),
2861 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2862 job.getUserId()) != null);
2863 } catch (RemoteException e) {
2864 }
2865 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002866 pw.println(")");
2867 }
Christopher Tate7060b042014-06-09 19:50:00 -07002868 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002869 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002870 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002871 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002872 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002873 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002874 }
2875 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002876 pw.println("Uid priority overrides:");
2877 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002878 int uid = mUidPriorityOverride.keyAt(i);
2879 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2880 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2881 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2882 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002883 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002884 if (mBackingUpUids.size() > 0) {
2885 pw.println();
2886 pw.println("Backing up uids:");
2887 boolean first = true;
2888 for (int i = 0; i < mBackingUpUids.size(); i++) {
2889 int uid = mBackingUpUids.keyAt(i);
2890 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2891 if (first) {
2892 pw.print(" ");
2893 first = false;
2894 } else {
2895 pw.print(", ");
2896 }
2897 pw.print(UserHandle.formatUid(uid));
2898 }
2899 }
2900 pw.println();
2901 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002902 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002903 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002904 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002905 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2906 pw.println();
2907 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002908 pw.println("Pending queue:");
2909 for (int i=0; i<mPendingJobs.size(); i++) {
2910 JobStatus job = mPendingJobs.get(i);
2911 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2912 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002913 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002914 int priority = evaluateJobPriorityLocked(job);
2915 if (priority != JobInfo.PRIORITY_DEFAULT) {
2916 pw.print(" Evaluated priority: "); pw.println(priority);
2917 }
2918 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002919 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002920 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002921 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002922 }
Christopher Tate7060b042014-06-09 19:50:00 -07002923 pw.println();
2924 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002925 for (int i=0; i<mActiveServices.size(); i++) {
2926 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002927 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002928 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002929 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002930 if (jsc.mStoppedReason != null) {
2931 pw.print("inactive since ");
2932 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2933 pw.print(", stopped because: ");
2934 pw.println(jsc.mStoppedReason);
2935 } else {
2936 pw.println("inactive");
2937 }
Christopher Tate7060b042014-06-09 19:50:00 -07002938 continue;
2939 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002940 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002941 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002942 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002943 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002944 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002945 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002946 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002947 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002948 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002949 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002950 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002951 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002952 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002953 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002954 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2955 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002956 }
2957 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002958 if (filterUid == -1) {
2959 pw.println();
2960 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2961 pw.print("mReportedActive="); pw.println(mReportedActive);
2962 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2963 }
Makoto Onukie7b02982017-08-24 14:23:36 -07002964 pw.println();
2965 pw.print("PersistStats: ");
2966 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07002967 }
2968 pw.println();
2969 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002970
2971 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
2972 ProtoOutputStream proto = new ProtoOutputStream(fd);
2973 final int filterUidFinal = UserHandle.getAppId(filterUid);
2974 final long nowElapsed = sElapsedRealtimeClock.millis();
2975 final long nowUptime = sUptimeMillisClock.millis();
2976
2977 synchronized (mLock) {
2978 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
2979 for (int u : mStartedUsers) {
2980 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
2981 }
2982 if (mJobs.size() > 0) {
2983 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2984 sortJobs(jobs);
2985 for (JobStatus job : jobs) {
2986 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
2987 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
2988
2989 // Skip printing details if the caller requested a filter
2990 if (!job.shouldDump(filterUidFinal)) {
2991 continue;
2992 }
2993
2994 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
2995
2996 // isReadyToBeExecuted
2997 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
2998 job.isReady());
2999 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
3000 ArrayUtils.contains(mStartedUsers, job.getUserId()));
3001 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
3002 mPendingJobs.contains(job));
3003 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
3004 isCurrentlyActiveLocked(job));
3005 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
3006 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
3007 boolean componentPresent = false;
3008 try {
3009 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3010 job.getServiceComponent(),
3011 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3012 job.getUserId()) != null);
3013 } catch (RemoteException e) {
3014 }
3015 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
3016 componentPresent);
3017
3018 proto.end(rjToken);
3019 }
3020 }
3021 for (StateController controller : mControllers) {
3022 controller.dumpControllerStateLocked(
3023 proto, JobSchedulerServiceDumpProto.CONTROLLERS, filterUidFinal);
3024 }
3025 for (int i=0; i< mUidPriorityOverride.size(); i++) {
3026 int uid = mUidPriorityOverride.keyAt(i);
3027 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3028 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3029 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3030 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3031 mUidPriorityOverride.valueAt(i));
3032 proto.end(pToken);
3033 }
3034 }
3035 for (int i = 0; i < mBackingUpUids.size(); i++) {
3036 int uid = mBackingUpUids.keyAt(i);
3037 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3038 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3039 }
3040 }
3041
3042 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3043 filterUidFinal);
3044 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3045 filterUidFinal);
3046
3047 for (JobStatus job : mPendingJobs) {
3048 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3049
3050 job.writeToShortProto(proto, PendingJob.INFO);
3051 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
3052 int priority = evaluateJobPriorityLocked(job);
3053 if (priority != JobInfo.PRIORITY_DEFAULT) {
3054 proto.write(PendingJob.EVALUATED_PRIORITY, priority);
3055 }
3056 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
3057
3058 proto.end(pjToken);
3059 }
3060 for (JobServiceContext jsc : mActiveServices) {
3061 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
3062 final JobStatus job = jsc.getRunningJobLocked();
3063
3064 if (job == null) {
3065 final long ijToken = proto.start(ActiveJob.INACTIVE);
3066
3067 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
3068 nowElapsed - jsc.mStoppedTime);
3069 if (jsc.mStoppedReason != null) {
3070 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
3071 jsc.mStoppedReason);
3072 }
3073
3074 proto.end(ijToken);
3075 } else {
3076 final long rjToken = proto.start(ActiveJob.RUNNING);
3077
3078 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
3079
3080 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
3081 nowElapsed - jsc.getExecutionStartTimeElapsed());
3082 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
3083 jsc.getTimeoutElapsed() - nowElapsed);
3084
3085 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3086
3087 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
3088 if (priority != JobInfo.PRIORITY_DEFAULT) {
3089 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY, priority);
3090 }
3091
3092 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3093 nowUptime - job.madeActive);
3094 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3095 job.madeActive - job.madePending);
3096
3097 proto.end(rjToken);
3098 }
3099 proto.end(ajToken);
3100 }
3101 if (filterUid == -1) {
3102 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3103 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3104 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
3105 }
3106 }
3107
3108 proto.flush();
3109 }
Christopher Tate7060b042014-06-09 19:50:00 -07003110}