blob: d895636895d3d9d9d3928c066e7943e1e6bcba98 [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.job;
18
Christopher Tateb5c07882016-05-26 17:11:09 -070019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21
Christopher Tateee7805b2016-07-15 16:56:56 -070022import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070023import android.app.ActivityManager;
Christopher Tate5568f542014-06-18 13:53:31 -070024import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070025import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070026import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070027import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000028import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.app.job.JobScheduler;
30import android.app.job.JobService;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070031import android.app.job.JobWorkItem;
Amith Yamasaniafbccb72017-11-27 10:44:24 -080032import android.app.usage.UsageStatsManager;
Christopher Tatea732f012017-10-26 17:26:53 -070033import android.app.usage.UsageStatsManagerInternal;
34import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
Christopher Tate7060b042014-06-09 19:50:00 -070035import android.content.BroadcastReceiver;
36import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070037import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070038import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070041import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070042import android.content.pm.PackageManager;
Christopher Tatea732f012017-10-26 17:26:53 -070043import android.content.pm.PackageManagerInternal;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060044import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070045import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070046import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070047import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070048import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070049import android.os.Binder;
50import android.os.Handler;
51import android.os.Looper;
52import android.os.Message;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070053import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070054import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080055import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070056import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070057import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070058import android.os.SystemClock;
59import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070060import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070061import android.provider.Settings;
62import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070063import android.util.Slog;
64import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080065import android.util.SparseIntArray;
66import android.util.TimeUtils;
Christopher Tate5d346052016-03-08 12:56:08 -080067
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070068import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070069import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070070import com.android.internal.app.procstats.ProcessStats;
Christopher Tatea732f012017-10-26 17:26:53 -070071import com.android.internal.os.BackgroundThread;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070072import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060073import com.android.internal.util.DumpUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080074import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070075import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080076import com.android.server.LocalServices;
Christopher Tate2f36fd62016-02-18 18:36:08 -080077import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080078import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070079import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070080import com.android.server.job.controllers.BatteryController;
81import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080082import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070083import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070084import com.android.server.job.controllers.IdleController;
85import com.android.server.job.controllers.JobStatus;
86import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070087import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070088import com.android.server.job.controllers.TimeController;
89
Jeff Sharkey822cbd12016-02-25 11:09:55 -070090import libcore.util.EmptyArray;
91
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070092import java.io.FileDescriptor;
93import java.io.PrintWriter;
94import java.time.Clock;
95import java.util.ArrayList;
96import java.util.Arrays;
97import java.util.Collections;
98import java.util.Comparator;
99import java.util.Iterator;
100import java.util.List;
101
Christopher Tate7060b042014-06-09 19:50:00 -0700102/**
103 * Responsible for taking jobs representing work to be performed by a client app, and determining
104 * based on the criteria specified when that job should be run against the client application's
105 * endpoint.
106 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
107 * about constraints, or the state of active jobs. It receives callbacks from the various
108 * controllers and completed jobs and operates accordingly.
109 *
110 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
111 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
112 * @hide
113 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800114public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700115 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800116 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700117 public static final boolean DEBUG = false;
Christopher Tatea732f012017-10-26 17:26:53 -0700118 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800119
Dianne Hackborn970510b2016-02-24 16:56:42 -0800120 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700121 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800122 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800123 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800124 /** The maximum number of jobs that we allow an unprivileged app to schedule */
125 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700126
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700127 @VisibleForTesting
128 public static Clock sSystemClock = Clock.systemUTC();
129 @VisibleForTesting
130 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
131 @VisibleForTesting
132 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800133
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800134 /** Global local for all job scheduler state. */
135 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700136 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700137 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700138 /** Tracking the standby bucket state of each app */
139 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700140 /** Tracking amount of time each package runs for. */
141 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700142
143 static final int MSG_JOB_EXPIRED = 0;
144 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700145 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000146 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700147
Christopher Tate7060b042014-06-09 19:50:00 -0700148 /**
149 * Track Services that have currently active or pending jobs. The index is provided by
150 * {@link JobStatus#getServiceToken()}
151 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700152 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700153 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700154 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800155 /** Need direct access to this for testing. */
156 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700157 /** Need direct access to this for testing. */
158 StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700159 /** Need directly for sending uid state changes */
160 private BackgroundJobsController mBackgroundJobsController;
Suprabh Shukla106203b2017-11-02 21:23:44 -0700161 private DeviceIdleJobsController mDeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700162 /**
163 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
164 * when ready to execute them.
165 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700166 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700167
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700168 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700169
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700170 final JobHandler mHandler;
171 final JobSchedulerStub mJobSchedulerStub;
172
Christopher Tatea732f012017-10-26 17:26:53 -0700173 PackageManagerInternal mLocalPM;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700174 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800175 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700176
177 /**
178 * Set to true once we are allowed to run third party apps.
179 */
180 boolean mReadyToRock;
181
Christopher Tate7060b042014-06-09 19:50:00 -0700182 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800183 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800184 */
185 boolean mReportedActive;
186
187 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800188 * Are we currently in device-wide standby parole?
189 */
190 volatile boolean mInParole;
191
192 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800193 * Current limit on the number of concurrent JobServiceContext entries we want to
194 * keep actively running a job.
195 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700196 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800197
198 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800199 * Which uids are currently in the foreground.
200 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800201 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
202
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700203 /**
204 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
205 */
206 final SparseIntArray mBackingUpUids = new SparseIntArray();
207
Christopher Tatea732f012017-10-26 17:26:53 -0700208 /**
209 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
210 * next become runnable. Index into this array is by normalized bucket:
211 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
212 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
213 * and NEVER apps don't get them at all.
214 */
215 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
216 long mHeartbeat = 0;
217 long mLastHeartbeatTime = 0;
218
Dianne Hackborn970510b2016-02-24 16:56:42 -0800219 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
220
221 /**
222 * This array essentially stores the state of mActiveServices array.
223 * The ith index stores the job present on the ith JobServiceContext.
224 * We manipulate this array until we arrive at what jobs should be running on
225 * what JobServiceContext.
226 */
227 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
228 /**
229 * Indicates whether we need to act on this jobContext id
230 */
231 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
232 /**
233 * The uid whose jobs we would like to assign to a context.
234 */
235 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800236
237 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700238 * All times are in milliseconds. These constants are kept synchronized with the system
239 * global Settings. Any access to this class or its fields should be done while
240 * holding the JobSchedulerService.mLock lock.
241 */
242 private final class Constants extends ContentObserver {
243 // Key names stored in the settings value.
244 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
245 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800246 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700247 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700248 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
249 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
250 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
251 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
252 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
253 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
254 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
255 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
256 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
257 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700258 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
259 = "max_standard_reschedule_count";
260 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
261 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
262 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700263 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
264 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
265 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
266 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700267
268 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
269 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800270 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700271 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700272 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
273 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
274 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
275 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
276 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
277 private static final int DEFAULT_FG_JOB_COUNT = 4;
278 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
279 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700280 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700281 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700282 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
283 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
284 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
285 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700286 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000287 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
288 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700289 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700290
291 /**
292 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
293 * early.
294 */
295 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
296 /**
297 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
298 * things early.
299 */
300 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
301 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800302 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
303 * schedule things early.
304 */
305 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
306 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700307 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
308 * schedule things early.
309 */
310 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
311 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700312 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
313 * things early. 1 == Run connectivity jobs as soon as ready.
314 */
315 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
316 /**
317 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
318 * schedule things early.
319 */
320 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
321 /**
322 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
323 * running some work early. This (and thus the other min counts) is now set to 1, to
324 * prevent any batching at this level. Since we now do batching through doze, that is
325 * a much better mechanism.
326 */
327 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
328 /**
329 * This is the job execution factor that is considered to be heavy use of the system.
330 */
331 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
332 /**
333 * This is the job execution factor that is considered to be moderate use of the system.
334 */
335 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
336 /**
337 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
338 */
339 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
340 /**
341 * The maximum number of background jobs we allow when the system is in a normal
342 * memory state.
343 */
344 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
345 /**
346 * The maximum number of background jobs we allow when the system is in a moderate
347 * memory state.
348 */
349 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
350 /**
351 * The maximum number of background jobs we allow when the system is in a low
352 * memory state.
353 */
354 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
355 /**
356 * The maximum number of background jobs we allow when the system is in a critical
357 * memory state.
358 */
359 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700360 /**
361 * The maximum number of times we allow a job to have itself rescheduled before
362 * giving up on it, for standard jobs.
363 */
364 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
365 /**
366 * The maximum number of times we allow a job to have itself rescheduled before
367 * giving up on it, for jobs that are executing work.
368 */
369 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
370 /**
371 * The minimum backoff time to allow for linear backoff.
372 */
373 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
374 /**
375 * The minimum backoff time to allow for exponential backoff.
376 */
377 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700378 /**
379 * How often we recalculate runnability based on apps' standby bucket assignment.
380 * This should be prime relative to common time interval lengths such as a quarter-
381 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
382 */
383 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
384
385 /**
386 * Mapping: standby bucket -> number of heartbeats between each sweep of that
387 * bucket's jobs.
388 *
389 * Bucket assignments as recorded in the JobStatus objects are normalized to be
390 * indices into this array, rather than the raw constants used
391 * by AppIdleHistory.
392 */
393 final int[] STANDBY_BEATS = {
394 0,
395 DEFAULT_STANDBY_WORKING_BEATS,
396 DEFAULT_STANDBY_FREQUENT_BEATS,
397 DEFAULT_STANDBY_RARE_BEATS
398 };
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700399
400 private ContentResolver mResolver;
401 private final KeyValueListParser mParser = new KeyValueListParser(',');
402
403 public Constants(Handler handler) {
404 super(handler);
405 }
406
407 public void start(ContentResolver resolver) {
408 mResolver = resolver;
409 mResolver.registerContentObserver(Settings.Global.getUriFor(
410 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
411 updateConstants();
412 }
413
414 @Override
415 public void onChange(boolean selfChange, Uri uri) {
416 updateConstants();
417 }
418
419 private void updateConstants() {
420 synchronized (mLock) {
421 try {
422 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000423 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700424 } catch (IllegalArgumentException e) {
425 // Failed to parse the settings string, log this and move on
426 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000427 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700428 }
429
430 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
431 DEFAULT_MIN_IDLE_COUNT);
432 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
433 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800434 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
435 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700436 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
437 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700438 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
439 DEFAULT_MIN_CONNECTIVITY_COUNT);
440 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
441 DEFAULT_MIN_CONTENT_COUNT);
442 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
443 DEFAULT_MIN_READY_JOBS_COUNT);
444 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
445 DEFAULT_HEAVY_USE_FACTOR);
446 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
447 DEFAULT_MODERATE_USE_FACTOR);
448 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
449 DEFAULT_FG_JOB_COUNT);
450 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
451 DEFAULT_BG_NORMAL_JOB_COUNT);
452 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
453 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
454 }
455 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
456 DEFAULT_BG_MODERATE_JOB_COUNT);
457 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
458 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
459 }
460 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
461 DEFAULT_BG_LOW_JOB_COUNT);
462 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
463 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
464 }
465 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
466 DEFAULT_BG_CRITICAL_JOB_COUNT);
467 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
468 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
469 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700470 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
471 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
472 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
473 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
474 MIN_LINEAR_BACKOFF_TIME = mParser.getLong(KEY_MIN_LINEAR_BACKOFF_TIME,
475 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
476 MIN_EXP_BACKOFF_TIME = mParser.getLong(KEY_MIN_EXP_BACKOFF_TIME,
477 DEFAULT_MIN_EXP_BACKOFF_TIME);
Christopher Tatea732f012017-10-26 17:26:53 -0700478 STANDBY_HEARTBEAT_TIME = mParser.getLong(KEY_STANDBY_HEARTBEAT_TIME,
479 DEFAULT_STANDBY_HEARTBEAT_TIME);
480 STANDBY_BEATS[1] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
481 DEFAULT_STANDBY_WORKING_BEATS);
482 STANDBY_BEATS[2] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
483 DEFAULT_STANDBY_FREQUENT_BEATS);
484 STANDBY_BEATS[3] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
485 DEFAULT_STANDBY_RARE_BEATS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700486 }
487 }
488
489 void dump(PrintWriter pw) {
490 pw.println(" Settings:");
491
492 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
493 pw.print(MIN_IDLE_COUNT); pw.println();
494
495 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
496 pw.print(MIN_CHARGING_COUNT); pw.println();
497
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800498 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
499 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
500
Dianne Hackborn532ea262017-03-17 17:50:55 -0700501 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
502 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
503
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700504 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
505 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
506
507 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
508 pw.print(MIN_CONTENT_COUNT); pw.println();
509
510 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
511 pw.print(MIN_READY_JOBS_COUNT); pw.println();
512
513 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
514 pw.print(HEAVY_USE_FACTOR); pw.println();
515
516 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
517 pw.print(MODERATE_USE_FACTOR); pw.println();
518
519 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
520 pw.print(FG_JOB_COUNT); pw.println();
521
522 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
523 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
524
525 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
526 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
527
528 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
529 pw.print(BG_LOW_JOB_COUNT); pw.println();
530
531 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
532 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700533
534 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
535 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
536
537 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
538 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
539
540 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
541 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
542
543 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
544 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Christopher Tatea732f012017-10-26 17:26:53 -0700545
546 pw.print(" "); pw.print(KEY_STANDBY_HEARTBEAT_TIME); pw.print("=");
547 pw.print(STANDBY_HEARTBEAT_TIME); pw.println();
548
549 pw.print(" standby_beats={");
550 pw.print(STANDBY_BEATS[0]);
551 for (int i = 1; i < STANDBY_BEATS.length; i++) {
552 pw.print(", ");
553 pw.print(STANDBY_BEATS[i]);
554 }
555 pw.println('}');
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700556 }
557 }
558
559 final Constants mConstants;
560
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700561 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
562 if (o1.enqueueTime < o2.enqueueTime) {
563 return -1;
564 }
565 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
566 };
567
568 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
569 int where = Collections.binarySearch(array, newItem, comparator);
570 if (where < 0) {
571 where = ~where;
572 }
573 array.add(where, newItem);
574 }
575
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700576 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700577 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
578 * still clean up. On reinstall the package will have a new uid.
579 */
580 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
581 @Override
582 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700583 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700584 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700585 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700586 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700587 final String pkgName = getPackageName(intent);
588 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
589
Christopher Tateee7805b2016-07-15 16:56:56 -0700590 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700591 // Purge the app's jobs if the whole package was just disabled. When this is
592 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700593 if (pkgName != null && pkgUid != -1) {
594 final String[] changedComponents = intent.getStringArrayExtra(
595 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
596 if (changedComponents != null) {
597 for (String component : changedComponents) {
598 if (component.equals(pkgName)) {
599 if (DEBUG) {
600 Slog.d(TAG, "Package state change: " + pkgName);
601 }
602 try {
603 final int userId = UserHandle.getUserId(pkgUid);
604 IPackageManager pm = AppGlobals.getPackageManager();
605 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
606 if (state == COMPONENT_ENABLED_STATE_DISABLED
607 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
608 if (DEBUG) {
609 Slog.d(TAG, "Removing jobs for package " + pkgName
610 + " in user " + userId);
611 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700612 cancelJobsForPackageAndUid(pkgName, pkgUid,
613 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700614 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700615 } catch (RemoteException|IllegalArgumentException e) {
616 /*
617 * IllegalArgumentException means that the package doesn't exist.
618 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
619 * behind outright uninstall, so by the time we try to act it's gone.
620 * We don't need to act on this PACKAGE_CHANGED when this happens;
621 * we'll get a PACKAGE_REMOVED later and clean up then.
622 *
623 * RemoteException can't actually happen; the package manager is
624 * running in this same process.
625 */
626 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700627 break;
628 }
629 }
630 }
631 } else {
632 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
633 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700634 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700635 // If this is an outright uninstall rather than the first half of an
636 // app update sequence, cancel the jobs associated with the app.
637 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
638 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
639 if (DEBUG) {
640 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
641 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700642 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700643 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700644 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700645 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
646 if (DEBUG) {
647 Slog.d(TAG, "Removing jobs for user: " + userId);
648 }
649 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700650 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
651 // Has this package scheduled any jobs, such that we will take action
652 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700653 if (pkgUid != -1) {
654 List<JobStatus> jobsForUid;
655 synchronized (mLock) {
656 jobsForUid = mJobs.getJobsByUid(pkgUid);
657 }
658 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
659 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
660 if (DEBUG) {
661 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
662 + pkgUid + " has jobs");
663 }
664 setResultCode(Activity.RESULT_OK);
665 break;
666 }
667 }
668 }
669 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
670 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700671 if (pkgUid != -1) {
672 if (DEBUG) {
673 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
674 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700675 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700676 }
Christopher Tate7060b042014-06-09 19:50:00 -0700677 }
678 }
679 };
680
Christopher Tateb5c07882016-05-26 17:11:09 -0700681 private String getPackageName(Intent intent) {
682 Uri uri = intent.getData();
683 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
684 return pkg;
685 }
686
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700687 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700688 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800689 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700690 }
691
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700692 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800693 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800694 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700695 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800696 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700697 synchronized (mLock) {
698 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
699 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700700 }
701
702 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla106203b2017-11-02 21:23:44 -0700703 synchronized (mLock) {
704 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
705 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700706 }
707
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700708 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800709 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700710 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800711 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700712 synchronized (mLock) {
713 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
714 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700715 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700716
717 @Override public void onUidCachedChanged(int uid, boolean cached) {
718 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700719 };
720
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800721 public Object getLock() {
722 return mLock;
723 }
724
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700725 public JobStore getJobStore() {
726 return mJobs;
727 }
728
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700729 @Override
730 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700731 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
732 // Let's kick any outstanding jobs for this user.
733 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
734 }
735
736 @Override
737 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700738 // Let's kick any outstanding jobs for this user.
739 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
740 }
741
742 @Override
743 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700744 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700745 }
746
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700747 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
748 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700749 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800750 if (ActivityManager.getService().isAppStartModeDisabled(uId,
751 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700752 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
753 + " -- package not allowed to start");
754 return JobScheduler.RESULT_FAILURE;
755 }
756 } catch (RemoteException e) {
757 }
Christopher Tatea732f012017-10-26 17:26:53 -0700758
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800759 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700760 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
761
762 if (work != null && toCancel != null) {
763 // Fast path: we are adding work to an existing job, and the JobInfo is not
764 // changing. We can just directly enqueue this work in to the job.
765 if (toCancel.getJob().equals(job)) {
Dianne Hackborn342e6032017-04-13 18:04:31 -0700766 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700767 return JobScheduler.RESULT_SUCCESS;
768 }
769 }
770
771 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
772 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800773 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800774 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800775 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
776 Slog.w(TAG, "Too many jobs for uid " + uId);
777 throw new IllegalStateException("Apps may not schedule more than "
778 + MAX_JOBS_PER_APP + " distinct jobs");
779 }
780 }
781
Dianne Hackborna47223f2017-03-30 13:49:13 -0700782 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700783 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700784
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700785 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700786 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700787 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700788 if (work != null) {
789 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700790 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700791 }
792 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700793
794 // If the job is immediately ready to run, then we can just immediately
795 // put it in the pending list and try to schedule it. This is especially
796 // important for jobs with a 0 deadline constraint, since they will happen a fair
797 // amount, we want to handle them as quickly as possible, and semantically we want to
798 // make sure we have started holding the wake lock for the job before returning to
799 // the caller.
800 // If the job is not yet ready to run, there is nothing more to do -- we are
801 // now just waiting for one of its controllers to change state and schedule
802 // the job appropriately.
803 if (isReadyToBeExecutedLocked(jobStatus)) {
804 // This is a new job, we can just immediately put it on the pending
805 // list and try to run it.
806 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700807 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700808 maybeRunPendingJobsLocked();
809 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800810 }
Christopher Tate7060b042014-06-09 19:50:00 -0700811 return JobScheduler.RESULT_SUCCESS;
812 }
813
814 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800815 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800816 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
817 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
818 for (int i = jobs.size() - 1; i >= 0; i--) {
819 JobStatus job = jobs.get(i);
820 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700821 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800822 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700823 }
Christopher Tate7060b042014-06-09 19:50:00 -0700824 }
825
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600826 public JobInfo getPendingJob(int uid, int jobId) {
827 synchronized (mLock) {
828 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
829 for (int i = jobs.size() - 1; i >= 0; i--) {
830 JobStatus job = jobs.get(i);
831 if (job.getJobId() == jobId) {
832 return job.getJob();
833 }
834 }
835 return null;
836 }
837 }
838
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700839 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800840 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700841 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
842 for (int i=0; i<jobsForUser.size(); i++) {
843 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700844 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700845 }
Christopher Tate7060b042014-06-09 19:50:00 -0700846 }
847 }
848
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700849 private void cancelJobsForNonExistentUsers() {
850 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
851 synchronized (mLock) {
852 mJobs.removeJobsOfNonUsers(umi.getUserIds());
853 }
854 }
855
Makoto Onukie7b96182017-08-30 14:53:16 -0700856 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
857 if ("android".equals(pkgName)) {
858 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
859 return;
860 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700861 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700862 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
863 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
864 final JobStatus job = jobsForUid.get(i);
865 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700866 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700867 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700868 }
869 }
870 }
871
Christopher Tate7060b042014-06-09 19:50:00 -0700872 /**
873 * Entry point from client to cancel all jobs originating from their uid.
874 * This will remove the job from the master list, and cancel the job if it was staged for
875 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700876 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800877 *
Christopher Tate7060b042014-06-09 19:50:00 -0700878 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700879 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700880 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700881 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700882 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700883 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700884
885 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800886 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700887 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
888 for (int i=0; i<jobsForUid.size(); i++) {
889 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700890 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700891 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700892 }
Christopher Tate7060b042014-06-09 19:50:00 -0700893 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700894 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700895 }
896
897 /**
898 * Entry point from client to cancel the job corresponding to the jobId provided.
899 * This will remove the job from the master list, and cancel the job if it was staged for
900 * execution or being executed.
901 * @param uid Uid of the calling client.
902 * @param jobId Id of the job, provided at schedule-time.
903 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700904 public boolean cancelJob(int uid, int jobId) {
Christopher Tate7060b042014-06-09 19:50:00 -0700905 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800906 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700907 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700908 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700909 cancelJobImplLocked(toCancel, null, "cancel() called by app");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700910 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700911 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -0700912 }
913 }
914
Dianne Hackborn729a3282017-06-09 16:06:01 -0700915 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700916 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
917 cancelled.unprepareLocked(ActivityManager.getService());
918 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
919 // Remove from pending queue.
920 if (mPendingJobs.remove(cancelled)) {
921 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700922 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700923 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700924 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700925 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700926 }
927
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800928 void updateUidState(int uid, int procState) {
929 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800930 if (procState == ActivityManager.PROCESS_STATE_TOP) {
931 // Only use this if we are exactly the top app. All others can live
932 // with just the foreground priority. This means that persistent processes
933 // can never be the top app priority... that is fine.
934 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
935 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
936 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800937 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800938 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800939 }
940 }
941 }
942
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700943 @Override
944 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800945 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700946 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600947 // When becoming idle, make sure no jobs are actively running,
948 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700949 for (int i=0; i<mActiveServices.size(); i++) {
950 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700951 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600952 if (executing != null
953 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700954 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
955 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700956 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700957 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700958 } else {
959 // When coming out of idle, allow thing to start back up.
960 if (mReadyToRock) {
961 if (mLocalDeviceIdleController != null) {
962 if (!mReportedActive) {
963 mReportedActive = true;
964 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700965 }
966 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700967 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700968 }
969 }
970 }
971 }
972
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700973 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000974 // active is true if pending queue contains jobs OR some job is running.
975 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800976 if (mPendingJobs.size() <= 0) {
977 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700978 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700979 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700980 if (job != null
981 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
982 && !job.dozeWhitelisted) {
983 // We will report active if we have a job running and it is not an exception
984 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800985 active = true;
986 break;
987 }
988 }
989 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000990
991 if (mReportedActive != active) {
992 mReportedActive = active;
993 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800994 mLocalDeviceIdleController.setJobsActive(active);
995 }
996 }
997 }
998
Christopher Tate7060b042014-06-09 19:50:00 -0700999 /**
1000 * Initializes the system service.
1001 * <p>
1002 * Subclasses must define a single argument constructor that accepts the context
1003 * and passes it to super.
1004 * </p>
1005 *
1006 * @param context The system server context.
1007 */
1008 public JobSchedulerService(Context context) {
1009 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001010
1011 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
1012
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001013 mHandler = new JobHandler(context.getMainLooper());
1014 mConstants = new Constants(mHandler);
1015 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001016
1017 // Set up the app standby bucketing tracker
1018 UsageStatsManagerInternal usageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1019 mStandbyTracker = new StandbyTracker(usageStats);
1020 usageStats.addAppIdleStateChangeListener(mStandbyTracker);
1021
1022 // The job store needs to call back
1023 publishLocalService(JobSchedulerInternal.class, new LocalService());
1024
1025 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001026 mJobs = JobStore.initAndGet(this);
1027
Christopher Tate7060b042014-06-09 19:50:00 -07001028 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001029 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -07001030 mControllers.add(ConnectivityController.get(this));
1031 mControllers.add(TimeController.get(this));
1032 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001033 mBatteryController = BatteryController.get(this);
1034 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001035 mStorageController = StorageController.get(this);
1036 mControllers.add(mStorageController);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001037 mControllers.add(BackgroundJobsController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -08001038 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001039 mControllers.add(ContentObserverController.get(this));
Suprabh Shukla106203b2017-11-02 21:23:44 -07001040 mDeviceIdleJobsController = DeviceIdleJobsController.get(this);
1041 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001042
1043 // If the job store determined that it can't yet reschedule persisted jobs,
1044 // we need to start watching the clock.
1045 if (!mJobs.jobTimesInflatedValid()) {
1046 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1047 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1048 }
Christopher Tate7060b042014-06-09 19:50:00 -07001049 }
1050
Christopher Tate616541d2017-07-26 14:27:38 -07001051 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1052 @Override
1053 public void onReceive(Context context, Intent intent) {
1054 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1055 // When we reach clock sanity, recalculate the temporal windows
1056 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001057 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001058 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1059
1060 // We've done our job now, so stop watching the time.
1061 context.unregisterReceiver(this);
1062
1063 // And kick off the work to update the affected jobs, using a secondary
1064 // thread instead of chugging away here on the main looper thread.
1065 FgThread.getHandler().post(mJobTimeUpdater);
1066 }
1067 }
1068 }
1069 };
1070
1071 private final Runnable mJobTimeUpdater = () -> {
1072 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1073 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1074 synchronized (mLock) {
1075 // Note: we intentionally both look up the existing affected jobs and replace them
1076 // with recalculated ones inside the same lock lifetime.
1077 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1078
1079 // Now, at each position [i], we have both the existing JobStatus
1080 // and the one that replaces it.
1081 final int N = toAdd.size();
1082 for (int i = 0; i < N; i++) {
1083 final JobStatus oldJob = toRemove.get(i);
1084 final JobStatus newJob = toAdd.get(i);
1085 if (DEBUG) {
1086 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1087 }
1088 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1089 }
1090 }
1091 };
1092
Christopher Tate7060b042014-06-09 19:50:00 -07001093 @Override
1094 public void onStart() {
1095 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1096 }
1097
1098 @Override
1099 public void onBootPhase(int phase) {
1100 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001101 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001102 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001103 final IntentFilter filter = new IntentFilter();
1104 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1105 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001106 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1107 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001108 filter.addDataScheme("package");
1109 getContext().registerReceiverAsUser(
1110 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1111 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1112 getContext().registerReceiverAsUser(
1113 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001114 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001115 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001116 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001117 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1118 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001119 } catch (RemoteException e) {
1120 // ignored; both services live in system_server
1121 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001122 // Remove any jobs that are not associated with any of the current users.
1123 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001124 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001125 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001126 // Let's go!
1127 mReadyToRock = true;
1128 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1129 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001130 mLocalDeviceIdleController
1131 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001132 // Create the "runners".
1133 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1134 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001135 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001136 getContext().getMainLooper()));
1137 }
1138 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001139 mJobs.forEachJob(new JobStatusFunctor() {
1140 @Override
1141 public void process(JobStatus job) {
1142 for (int controller = 0; controller < mControllers.size(); controller++) {
1143 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001144 sc.maybeStartTrackingJobLocked(job, null);
1145 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001146 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001147 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001148 // GO GO GO!
1149 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1150 }
Christopher Tate7060b042014-06-09 19:50:00 -07001151 }
1152 }
1153
1154 /**
1155 * Called when we have a job status object that we need to insert in our
1156 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1157 * about.
1158 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001159 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1160 if (!jobStatus.isPreparedLocked()) {
1161 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1162 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001163 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001164 final boolean update = mJobs.add(jobStatus);
1165 if (mReadyToRock) {
1166 for (int i = 0; i < mControllers.size(); i++) {
1167 StateController controller = mControllers.get(i);
1168 if (update) {
1169 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001170 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001171 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001172 }
Christopher Tate7060b042014-06-09 19:50:00 -07001173 }
1174 }
1175
1176 /**
1177 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1178 * object removed.
1179 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001180 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001181 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001182 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001183 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001184
1185 // Remove from store as well as controllers.
1186 final boolean removed = mJobs.remove(jobStatus, writeBack);
1187 if (removed && mReadyToRock) {
1188 for (int i=0; i<mControllers.size(); i++) {
1189 StateController controller = mControllers.get(i);
1190 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001191 }
1192 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001193 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001194 }
1195
Dianne Hackborn729a3282017-06-09 16:06:01 -07001196 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001197 for (int i=0; i<mActiveServices.size(); i++) {
1198 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001199 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001200 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001201 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001202 return true;
1203 }
1204 }
1205 return false;
1206 }
1207
1208 /**
1209 * @param job JobStatus we are querying against.
1210 * @return Whether or not the job represented by the status object is currently being run or
1211 * is pending.
1212 */
1213 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001214 for (int i=0; i<mActiveServices.size(); i++) {
1215 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001216 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001217 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1218 return true;
1219 }
1220 }
1221 return false;
1222 }
1223
Dianne Hackborn807de782016-04-07 17:54:41 -07001224 void noteJobsPending(List<JobStatus> jobs) {
1225 for (int i = jobs.size() - 1; i >= 0; i--) {
1226 JobStatus job = jobs.get(i);
1227 mJobPackageTracker.notePending(job);
1228 }
1229 }
1230
1231 void noteJobsNonpending(List<JobStatus> jobs) {
1232 for (int i = jobs.size() - 1; i >= 0; i--) {
1233 JobStatus job = jobs.get(i);
1234 mJobPackageTracker.noteNonpending(job);
1235 }
1236 }
1237
Christopher Tate7060b042014-06-09 19:50:00 -07001238 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001239 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1240 * specify an override deadline on a failed job (the failed job will run even though it's not
1241 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1242 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1243 *
Christopher Tate7060b042014-06-09 19:50:00 -07001244 * @param failureToReschedule Provided job status that we will reschedule.
1245 * @return A newly instantiated JobStatus with the same constraints as the last job except
1246 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001247 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001248 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001249 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001250 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001251 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001252 final JobInfo job = failureToReschedule.getJob();
1253
1254 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001255 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1256 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001257
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001258 if (failureToReschedule.hasWorkLocked()) {
1259 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1260 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1261 + backoffAttempts + " > work limit "
1262 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1263 return null;
1264 }
1265 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1266 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1267 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1268 return null;
1269 }
1270
Christopher Tate7060b042014-06-09 19:50:00 -07001271 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001272 case JobInfo.BACKOFF_POLICY_LINEAR: {
1273 long backoff = initialBackoffMillis;
1274 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1275 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1276 }
1277 delayMillis = backoff * backoffAttempts;
1278 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001279 default:
1280 if (DEBUG) {
1281 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1282 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001283 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1284 long backoff = initialBackoffMillis;
1285 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1286 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1287 }
1288 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1289 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001290 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001291 delayMillis =
1292 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001293 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1294 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001295 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001296 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001297 for (int ic=0; ic<mControllers.size(); ic++) {
1298 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001299 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001300 }
1301 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001302 }
1303
1304 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001305 * Called after a periodic has executed so we can reschedule it. We take the last execution
1306 * time of the job to be the time of completion (i.e. the time at which this function is
1307 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001308 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001309 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1310 * to underscheduling at least, rather than if we had taken the last execution time to be the
1311 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001312 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1313 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001314 * @return A new job representing the execution criteria for this instantiation of the
1315 * recurring job.
1316 */
1317 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001318 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001319 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001320 long runEarly = 0L;
1321
1322 // If this periodic was rescheduled it won't have a deadline.
1323 if (periodicToReschedule.hasDeadlineConstraint()) {
1324 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1325 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001326 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001327 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001328 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1329 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001330
1331 if (DEBUG) {
1332 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1333 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1334 }
Christopher Tatea732f012017-10-26 17:26:53 -07001335 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1336 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1337 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001338 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001339 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001340 }
1341
1342 // JobCompletedListener implementations.
1343
1344 /**
1345 * A job just finished executing. We fetch the
1346 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1347 * whether we want to reschedule we readd it to the controllers.
1348 * @param jobStatus Completed job.
1349 * @param needsReschedule Whether the implementing class should reschedule this job.
1350 */
1351 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001352 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001353 if (DEBUG) {
1354 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1355 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001356
1357 // If the job wants to be rescheduled, we first need to make the next upcoming
1358 // job so we can transfer any appropriate state over from the previous job when
1359 // we stop it.
1360 final JobStatus rescheduledJob = needsReschedule
1361 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1362
Shreyas Basarge73f10252016-02-11 17:06:13 +00001363 // Do not write back immediately if this is a periodic job. The job may get lost if system
1364 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001365 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001366 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001367 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001368 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001369 // We still want to check for jobs to execute, because this job may have
1370 // scheduled a new job under the same job id, and now we can run it.
1371 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001372 return;
1373 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001374
1375 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001376 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001377 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001378 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001379 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001380 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001381 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001382 } else if (jobStatus.getJob().isPeriodic()) {
1383 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001384 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001385 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001386 } catch (SecurityException e) {
1387 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1388 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001389 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001390 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001391 jobStatus.unprepareLocked(ActivityManager.getService());
1392 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001393 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001394 }
1395
1396 // StateChangedListener implementations.
1397
1398 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001399 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1400 * some controller's state has changed, so as to run through the list of jobs and start/stop
1401 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001402 */
1403 @Override
1404 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001405 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001406 }
1407
1408 @Override
1409 public void onRunJobNow(JobStatus jobStatus) {
1410 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1411 }
1412
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001413 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001414
1415 public JobHandler(Looper looper) {
1416 super(looper);
1417 }
1418
1419 @Override
1420 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001421 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001422 if (!mReadyToRock) {
1423 return;
1424 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001425 switch (message.what) {
1426 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001427 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001428 // runNow can be null, which is a controller's way of indicating that its
1429 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001430 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001431 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001432 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001433 } else {
1434 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001435 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001436 } break;
1437 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001438 if (mReportedActive) {
1439 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001440 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001441 } else {
1442 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001443 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001444 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001445 break;
1446 case MSG_CHECK_JOB_GREEDY:
1447 queueReadyJobsForExecutionLocked();
1448 break;
1449 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001450 cancelJobImplLocked((JobStatus) message.obj, null,
1451 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001452 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001453 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001454 maybeRunPendingJobsLocked();
1455 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1456 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001457 }
1458 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001459 }
Christopher Tate7060b042014-06-09 19:50:00 -07001460
Dianne Hackborn6d068262017-05-16 13:14:37 -07001461 private void stopNonReadyActiveJobsLocked() {
1462 for (int i=0; i<mActiveServices.size(); i++) {
1463 JobServiceContext serviceContext = mActiveServices.get(i);
1464 final JobStatus running = serviceContext.getRunningJobLocked();
1465 if (running != null && !running.isReady()) {
1466 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001467 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1468 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001469 }
1470 }
1471 }
1472
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001473 /**
1474 * Run through list of jobs and execute all possible - at least one is expired so we do
1475 * as many as we can.
1476 */
1477 private void queueReadyJobsForExecutionLocked() {
1478 if (DEBUG) {
1479 Slog.d(TAG, "queuing all ready jobs for execution:");
1480 }
1481 noteJobsNonpending(mPendingJobs);
1482 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001483 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001484 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001485 mJobs.forEachJob(mReadyQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001486 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001487 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001488
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001489 if (DEBUG) {
1490 final int queuedJobs = mPendingJobs.size();
1491 if (queuedJobs == 0) {
1492 Slog.d(TAG, "No jobs pending.");
1493 } else {
1494 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001495 }
1496 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001497 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001498
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001499 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1500 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001501
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001502 @Override
1503 public void process(JobStatus job) {
1504 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001505 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001506 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001507 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001508 if (newReadyJobs == null) {
1509 newReadyJobs = new ArrayList<JobStatus>();
1510 }
1511 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001512 }
1513 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001514
1515 public void postProcess() {
1516 if (newReadyJobs != null) {
1517 noteJobsPending(newReadyJobs);
1518 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001519 if (mPendingJobs.size() > 1) {
1520 mPendingJobs.sort(mEnqueueTimeComparator);
1521 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001522 }
1523 newReadyJobs = null;
1524 }
1525 }
1526 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1527
1528 /**
1529 * The state of at least one job has changed. Here is where we could enforce various
1530 * policies on when we want to execute jobs.
1531 * Right now the policy is such:
1532 * If >1 of the ready jobs is idle mode we send all of them off
1533 * if more than 2 network connectivity jobs are ready we send them all off.
1534 * If more than 4 jobs total are ready we send them all off.
1535 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1536 */
1537 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1538 int chargingCount;
1539 int batteryNotLowCount;
1540 int storageNotLowCount;
1541 int idleCount;
1542 int backoffCount;
1543 int connectivityCount;
1544 int contentCount;
1545 List<JobStatus> runnableJobs;
1546
1547 public MaybeReadyJobQueueFunctor() {
1548 reset();
1549 }
1550
1551 // Functor method invoked for each job via JobStore.forEachJob()
1552 @Override
1553 public void process(JobStatus job) {
1554 if (isReadyToBeExecutedLocked(job)) {
1555 try {
1556 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1557 job.getJob().getService().getPackageName())) {
1558 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1559 + job.getJob().toString() + " -- package not allowed to start");
1560 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1561 return;
1562 }
1563 } catch (RemoteException e) {
1564 }
1565 if (job.getNumFailures() > 0) {
1566 backoffCount++;
1567 }
1568 if (job.hasIdleConstraint()) {
1569 idleCount++;
1570 }
1571 if (job.hasConnectivityConstraint()) {
1572 connectivityCount++;
1573 }
1574 if (job.hasChargingConstraint()) {
1575 chargingCount++;
1576 }
1577 if (job.hasBatteryNotLowConstraint()) {
1578 batteryNotLowCount++;
1579 }
1580 if (job.hasStorageNotLowConstraint()) {
1581 storageNotLowCount++;
1582 }
1583 if (job.hasContentTriggerConstraint()) {
1584 contentCount++;
1585 }
1586 if (runnableJobs == null) {
1587 runnableJobs = new ArrayList<>();
1588 }
1589 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001590 }
1591 }
1592
1593 public void postProcess() {
1594 if (backoffCount > 0 ||
1595 idleCount >= mConstants.MIN_IDLE_COUNT ||
1596 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1597 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1598 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1599 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1600 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1601 (runnableJobs != null
1602 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1603 if (DEBUG) {
1604 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1605 }
1606 noteJobsPending(runnableJobs);
1607 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001608 if (mPendingJobs.size() > 1) {
1609 mPendingJobs.sort(mEnqueueTimeComparator);
1610 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001611 } else {
1612 if (DEBUG) {
1613 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1614 }
1615 }
1616
1617 // Be ready for next time
1618 reset();
1619 }
1620
1621 private void reset() {
1622 chargingCount = 0;
1623 idleCount = 0;
1624 backoffCount = 0;
1625 connectivityCount = 0;
1626 batteryNotLowCount = 0;
1627 storageNotLowCount = 0;
1628 contentCount = 0;
1629 runnableJobs = null;
1630 }
1631 }
1632 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1633
1634 private void maybeQueueReadyJobsForExecutionLocked() {
1635 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1636
1637 noteJobsNonpending(mPendingJobs);
1638 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001639 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001640 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001641 mJobs.forEachJob(mMaybeQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001642 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001643 mMaybeQueueFunctor.postProcess();
1644 }
1645
Christopher Tatea732f012017-10-26 17:26:53 -07001646 private boolean updateStandbyHeartbeatLocked() {
1647 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1648 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1649 if (beatsElapsed > 0) {
1650 mHeartbeat += beatsElapsed;
1651 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1652 if (DEBUG_STANDBY) {
1653 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed + " to " + mHeartbeat);
1654 }
1655 return true;
1656 }
1657 return false;
1658 }
1659
1660 private void updateNextStandbyHeartbeatsLocked() {
1661 // don't update ACTIVE or NEVER bucket milestones
1662 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
1663 while (mHeartbeat >= mNextBucketHeartbeat[i]) {
1664 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1665 }
1666 if (DEBUG_STANDBY) {
1667 Slog.v(TAG, " Bucket " + i + " next heartbeat " + mNextBucketHeartbeat[i]);
1668 }
1669 }
1670 }
1671
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001672 /**
1673 * Criteria for moving a job into the pending queue:
1674 * - It's ready.
1675 * - It's not pending.
1676 * - It's not already running on a JSC.
1677 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001678 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001679 * - The component is enabled and runnable.
1680 */
1681 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001682 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001683
1684 if (DEBUG) {
1685 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1686 + " ready=" + jobReady);
1687 }
1688
1689 // This is a condition that is very likely to be false (most jobs that are
1690 // scheduled are sitting there, not ready yet) and very cheap to check (just
1691 // a few conditions on data in JobStatus).
1692 if (!jobReady) {
1693 return false;
1694 }
1695
1696 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001697
1698 final int userId = job.getUserId();
1699 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1700
1701 if (DEBUG) {
1702 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001703 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001704 }
1705
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001706 // These are also fairly cheap to check, though they typically will not
1707 // be conditions we fail.
1708 if (!jobExists || !userStarted) {
1709 return false;
1710 }
1711
1712 final boolean jobPending = mPendingJobs.contains(job);
1713 final boolean jobActive = isCurrentlyActiveLocked(job);
1714
1715 if (DEBUG) {
1716 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1717 + " pending=" + jobPending + " active=" + jobActive);
1718 }
1719
1720 // These can be a little more expensive (especially jobActive, since we need to
1721 // go through the array of all potentially active jobs), so we are doing them
1722 // later... but still before checking with the package manager!
1723 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001724 return false;
1725 }
1726
Christopher Tatea732f012017-10-26 17:26:53 -07001727 // If the app is in a non-active standby bucket, make sure we've waited
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001728 // an appropriate amount of time since the last invocation. During device-
1729 // wide parole, standby bucketing is ignored.
1730 if (!mInParole) {
1731 final int bucket = job.getStandbyBucket();
1732 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
1733 // Only skip this job if it's still waiting for the end of its (initial) nominal
1734 // bucket interval. Once it's waited that long, we let it go ahead and clear.
1735 // The final (NEVER) bucket is special; we never age those apps' jobs into
1736 // runnability.
1737 if (bucket >= mConstants.STANDBY_BEATS.length
1738 || (mHeartbeat < job.getBaseHeartbeat() + mConstants.STANDBY_BEATS[bucket])) {
1739 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
1740 if (job.getWhenStandbyDeferred() == 0) {
1741 if (DEBUG_STANDBY) {
1742 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
1743 + mNextBucketHeartbeat[job.getStandbyBucket()] + " for " + job);
1744 }
1745 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tate0c4d7682017-12-06 15:10:22 -08001746 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001747 return false;
1748 } else {
1749 if (DEBUG_STANDBY) {
1750 Slog.v(TAG, "Bucket deferred job aged into runnability at "
1751 + mHeartbeat + " : " + job);
1752 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08001753 }
Christopher Tatea732f012017-10-26 17:26:53 -07001754 }
Christopher Tatea732f012017-10-26 17:26:53 -07001755 }
1756
1757 // The expensive check last: validate that the defined package+service is
1758 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001759 final boolean componentPresent;
1760 try {
1761 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1762 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1763 userId) != null);
1764 } catch (RemoteException e) {
1765 throw e.rethrowAsRuntimeException();
1766 }
1767
1768 if (DEBUG) {
1769 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1770 + " componentPresent=" + componentPresent);
1771 }
1772
1773 // Everything else checked out so far, so this is the final yes/no check
1774 return componentPresent;
1775 }
1776
1777 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001778 * Reconcile jobs in the pending queue against available execution contexts.
1779 * A controller can force a job into the pending queue even if it's already running, but
1780 * here is where we decide whether to actually execute it.
1781 */
1782 private void maybeRunPendingJobsLocked() {
1783 if (DEBUG) {
1784 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1785 }
1786 assignJobsToContextsLocked();
1787 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001788 }
1789
Dianne Hackborn807de782016-04-07 17:54:41 -07001790 private int adjustJobPriority(int curPriority, JobStatus job) {
1791 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1792 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001793 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001794 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001795 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001796 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1797 }
1798 }
1799 return curPriority;
1800 }
1801
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001802 private int evaluateJobPriorityLocked(JobStatus job) {
1803 int priority = job.getPriority();
1804 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001805 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001806 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001807 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1808 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001809 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001810 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001811 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001812 }
1813
Christopher Tate7060b042014-06-09 19:50:00 -07001814 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001815 * Takes jobs from pending queue and runs them on available contexts.
1816 * If no contexts are available, preempts lower priority jobs to
1817 * run higher priority ones.
1818 * Lock on mJobs before calling this function.
1819 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001820 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001821 if (DEBUG) {
1822 Slog.d(TAG, printPendingQueue());
1823 }
1824
Dianne Hackborn970510b2016-02-24 16:56:42 -08001825 int memLevel;
1826 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001827 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001828 } catch (RemoteException e) {
1829 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1830 }
1831 switch (memLevel) {
1832 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001833 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001834 break;
1835 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001836 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001837 break;
1838 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001839 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001840 break;
1841 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001842 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001843 break;
1844 }
1845
1846 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1847 boolean[] act = mTmpAssignAct;
1848 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1849 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001850 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001851 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1852 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001853 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001854 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001855 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001856 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1857 numForeground++;
1858 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001859 }
1860 act[i] = false;
1861 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001862 }
1863 if (DEBUG) {
1864 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1865 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001866 for (int i=0; i<mPendingJobs.size(); i++) {
1867 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001868
1869 // If job is already running, go to next job.
1870 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1871 if (jobRunningContext != -1) {
1872 continue;
1873 }
1874
Dianne Hackborn970510b2016-02-24 16:56:42 -08001875 final int priority = evaluateJobPriorityLocked(nextPending);
1876 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001877
Shreyas Basarge5db09082016-01-07 13:38:29 +00001878 // Find a context for nextPending. The context should be available OR
1879 // it should have lowest priority among all running jobs
1880 // (sharing the same Uid as nextPending)
1881 int minPriority = Integer.MAX_VALUE;
1882 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001883 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1884 JobStatus job = contextIdToJobMap[j];
1885 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001886 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001887 if ((numActive < mMaxActiveJobs ||
1888 (priority >= JobInfo.PRIORITY_TOP_APP &&
1889 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001890 (preferredUid == nextPending.getUid() ||
1891 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1892 // This slot is free, and we haven't yet hit the limit on
1893 // concurrent jobs... we can just throw the job in to here.
1894 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001895 break;
1896 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001897 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001898 // the context has a preferred Uid or we have reached the limit on
1899 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001900 continue;
1901 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001902 if (job.getUid() != nextPending.getUid()) {
1903 continue;
1904 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001905 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001906 continue;
1907 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001908 if (minPriority > nextPending.lastEvaluatedPriority) {
1909 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001910 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001911 }
1912 }
1913 if (minPriorityContextId != -1) {
1914 contextIdToJobMap[minPriorityContextId] = nextPending;
1915 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001916 numActive++;
1917 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1918 numForeground++;
1919 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001920 }
1921 }
1922 if (DEBUG) {
1923 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1924 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001925 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001926 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001927 boolean preservePreferredUid = false;
1928 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001929 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001930 if (js != null) {
1931 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001932 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001933 }
1934 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001935 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001936 preservePreferredUid = true;
1937 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001938 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001939 if (DEBUG) {
1940 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001941 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001942 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001943 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001944 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001945 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001946 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1947 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001948 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001949 if (mPendingJobs.remove(pendingJob)) {
1950 mJobPackageTracker.noteNonpending(pendingJob);
1951 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001952 }
1953 }
1954 if (!preservePreferredUid) {
1955 mActiveServices.get(i).clearPreferredUid();
1956 }
1957 }
1958 }
1959
1960 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1961 for (int i=0; i<map.length; i++) {
1962 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1963 return i;
1964 }
1965 }
1966 return -1;
1967 }
1968
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001969 final class LocalService implements JobSchedulerInternal {
1970
1971 /**
Christopher Tatea732f012017-10-26 17:26:53 -07001972 * The current bucket heartbeat ordinal
1973 */
1974 public long currentHeartbeat() {
1975 return getCurrentHeartbeat();
1976 }
1977
1978 /**
1979 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
1980 */
1981 public long nextHeartbeatForBucket(int bucket) {
1982 synchronized (mLock) {
1983 return mNextBucketHeartbeat[bucket];
1984 }
1985 }
1986
1987 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001988 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1989 * jobs are always considered pending.
1990 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001991 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001992 public List<JobInfo> getSystemScheduledPendingJobs() {
1993 synchronized (mLock) {
1994 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1995 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1996 @Override
1997 public void process(JobStatus job) {
1998 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1999 pendingJobs.add(job.getJob());
2000 }
2001 }
2002 });
2003 return pendingJobs;
2004 }
2005 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002006
2007 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002008 public void cancelJobsForUid(int uid, String reason) {
2009 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2010 }
2011
2012 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002013 public void addBackingUpUid(int uid) {
2014 synchronized (mLock) {
2015 // No need to actually do anything here, since for a full backup the
2016 // activity manager will kill the process which will kill the job (and
2017 // cause it to restart, but now it can't run).
2018 mBackingUpUids.put(uid, uid);
2019 }
2020 }
2021
2022 @Override
2023 public void removeBackingUpUid(int uid) {
2024 synchronized (mLock) {
2025 mBackingUpUids.delete(uid);
2026 // If there are any jobs for this uid, we need to rebuild the pending list
2027 // in case they are now ready to run.
2028 if (mJobs.countJobsForUid(uid) > 0) {
2029 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2030 }
2031 }
2032 }
2033
2034 @Override
2035 public void clearAllBackingUpUids() {
2036 synchronized (mLock) {
2037 if (mBackingUpUids.size() > 0) {
2038 mBackingUpUids.clear();
2039 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2040 }
2041 }
2042 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002043
2044 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002045 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002046 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002047 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002048 }
2049 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002050 }
2051
Shreyas Basarge5db09082016-01-07 13:38:29 +00002052 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002053 * Tracking of app assignments to standby buckets
2054 */
2055 final class StandbyTracker extends AppIdleStateChangeListener {
2056 final UsageStatsManagerInternal mUsageStats;
2057
2058 StandbyTracker(UsageStatsManagerInternal usageStats) {
2059 mUsageStats = usageStats;
2060 }
2061
2062 // AppIdleStateChangeListener interface for live updates
2063
2064 @Override
2065 public void onAppIdleStateChanged(final String packageName, final int userId,
2066 boolean idle, int bucket) {
2067 final int uid = mLocalPM.getPackageUid(packageName,
2068 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2069 if (uid < 0) {
2070 if (DEBUG_STANDBY) {
2071 Slog.i(TAG, "App idle state change for unknown app "
2072 + packageName + "/" + userId);
2073 }
2074 return;
2075 }
2076
2077 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2078 // update job bookkeeping out of band
2079 BackgroundThread.getHandler().post(() -> {
2080 if (DEBUG_STANDBY) {
2081 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2082 }
2083 synchronized (mLock) {
2084 // TODO: update to be more efficient once we can slice by source UID
2085 mJobs.forEachJob((JobStatus job) -> {
2086 if (job.getSourceUid() == uid) {
2087 job.setStandbyBucket(bucketIndex);
2088 }
2089 });
2090 onControllerStateChanged();
2091 }
2092 });
2093 }
2094
2095 @Override
2096 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002097 if (DEBUG_STANDBY) {
2098 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2099 }
2100 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002101 }
2102 }
2103
2104 public static int standbyBucketToBucketIndex(int bucket) {
2105 // Normalize AppStandby constants to indices into our bookkeeping
Amith Yamasaniafbccb72017-11-27 10:44:24 -08002106 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return 4;
2107 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) return 3;
2108 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) return 2;
2109 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return 1;
Christopher Tatea732f012017-10-26 17:26:53 -07002110 else return 0;
2111 }
2112
2113 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2114 UsageStatsManagerInternal usageStats = LocalServices.getService(
2115 UsageStatsManagerInternal.class);
2116 int bucket = usageStats != null
2117 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2118 : 0;
2119
2120 bucket = standbyBucketToBucketIndex(bucket);
2121
2122 if (DEBUG_STANDBY) {
2123 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2124 }
2125 return bucket;
2126 }
2127
2128 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002129 * Binder stub trampoline implementation
2130 */
2131 final class JobSchedulerStub extends IJobScheduler.Stub {
2132 /** Cache determination of whether a given app can persist jobs
2133 * key is uid of the calling app; value is undetermined/true/false
2134 */
2135 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2136
2137 // Enforce that only the app itself (or shared uid participant) can schedule a
2138 // job that runs one of the app's services, as well as verifying that the
2139 // named service properly requires the BIND_JOB_SERVICE permission
2140 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002141 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002142 final ComponentName service = job.getService();
2143 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002144 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002145 PackageManager.MATCH_DIRECT_BOOT_AWARE
2146 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002147 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002148 if (si == null) {
2149 throw new IllegalArgumentException("No such service " + service);
2150 }
Christopher Tate7060b042014-06-09 19:50:00 -07002151 if (si.applicationInfo.uid != uid) {
2152 throw new IllegalArgumentException("uid " + uid +
2153 " cannot schedule job in " + service.getPackageName());
2154 }
2155 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2156 throw new IllegalArgumentException("Scheduled service " + service
2157 + " does not require android.permission.BIND_JOB_SERVICE permission");
2158 }
Christopher Tate5568f542014-06-18 13:53:31 -07002159 } catch (RemoteException e) {
2160 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002161 }
2162 }
2163
2164 private boolean canPersistJobs(int pid, int uid) {
2165 // If we get this far we're good to go; all we need to do now is check
2166 // whether the app is allowed to persist its scheduled work.
2167 final boolean canPersist;
2168 synchronized (mPersistCache) {
2169 Boolean cached = mPersistCache.get(uid);
2170 if (cached != null) {
2171 canPersist = cached.booleanValue();
2172 } else {
2173 // Persisting jobs is tantamount to running at boot, so we permit
2174 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2175 // permission
2176 int result = getContext().checkPermission(
2177 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2178 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2179 mPersistCache.put(uid, canPersist);
2180 }
2181 }
2182 return canPersist;
2183 }
2184
2185 // IJobScheduler implementation
2186 @Override
2187 public int schedule(JobInfo job) throws RemoteException {
2188 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002189 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002190 }
2191 final int pid = Binder.getCallingPid();
2192 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002193 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002194
2195 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002196 if (job.isPersisted()) {
2197 if (!canPersistJobs(pid, uid)) {
2198 throw new IllegalArgumentException("Error: requested job be persisted without"
2199 + " holding RECEIVE_BOOT_COMPLETED permission.");
2200 }
2201 }
Christopher Tate7060b042014-06-09 19:50:00 -07002202
Jeff Sharkey785f4942016-07-14 10:31:15 -06002203 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2204 getContext().enforceCallingOrSelfPermission(
2205 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2206 }
2207
Christopher Tate7060b042014-06-09 19:50:00 -07002208 long ident = Binder.clearCallingIdentity();
2209 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002210 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2211 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002212 } finally {
2213 Binder.restoreCallingIdentity(ident);
2214 }
2215 }
2216
2217 // IJobScheduler implementation
2218 @Override
2219 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2220 if (DEBUG) {
2221 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2222 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002223 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002224 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002225
2226 enforceValidJobRequest(uid, job);
2227 if (job.isPersisted()) {
2228 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2229 }
2230 if (work == null) {
2231 throw new NullPointerException("work is null");
2232 }
2233
2234 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2235 getContext().enforceCallingOrSelfPermission(
2236 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2237 }
2238
2239 long ident = Binder.clearCallingIdentity();
2240 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002241 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2242 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002243 } finally {
2244 Binder.restoreCallingIdentity(ident);
2245 }
2246 }
2247
2248 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002249 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002250 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002251 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002252 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002253 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002254 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002255 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002256
2257 if (packageName == null) {
2258 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002259 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002260
2261 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2262 android.Manifest.permission.UPDATE_DEVICE_STATS);
2263 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2264 throw new SecurityException("Caller uid " + callerUid
2265 + " not permitted to schedule jobs for other apps");
2266 }
2267
Jeff Sharkey4f100402016-05-03 17:44:23 -06002268 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2269 getContext().enforceCallingOrSelfPermission(
2270 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2271 }
2272
Shreyas Basarge968ac752016-01-11 23:09:26 +00002273 long ident = Binder.clearCallingIdentity();
2274 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002275 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002276 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002277 } finally {
2278 Binder.restoreCallingIdentity(ident);
2279 }
2280 }
2281
2282 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002283 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2284 final int uid = Binder.getCallingUid();
2285
2286 long ident = Binder.clearCallingIdentity();
2287 try {
2288 return JobSchedulerService.this.getPendingJobs(uid);
2289 } finally {
2290 Binder.restoreCallingIdentity(ident);
2291 }
2292 }
2293
2294 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002295 public JobInfo getPendingJob(int jobId) throws RemoteException {
2296 final int uid = Binder.getCallingUid();
2297
2298 long ident = Binder.clearCallingIdentity();
2299 try {
2300 return JobSchedulerService.this.getPendingJob(uid, jobId);
2301 } finally {
2302 Binder.restoreCallingIdentity(ident);
2303 }
2304 }
2305
2306 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002307 public void cancelAll() throws RemoteException {
2308 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002309 long ident = Binder.clearCallingIdentity();
2310 try {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002311 JobSchedulerService.this.cancelJobsForUid(uid, "cancelAll() called by app");
Christopher Tate7060b042014-06-09 19:50:00 -07002312 } finally {
2313 Binder.restoreCallingIdentity(ident);
2314 }
2315 }
2316
2317 @Override
2318 public void cancel(int jobId) throws RemoteException {
2319 final int uid = Binder.getCallingUid();
2320
2321 long ident = Binder.clearCallingIdentity();
2322 try {
2323 JobSchedulerService.this.cancelJob(uid, jobId);
2324 } finally {
2325 Binder.restoreCallingIdentity(ident);
2326 }
2327 }
2328
2329 /**
2330 * "dumpsys" infrastructure
2331 */
2332 @Override
2333 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002334 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002335
2336 long identityToken = Binder.clearCallingIdentity();
2337 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002338 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07002339 } finally {
2340 Binder.restoreCallingIdentity(identityToken);
2341 }
2342 }
Christopher Tate5d346052016-03-08 12:56:08 -08002343
2344 @Override
2345 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002346 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002347 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002348 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002349 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002350 };
2351
Christopher Tate5d346052016-03-08 12:56:08 -08002352 // Shell command infrastructure: run the given job immediately
2353 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2354 if (DEBUG) {
2355 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2356 + " " + jobId + " f=" + force);
2357 }
2358
2359 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002360 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2361 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002362 if (uid < 0) {
2363 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2364 }
2365
2366 synchronized (mLock) {
2367 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2368 if (js == null) {
2369 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2370 }
2371
2372 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2373 if (!js.isConstraintsSatisfied()) {
2374 js.overrideState = 0;
2375 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2376 }
2377
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002378 queueReadyJobsForExecutionLocked();
2379 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002380 }
2381 } catch (RemoteException e) {
2382 // can't happen
2383 }
2384 return 0;
2385 }
2386
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002387 // Shell command infrastructure: immediately timeout currently executing jobs
2388 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2389 boolean hasJobId, int jobId) {
2390 if (DEBUG) {
2391 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2392 }
2393
2394 synchronized (mLock) {
2395 boolean foundSome = false;
2396 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002397 final JobServiceContext jc = mActiveServices.get(i);
2398 final JobStatus js = jc.getRunningJobLocked();
2399 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId)) {
2400 foundSome = true;
2401 pw.print("Timing out: ");
2402 js.printUniqueId(pw);
2403 pw.print(" ");
2404 pw.println(js.getServiceComponent().flattenToShortString());
2405 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002406 }
2407 if (!foundSome) {
2408 pw.println("No matching executing jobs found.");
2409 }
2410 }
2411 return 0;
2412 }
2413
Christopher Tate8c67d122017-09-29 16:54:26 -07002414 // Shell command infrastructure: cancel a scheduled job
2415 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2416 boolean hasJobId, int jobId) {
2417 if (DEBUG) {
2418 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2419 }
2420
2421 int pkgUid = -1;
2422 try {
2423 IPackageManager pm = AppGlobals.getPackageManager();
2424 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2425 } catch (RemoteException e) { /* can't happen */ }
2426
2427 if (pkgUid < 0) {
2428 pw.println("Package " + pkgName + " not found.");
2429 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2430 }
2431
2432 if (!hasJobId) {
2433 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2434 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2435 pw.println("No matching jobs found.");
2436 }
2437 } else {
2438 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
2439 if (!cancelJob(pkgUid, jobId)) {
2440 pw.println("No matching job found.");
2441 }
2442 }
2443
2444 return 0;
2445 }
2446
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002447 void setMonitorBattery(boolean enabled) {
2448 synchronized (mLock) {
2449 if (mBatteryController != null) {
2450 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2451 }
2452 }
2453 }
2454
2455 int getBatterySeq() {
2456 synchronized (mLock) {
2457 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2458 }
2459 }
2460
2461 boolean getBatteryCharging() {
2462 synchronized (mLock) {
2463 return mBatteryController != null
2464 ? mBatteryController.getTracker().isOnStablePower() : false;
2465 }
2466 }
2467
2468 boolean getBatteryNotLow() {
2469 synchronized (mLock) {
2470 return mBatteryController != null
2471 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2472 }
2473 }
2474
Dianne Hackborn532ea262017-03-17 17:50:55 -07002475 int getStorageSeq() {
2476 synchronized (mLock) {
2477 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2478 }
2479 }
2480
2481 boolean getStorageNotLow() {
2482 synchronized (mLock) {
2483 return mStorageController != null
2484 ? mStorageController.getTracker().isStorageNotLow() : false;
2485 }
2486 }
2487
Christopher Tatea732f012017-10-26 17:26:53 -07002488 long getCurrentHeartbeat() {
2489 synchronized (mLock) {
2490 return mHeartbeat;
2491 }
2492 }
2493
Dianne Hackborn6d068262017-05-16 13:14:37 -07002494 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2495 try {
2496 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2497 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2498 if (uid < 0) {
2499 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2500 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2501 }
2502
2503 synchronized (mLock) {
2504 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2505 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2506 if (js == null) {
2507 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2508 pw.print("/jid"); pw.print(jobId); pw.println(")");
2509 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2510 }
2511
2512 boolean printed = false;
2513 if (mPendingJobs.contains(js)) {
2514 pw.print("pending");
2515 printed = true;
2516 }
2517 if (isCurrentlyActiveLocked(js)) {
2518 if (printed) {
2519 pw.print(" ");
2520 }
2521 printed = true;
2522 pw.println("active");
2523 }
2524 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2525 if (printed) {
2526 pw.print(" ");
2527 }
2528 printed = true;
2529 pw.println("user-stopped");
2530 }
2531 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2532 if (printed) {
2533 pw.print(" ");
2534 }
2535 printed = true;
2536 pw.println("backing-up");
2537 }
2538 boolean componentPresent = false;
2539 try {
2540 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2541 js.getServiceComponent(),
2542 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2543 js.getUserId()) != null);
2544 } catch (RemoteException e) {
2545 }
2546 if (!componentPresent) {
2547 if (printed) {
2548 pw.print(" ");
2549 }
2550 printed = true;
2551 pw.println("no-component");
2552 }
2553 if (js.isReady()) {
2554 if (printed) {
2555 pw.print(" ");
2556 }
2557 printed = true;
2558 pw.println("ready");
2559 }
2560 if (!printed) {
2561 pw.print("waiting");
2562 }
2563 pw.println();
2564 }
2565 } catch (RemoteException e) {
2566 // can't happen
2567 }
2568 return 0;
2569 }
2570
Shreyas Basarge5db09082016-01-07 13:38:29 +00002571 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2572 StringBuilder s = new StringBuilder(initial + ": ");
2573 for (int i=0; i<map.length; i++) {
2574 s.append("(")
2575 .append(map[i] == null? -1: map[i].getJobId())
2576 .append(map[i] == null? -1: map[i].getUid())
2577 .append(")" );
2578 }
2579 return s.toString();
2580 }
2581
2582 private String printPendingQueue() {
2583 StringBuilder s = new StringBuilder("Pending queue: ");
2584 Iterator<JobStatus> it = mPendingJobs.iterator();
2585 while (it.hasNext()) {
2586 JobStatus js = it.next();
2587 s.append("(")
2588 .append(js.getJob().getId())
2589 .append(", ")
2590 .append(js.getUid())
2591 .append(") ");
2592 }
2593 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002594 }
Christopher Tate7060b042014-06-09 19:50:00 -07002595
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002596 static void dumpHelp(PrintWriter pw) {
2597 pw.println("Job Scheduler (jobscheduler) dump options:");
2598 pw.println(" [-h] [package] ...");
2599 pw.println(" -h: print this help");
2600 pw.println(" [package] is an optional package name to limit the output to.");
2601 }
2602
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002603 void dumpInternal(final PrintWriter pw, String[] args) {
2604 int filterUid = -1;
2605 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002606 int opti = 0;
2607 while (opti < args.length) {
2608 String arg = args[opti];
2609 if ("-h".equals(arg)) {
2610 dumpHelp(pw);
2611 return;
2612 } else if ("-a".equals(arg)) {
2613 // Ignore, we always dump all.
2614 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2615 pw.println("Unknown option: " + arg);
2616 return;
2617 } else {
2618 break;
2619 }
2620 opti++;
2621 }
2622 if (opti < args.length) {
2623 String pkg = args[opti];
2624 try {
2625 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002626 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002627 } catch (NameNotFoundException ignored) {
2628 pw.println("Invalid package: " + pkg);
2629 return;
2630 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002631 }
2632 }
2633
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002634 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07002635 final long nowElapsed = sElapsedRealtimeClock.millis();
2636 final long nowUptime = sUptimeMillisClock.millis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002637 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002638 mConstants.dump(pw);
2639 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002640 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002641 pw.print("Registered ");
2642 pw.print(mJobs.size());
2643 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002644 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002645 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2646 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002647 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002648 public int compare(JobStatus o1, JobStatus o2) {
2649 int uid1 = o1.getUid();
2650 int uid2 = o2.getUid();
2651 int id1 = o1.getJobId();
2652 int id2 = o2.getJobId();
2653 if (uid1 != uid2) {
2654 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002655 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002656 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08002657 }
2658 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002659 for (JobStatus job : jobs) {
2660 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2661 pw.println(job.toShortStringExceptUniqueId());
2662
2663 // Skip printing details if the caller requested a filter
2664 if (!job.shouldDump(filterUidFinal)) {
2665 continue;
2666 }
2667
Dianne Hackborn6d068262017-05-16 13:14:37 -07002668 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002669 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002670 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002671 pw.print(" (job=");
2672 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002673 pw.print(" user=");
2674 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002675 pw.print(" !pending=");
2676 pw.print(!mPendingJobs.contains(job));
2677 pw.print(" !active=");
2678 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002679 pw.print(" !backingup=");
2680 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002681 pw.print(" comp=");
2682 boolean componentPresent = false;
2683 try {
2684 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2685 job.getServiceComponent(),
2686 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2687 job.getUserId()) != null);
2688 } catch (RemoteException e) {
2689 }
2690 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002691 pw.println(")");
2692 }
Christopher Tate7060b042014-06-09 19:50:00 -07002693 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002694 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002695 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002696 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002697 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002698 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002699 }
2700 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002701 pw.println("Uid priority overrides:");
2702 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002703 int uid = mUidPriorityOverride.keyAt(i);
2704 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2705 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2706 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2707 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002708 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002709 if (mBackingUpUids.size() > 0) {
2710 pw.println();
2711 pw.println("Backing up uids:");
2712 boolean first = true;
2713 for (int i = 0; i < mBackingUpUids.size(); i++) {
2714 int uid = mBackingUpUids.keyAt(i);
2715 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2716 if (first) {
2717 pw.print(" ");
2718 first = false;
2719 } else {
2720 pw.print(", ");
2721 }
2722 pw.print(UserHandle.formatUid(uid));
2723 }
2724 }
2725 pw.println();
2726 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002727 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002728 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002729 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002730 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2731 pw.println();
2732 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002733 pw.println("Pending queue:");
2734 for (int i=0; i<mPendingJobs.size(); i++) {
2735 JobStatus job = mPendingJobs.get(i);
2736 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2737 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002738 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002739 int priority = evaluateJobPriorityLocked(job);
2740 if (priority != JobInfo.PRIORITY_DEFAULT) {
2741 pw.print(" Evaluated priority: "); pw.println(priority);
2742 }
2743 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002744 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002745 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002746 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002747 }
Christopher Tate7060b042014-06-09 19:50:00 -07002748 pw.println();
2749 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002750 for (int i=0; i<mActiveServices.size(); i++) {
2751 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002752 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002753 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002754 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002755 if (jsc.mStoppedReason != null) {
2756 pw.print("inactive since ");
2757 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2758 pw.print(", stopped because: ");
2759 pw.println(jsc.mStoppedReason);
2760 } else {
2761 pw.println("inactive");
2762 }
Christopher Tate7060b042014-06-09 19:50:00 -07002763 continue;
2764 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002765 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002766 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002767 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002768 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002769 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002770 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002771 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002772 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002773 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002774 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002775 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002776 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002777 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002778 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002779 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2780 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002781 }
2782 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002783 if (filterUid == -1) {
2784 pw.println();
2785 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2786 pw.print("mReportedActive="); pw.println(mReportedActive);
2787 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2788 }
Makoto Onukie7b02982017-08-24 14:23:36 -07002789 pw.println();
2790 pw.print("PersistStats: ");
2791 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07002792 }
2793 pw.println();
2794 }
2795}