blob: 4af86a05365daaef88507a5c2860328438819b27 [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.job;
18
Christopher Tateb5c07882016-05-26 17:11:09 -070019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21
Christopher Tateee7805b2016-07-15 16:56:56 -070022import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070023import android.app.ActivityManager;
Christopher Tate5568f542014-06-18 13:53:31 -070024import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070025import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070026import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070027import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000028import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.app.job.JobScheduler;
30import android.app.job.JobService;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070031import android.app.job.JobWorkItem;
Christopher Tatea732f012017-10-26 17:26:53 -070032import android.app.usage.AppStandby;
33import 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 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800188 * Current limit on the number of concurrent JobServiceContext entries we want to
189 * keep actively running a job.
190 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700191 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800192
193 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800194 * Which uids are currently in the foreground.
195 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800196 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
197
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700198 /**
199 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
200 */
201 final SparseIntArray mBackingUpUids = new SparseIntArray();
202
Christopher Tatea732f012017-10-26 17:26:53 -0700203 /**
204 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
205 * next become runnable. Index into this array is by normalized bucket:
206 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
207 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
208 * and NEVER apps don't get them at all.
209 */
210 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
211 long mHeartbeat = 0;
212 long mLastHeartbeatTime = 0;
213
Dianne Hackborn970510b2016-02-24 16:56:42 -0800214 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
215
216 /**
217 * This array essentially stores the state of mActiveServices array.
218 * The ith index stores the job present on the ith JobServiceContext.
219 * We manipulate this array until we arrive at what jobs should be running on
220 * what JobServiceContext.
221 */
222 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
223 /**
224 * Indicates whether we need to act on this jobContext id
225 */
226 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
227 /**
228 * The uid whose jobs we would like to assign to a context.
229 */
230 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800231
232 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700233 * All times are in milliseconds. These constants are kept synchronized with the system
234 * global Settings. Any access to this class or its fields should be done while
235 * holding the JobSchedulerService.mLock lock.
236 */
237 private final class Constants extends ContentObserver {
238 // Key names stored in the settings value.
239 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
240 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800241 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700242 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700243 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
244 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
245 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
246 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
247 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
248 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
249 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
250 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
251 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
252 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700253 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
254 = "max_standard_reschedule_count";
255 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
256 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
257 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700258 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
259 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
260 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
261 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700262
263 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
264 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800265 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700266 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700267 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
268 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
269 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
270 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
271 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
272 private static final int DEFAULT_FG_JOB_COUNT = 4;
273 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
274 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700275 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700276 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700277 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
278 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
279 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
280 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700281 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
282 private static final int DEFAULT_STANDBY_WORKING_BEATS = 5; // ~ 1 hour, with 11-min beats
283 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 31; // ~ 6 hours
284 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700285
286 /**
287 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
288 * early.
289 */
290 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
291 /**
292 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
293 * things early.
294 */
295 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
296 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800297 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
298 * schedule things early.
299 */
300 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
301 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700302 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
303 * schedule things early.
304 */
305 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
306 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700307 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
308 * things early. 1 == Run connectivity jobs as soon as ready.
309 */
310 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
311 /**
312 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
313 * schedule things early.
314 */
315 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
316 /**
317 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
318 * running some work early. This (and thus the other min counts) is now set to 1, to
319 * prevent any batching at this level. Since we now do batching through doze, that is
320 * a much better mechanism.
321 */
322 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
323 /**
324 * This is the job execution factor that is considered to be heavy use of the system.
325 */
326 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
327 /**
328 * This is the job execution factor that is considered to be moderate use of the system.
329 */
330 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
331 /**
332 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
333 */
334 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
335 /**
336 * The maximum number of background jobs we allow when the system is in a normal
337 * memory state.
338 */
339 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
340 /**
341 * The maximum number of background jobs we allow when the system is in a moderate
342 * memory state.
343 */
344 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
345 /**
346 * The maximum number of background jobs we allow when the system is in a low
347 * memory state.
348 */
349 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
350 /**
351 * The maximum number of background jobs we allow when the system is in a critical
352 * memory state.
353 */
354 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700355 /**
356 * The maximum number of times we allow a job to have itself rescheduled before
357 * giving up on it, for standard jobs.
358 */
359 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
360 /**
361 * The maximum number of times we allow a job to have itself rescheduled before
362 * giving up on it, for jobs that are executing work.
363 */
364 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
365 /**
366 * The minimum backoff time to allow for linear backoff.
367 */
368 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
369 /**
370 * The minimum backoff time to allow for exponential backoff.
371 */
372 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700373 /**
374 * How often we recalculate runnability based on apps' standby bucket assignment.
375 * This should be prime relative to common time interval lengths such as a quarter-
376 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
377 */
378 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
379
380 /**
381 * Mapping: standby bucket -> number of heartbeats between each sweep of that
382 * bucket's jobs.
383 *
384 * Bucket assignments as recorded in the JobStatus objects are normalized to be
385 * indices into this array, rather than the raw constants used
386 * by AppIdleHistory.
387 */
388 final int[] STANDBY_BEATS = {
389 0,
390 DEFAULT_STANDBY_WORKING_BEATS,
391 DEFAULT_STANDBY_FREQUENT_BEATS,
392 DEFAULT_STANDBY_RARE_BEATS
393 };
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700394
395 private ContentResolver mResolver;
396 private final KeyValueListParser mParser = new KeyValueListParser(',');
397
398 public Constants(Handler handler) {
399 super(handler);
400 }
401
402 public void start(ContentResolver resolver) {
403 mResolver = resolver;
404 mResolver.registerContentObserver(Settings.Global.getUriFor(
405 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
406 updateConstants();
407 }
408
409 @Override
410 public void onChange(boolean selfChange, Uri uri) {
411 updateConstants();
412 }
413
414 private void updateConstants() {
415 synchronized (mLock) {
416 try {
417 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000418 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700419 } catch (IllegalArgumentException e) {
420 // Failed to parse the settings string, log this and move on
421 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000422 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700423 }
424
425 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
426 DEFAULT_MIN_IDLE_COUNT);
427 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
428 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800429 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
430 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700431 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
432 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700433 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
434 DEFAULT_MIN_CONNECTIVITY_COUNT);
435 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
436 DEFAULT_MIN_CONTENT_COUNT);
437 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
438 DEFAULT_MIN_READY_JOBS_COUNT);
439 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
440 DEFAULT_HEAVY_USE_FACTOR);
441 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
442 DEFAULT_MODERATE_USE_FACTOR);
443 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
444 DEFAULT_FG_JOB_COUNT);
445 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
446 DEFAULT_BG_NORMAL_JOB_COUNT);
447 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
448 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
449 }
450 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
451 DEFAULT_BG_MODERATE_JOB_COUNT);
452 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
453 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
454 }
455 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
456 DEFAULT_BG_LOW_JOB_COUNT);
457 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
458 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
459 }
460 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
461 DEFAULT_BG_CRITICAL_JOB_COUNT);
462 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
463 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
464 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700465 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
466 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
467 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
468 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
469 MIN_LINEAR_BACKOFF_TIME = mParser.getLong(KEY_MIN_LINEAR_BACKOFF_TIME,
470 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
471 MIN_EXP_BACKOFF_TIME = mParser.getLong(KEY_MIN_EXP_BACKOFF_TIME,
472 DEFAULT_MIN_EXP_BACKOFF_TIME);
Christopher Tatea732f012017-10-26 17:26:53 -0700473 STANDBY_HEARTBEAT_TIME = mParser.getLong(KEY_STANDBY_HEARTBEAT_TIME,
474 DEFAULT_STANDBY_HEARTBEAT_TIME);
475 STANDBY_BEATS[1] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
476 DEFAULT_STANDBY_WORKING_BEATS);
477 STANDBY_BEATS[2] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
478 DEFAULT_STANDBY_FREQUENT_BEATS);
479 STANDBY_BEATS[3] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
480 DEFAULT_STANDBY_RARE_BEATS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700481 }
482 }
483
484 void dump(PrintWriter pw) {
485 pw.println(" Settings:");
486
487 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
488 pw.print(MIN_IDLE_COUNT); pw.println();
489
490 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
491 pw.print(MIN_CHARGING_COUNT); pw.println();
492
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800493 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
494 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
495
Dianne Hackborn532ea262017-03-17 17:50:55 -0700496 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
497 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
498
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700499 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
500 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
501
502 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
503 pw.print(MIN_CONTENT_COUNT); pw.println();
504
505 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
506 pw.print(MIN_READY_JOBS_COUNT); pw.println();
507
508 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
509 pw.print(HEAVY_USE_FACTOR); pw.println();
510
511 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
512 pw.print(MODERATE_USE_FACTOR); pw.println();
513
514 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
515 pw.print(FG_JOB_COUNT); pw.println();
516
517 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
518 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
519
520 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
521 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
522
523 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
524 pw.print(BG_LOW_JOB_COUNT); pw.println();
525
526 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
527 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700528
529 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
530 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
531
532 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
533 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
534
535 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
536 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
537
538 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
539 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Christopher Tatea732f012017-10-26 17:26:53 -0700540
541 pw.print(" "); pw.print(KEY_STANDBY_HEARTBEAT_TIME); pw.print("=");
542 pw.print(STANDBY_HEARTBEAT_TIME); pw.println();
543
544 pw.print(" standby_beats={");
545 pw.print(STANDBY_BEATS[0]);
546 for (int i = 1; i < STANDBY_BEATS.length; i++) {
547 pw.print(", ");
548 pw.print(STANDBY_BEATS[i]);
549 }
550 pw.println('}');
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700551 }
552 }
553
554 final Constants mConstants;
555
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700556 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
557 if (o1.enqueueTime < o2.enqueueTime) {
558 return -1;
559 }
560 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
561 };
562
563 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
564 int where = Collections.binarySearch(array, newItem, comparator);
565 if (where < 0) {
566 where = ~where;
567 }
568 array.add(where, newItem);
569 }
570
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700571 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700572 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
573 * still clean up. On reinstall the package will have a new uid.
574 */
575 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
576 @Override
577 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700578 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700579 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700580 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700581 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700582 final String pkgName = getPackageName(intent);
583 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
584
Christopher Tateee7805b2016-07-15 16:56:56 -0700585 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700586 // Purge the app's jobs if the whole package was just disabled. When this is
587 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700588 if (pkgName != null && pkgUid != -1) {
589 final String[] changedComponents = intent.getStringArrayExtra(
590 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
591 if (changedComponents != null) {
592 for (String component : changedComponents) {
593 if (component.equals(pkgName)) {
594 if (DEBUG) {
595 Slog.d(TAG, "Package state change: " + pkgName);
596 }
597 try {
598 final int userId = UserHandle.getUserId(pkgUid);
599 IPackageManager pm = AppGlobals.getPackageManager();
600 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
601 if (state == COMPONENT_ENABLED_STATE_DISABLED
602 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
603 if (DEBUG) {
604 Slog.d(TAG, "Removing jobs for package " + pkgName
605 + " in user " + userId);
606 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700607 cancelJobsForPackageAndUid(pkgName, pkgUid,
608 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700609 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700610 } catch (RemoteException|IllegalArgumentException e) {
611 /*
612 * IllegalArgumentException means that the package doesn't exist.
613 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
614 * behind outright uninstall, so by the time we try to act it's gone.
615 * We don't need to act on this PACKAGE_CHANGED when this happens;
616 * we'll get a PACKAGE_REMOVED later and clean up then.
617 *
618 * RemoteException can't actually happen; the package manager is
619 * running in this same process.
620 */
621 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700622 break;
623 }
624 }
625 }
626 } else {
627 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
628 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700629 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700630 // If this is an outright uninstall rather than the first half of an
631 // app update sequence, cancel the jobs associated with the app.
632 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
633 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
634 if (DEBUG) {
635 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
636 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700637 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700638 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700639 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700640 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
641 if (DEBUG) {
642 Slog.d(TAG, "Removing jobs for user: " + userId);
643 }
644 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700645 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
646 // Has this package scheduled any jobs, such that we will take action
647 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700648 if (pkgUid != -1) {
649 List<JobStatus> jobsForUid;
650 synchronized (mLock) {
651 jobsForUid = mJobs.getJobsByUid(pkgUid);
652 }
653 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
654 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
655 if (DEBUG) {
656 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
657 + pkgUid + " has jobs");
658 }
659 setResultCode(Activity.RESULT_OK);
660 break;
661 }
662 }
663 }
664 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
665 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700666 if (pkgUid != -1) {
667 if (DEBUG) {
668 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
669 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700670 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700671 }
Christopher Tate7060b042014-06-09 19:50:00 -0700672 }
673 }
674 };
675
Christopher Tateb5c07882016-05-26 17:11:09 -0700676 private String getPackageName(Intent intent) {
677 Uri uri = intent.getData();
678 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
679 return pkg;
680 }
681
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700682 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700683 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800684 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700685 }
686
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700687 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800688 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800689 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700690 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800691 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700692 synchronized (mLock) {
693 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
694 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700695 }
696
697 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla106203b2017-11-02 21:23:44 -0700698 synchronized (mLock) {
699 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
700 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700701 }
702
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700703 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800704 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700705 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800706 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700707 synchronized (mLock) {
708 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
709 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700710 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700711
712 @Override public void onUidCachedChanged(int uid, boolean cached) {
713 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700714 };
715
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800716 public Object getLock() {
717 return mLock;
718 }
719
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700720 public JobStore getJobStore() {
721 return mJobs;
722 }
723
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700724 @Override
725 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700726 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
727 // Let's kick any outstanding jobs for this user.
728 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
729 }
730
731 @Override
732 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700733 // Let's kick any outstanding jobs for this user.
734 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
735 }
736
737 @Override
738 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700739 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700740 }
741
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700742 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
743 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700744 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800745 if (ActivityManager.getService().isAppStartModeDisabled(uId,
746 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700747 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
748 + " -- package not allowed to start");
749 return JobScheduler.RESULT_FAILURE;
750 }
751 } catch (RemoteException e) {
752 }
Christopher Tatea732f012017-10-26 17:26:53 -0700753
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800754 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700755 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
756
757 if (work != null && toCancel != null) {
758 // Fast path: we are adding work to an existing job, and the JobInfo is not
759 // changing. We can just directly enqueue this work in to the job.
760 if (toCancel.getJob().equals(job)) {
Dianne Hackborn342e6032017-04-13 18:04:31 -0700761 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700762 return JobScheduler.RESULT_SUCCESS;
763 }
764 }
765
766 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
767 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800768 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800769 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800770 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
771 Slog.w(TAG, "Too many jobs for uid " + uId);
772 throw new IllegalStateException("Apps may not schedule more than "
773 + MAX_JOBS_PER_APP + " distinct jobs");
774 }
775 }
776
Dianne Hackborna47223f2017-03-30 13:49:13 -0700777 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700778 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700779
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700780 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700781 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700782 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700783 if (work != null) {
784 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700785 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700786 }
787 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700788
789 // If the job is immediately ready to run, then we can just immediately
790 // put it in the pending list and try to schedule it. This is especially
791 // important for jobs with a 0 deadline constraint, since they will happen a fair
792 // amount, we want to handle them as quickly as possible, and semantically we want to
793 // make sure we have started holding the wake lock for the job before returning to
794 // the caller.
795 // If the job is not yet ready to run, there is nothing more to do -- we are
796 // now just waiting for one of its controllers to change state and schedule
797 // the job appropriately.
798 if (isReadyToBeExecutedLocked(jobStatus)) {
799 // This is a new job, we can just immediately put it on the pending
800 // list and try to run it.
801 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700802 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700803 maybeRunPendingJobsLocked();
804 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800805 }
Christopher Tate7060b042014-06-09 19:50:00 -0700806 return JobScheduler.RESULT_SUCCESS;
807 }
808
809 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800810 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800811 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
812 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
813 for (int i = jobs.size() - 1; i >= 0; i--) {
814 JobStatus job = jobs.get(i);
815 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700816 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800817 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700818 }
Christopher Tate7060b042014-06-09 19:50:00 -0700819 }
820
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600821 public JobInfo getPendingJob(int uid, int jobId) {
822 synchronized (mLock) {
823 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
824 for (int i = jobs.size() - 1; i >= 0; i--) {
825 JobStatus job = jobs.get(i);
826 if (job.getJobId() == jobId) {
827 return job.getJob();
828 }
829 }
830 return null;
831 }
832 }
833
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700834 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800835 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700836 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
837 for (int i=0; i<jobsForUser.size(); i++) {
838 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700839 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700840 }
Christopher Tate7060b042014-06-09 19:50:00 -0700841 }
842 }
843
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700844 private void cancelJobsForNonExistentUsers() {
845 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
846 synchronized (mLock) {
847 mJobs.removeJobsOfNonUsers(umi.getUserIds());
848 }
849 }
850
Makoto Onukie7b96182017-08-30 14:53:16 -0700851 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
852 if ("android".equals(pkgName)) {
853 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
854 return;
855 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700856 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700857 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
858 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
859 final JobStatus job = jobsForUid.get(i);
860 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700861 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700862 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700863 }
864 }
865 }
866
Christopher Tate7060b042014-06-09 19:50:00 -0700867 /**
868 * Entry point from client to cancel all jobs originating from their uid.
869 * This will remove the job from the master list, and cancel the job if it was staged for
870 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700871 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800872 *
Christopher Tate7060b042014-06-09 19:50:00 -0700873 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700874 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700875 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700876 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700877 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700878 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700879
880 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800881 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700882 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
883 for (int i=0; i<jobsForUid.size(); i++) {
884 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700885 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700886 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700887 }
Christopher Tate7060b042014-06-09 19:50:00 -0700888 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700889 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700890 }
891
892 /**
893 * Entry point from client to cancel the job corresponding to the jobId provided.
894 * This will remove the job from the master list, and cancel the job if it was staged for
895 * execution or being executed.
896 * @param uid Uid of the calling client.
897 * @param jobId Id of the job, provided at schedule-time.
898 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700899 public boolean cancelJob(int uid, int jobId) {
Christopher Tate7060b042014-06-09 19:50:00 -0700900 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800901 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700902 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700903 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700904 cancelJobImplLocked(toCancel, null, "cancel() called by app");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700905 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700906 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -0700907 }
908 }
909
Dianne Hackborn729a3282017-06-09 16:06:01 -0700910 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700911 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
912 cancelled.unprepareLocked(ActivityManager.getService());
913 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
914 // Remove from pending queue.
915 if (mPendingJobs.remove(cancelled)) {
916 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700917 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700918 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700919 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700920 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700921 }
922
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800923 void updateUidState(int uid, int procState) {
924 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800925 if (procState == ActivityManager.PROCESS_STATE_TOP) {
926 // Only use this if we are exactly the top app. All others can live
927 // with just the foreground priority. This means that persistent processes
928 // can never be the top app priority... that is fine.
929 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
930 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
931 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800932 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800933 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800934 }
935 }
936 }
937
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700938 @Override
939 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800940 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700941 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600942 // When becoming idle, make sure no jobs are actively running,
943 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700944 for (int i=0; i<mActiveServices.size(); i++) {
945 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700946 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600947 if (executing != null
948 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700949 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
950 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700951 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700952 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700953 } else {
954 // When coming out of idle, allow thing to start back up.
955 if (mReadyToRock) {
956 if (mLocalDeviceIdleController != null) {
957 if (!mReportedActive) {
958 mReportedActive = true;
959 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700960 }
961 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700962 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700963 }
964 }
965 }
966 }
967
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700968 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000969 // active is true if pending queue contains jobs OR some job is running.
970 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800971 if (mPendingJobs.size() <= 0) {
972 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700973 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700974 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700975 if (job != null
976 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
977 && !job.dozeWhitelisted) {
978 // We will report active if we have a job running and it is not an exception
979 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800980 active = true;
981 break;
982 }
983 }
984 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000985
986 if (mReportedActive != active) {
987 mReportedActive = active;
988 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800989 mLocalDeviceIdleController.setJobsActive(active);
990 }
991 }
992 }
993
Christopher Tate7060b042014-06-09 19:50:00 -0700994 /**
995 * Initializes the system service.
996 * <p>
997 * Subclasses must define a single argument constructor that accepts the context
998 * and passes it to super.
999 * </p>
1000 *
1001 * @param context The system server context.
1002 */
1003 public JobSchedulerService(Context context) {
1004 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001005
1006 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
1007
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001008 mHandler = new JobHandler(context.getMainLooper());
1009 mConstants = new Constants(mHandler);
1010 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001011
1012 // Set up the app standby bucketing tracker
1013 UsageStatsManagerInternal usageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1014 mStandbyTracker = new StandbyTracker(usageStats);
1015 usageStats.addAppIdleStateChangeListener(mStandbyTracker);
1016
1017 // The job store needs to call back
1018 publishLocalService(JobSchedulerInternal.class, new LocalService());
1019
1020 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001021 mJobs = JobStore.initAndGet(this);
1022
Christopher Tate7060b042014-06-09 19:50:00 -07001023 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001024 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -07001025 mControllers.add(ConnectivityController.get(this));
1026 mControllers.add(TimeController.get(this));
1027 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001028 mBatteryController = BatteryController.get(this);
1029 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001030 mStorageController = StorageController.get(this);
1031 mControllers.add(mStorageController);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001032 mControllers.add(BackgroundJobsController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -08001033 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001034 mControllers.add(ContentObserverController.get(this));
Suprabh Shukla106203b2017-11-02 21:23:44 -07001035 mDeviceIdleJobsController = DeviceIdleJobsController.get(this);
1036 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001037
1038 // If the job store determined that it can't yet reschedule persisted jobs,
1039 // we need to start watching the clock.
1040 if (!mJobs.jobTimesInflatedValid()) {
1041 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1042 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1043 }
Christopher Tate7060b042014-06-09 19:50:00 -07001044 }
1045
Christopher Tate616541d2017-07-26 14:27:38 -07001046 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1047 @Override
1048 public void onReceive(Context context, Intent intent) {
1049 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1050 // When we reach clock sanity, recalculate the temporal windows
1051 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001052 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001053 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1054
1055 // We've done our job now, so stop watching the time.
1056 context.unregisterReceiver(this);
1057
1058 // And kick off the work to update the affected jobs, using a secondary
1059 // thread instead of chugging away here on the main looper thread.
1060 FgThread.getHandler().post(mJobTimeUpdater);
1061 }
1062 }
1063 }
1064 };
1065
1066 private final Runnable mJobTimeUpdater = () -> {
1067 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1068 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1069 synchronized (mLock) {
1070 // Note: we intentionally both look up the existing affected jobs and replace them
1071 // with recalculated ones inside the same lock lifetime.
1072 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1073
1074 // Now, at each position [i], we have both the existing JobStatus
1075 // and the one that replaces it.
1076 final int N = toAdd.size();
1077 for (int i = 0; i < N; i++) {
1078 final JobStatus oldJob = toRemove.get(i);
1079 final JobStatus newJob = toAdd.get(i);
1080 if (DEBUG) {
1081 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1082 }
1083 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1084 }
1085 }
1086 };
1087
Christopher Tate7060b042014-06-09 19:50:00 -07001088 @Override
1089 public void onStart() {
1090 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1091 }
1092
1093 @Override
1094 public void onBootPhase(int phase) {
1095 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001096 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001097 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001098 final IntentFilter filter = new IntentFilter();
1099 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1100 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001101 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1102 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001103 filter.addDataScheme("package");
1104 getContext().registerReceiverAsUser(
1105 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1106 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1107 getContext().registerReceiverAsUser(
1108 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001109 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001110 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001111 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001112 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1113 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001114 } catch (RemoteException e) {
1115 // ignored; both services live in system_server
1116 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001117 // Remove any jobs that are not associated with any of the current users.
1118 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001119 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001120 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001121 // Let's go!
1122 mReadyToRock = true;
1123 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1124 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001125 mLocalDeviceIdleController
1126 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001127 // Create the "runners".
1128 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1129 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001130 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001131 getContext().getMainLooper()));
1132 }
1133 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001134 mJobs.forEachJob(new JobStatusFunctor() {
1135 @Override
1136 public void process(JobStatus job) {
1137 for (int controller = 0; controller < mControllers.size(); controller++) {
1138 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001139 sc.maybeStartTrackingJobLocked(job, null);
1140 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001141 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001142 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001143 // GO GO GO!
1144 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1145 }
Christopher Tate7060b042014-06-09 19:50:00 -07001146 }
1147 }
1148
1149 /**
1150 * Called when we have a job status object that we need to insert in our
1151 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1152 * about.
1153 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001154 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1155 if (!jobStatus.isPreparedLocked()) {
1156 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1157 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001158 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001159 final boolean update = mJobs.add(jobStatus);
1160 if (mReadyToRock) {
1161 for (int i = 0; i < mControllers.size(); i++) {
1162 StateController controller = mControllers.get(i);
1163 if (update) {
1164 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001165 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001166 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001167 }
Christopher Tate7060b042014-06-09 19:50:00 -07001168 }
1169 }
1170
1171 /**
1172 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1173 * object removed.
1174 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001175 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001176 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001177 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001178 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001179
1180 // Remove from store as well as controllers.
1181 final boolean removed = mJobs.remove(jobStatus, writeBack);
1182 if (removed && mReadyToRock) {
1183 for (int i=0; i<mControllers.size(); i++) {
1184 StateController controller = mControllers.get(i);
1185 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001186 }
1187 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001188 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001189 }
1190
Dianne Hackborn729a3282017-06-09 16:06:01 -07001191 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001192 for (int i=0; i<mActiveServices.size(); i++) {
1193 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001194 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001195 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001196 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001197 return true;
1198 }
1199 }
1200 return false;
1201 }
1202
1203 /**
1204 * @param job JobStatus we are querying against.
1205 * @return Whether or not the job represented by the status object is currently being run or
1206 * is pending.
1207 */
1208 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001209 for (int i=0; i<mActiveServices.size(); i++) {
1210 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001211 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001212 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1213 return true;
1214 }
1215 }
1216 return false;
1217 }
1218
Dianne Hackborn807de782016-04-07 17:54:41 -07001219 void noteJobsPending(List<JobStatus> jobs) {
1220 for (int i = jobs.size() - 1; i >= 0; i--) {
1221 JobStatus job = jobs.get(i);
1222 mJobPackageTracker.notePending(job);
1223 }
1224 }
1225
1226 void noteJobsNonpending(List<JobStatus> jobs) {
1227 for (int i = jobs.size() - 1; i >= 0; i--) {
1228 JobStatus job = jobs.get(i);
1229 mJobPackageTracker.noteNonpending(job);
1230 }
1231 }
1232
Christopher Tate7060b042014-06-09 19:50:00 -07001233 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001234 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1235 * specify an override deadline on a failed job (the failed job will run even though it's not
1236 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1237 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1238 *
Christopher Tate7060b042014-06-09 19:50:00 -07001239 * @param failureToReschedule Provided job status that we will reschedule.
1240 * @return A newly instantiated JobStatus with the same constraints as the last job except
1241 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001242 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001243 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001244 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001245 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001246 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001247 final JobInfo job = failureToReschedule.getJob();
1248
1249 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001250 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1251 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001252
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001253 if (failureToReschedule.hasWorkLocked()) {
1254 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1255 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1256 + backoffAttempts + " > work limit "
1257 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1258 return null;
1259 }
1260 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1261 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1262 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1263 return null;
1264 }
1265
Christopher Tate7060b042014-06-09 19:50:00 -07001266 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001267 case JobInfo.BACKOFF_POLICY_LINEAR: {
1268 long backoff = initialBackoffMillis;
1269 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1270 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1271 }
1272 delayMillis = backoff * backoffAttempts;
1273 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001274 default:
1275 if (DEBUG) {
1276 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1277 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001278 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1279 long backoff = initialBackoffMillis;
1280 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1281 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1282 }
1283 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1284 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001285 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001286 delayMillis =
1287 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001288 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1289 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001290 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001291 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001292 for (int ic=0; ic<mControllers.size(); ic++) {
1293 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001294 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001295 }
1296 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001297 }
1298
1299 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001300 * Called after a periodic has executed so we can reschedule it. We take the last execution
1301 * time of the job to be the time of completion (i.e. the time at which this function is
1302 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001303 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001304 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1305 * to underscheduling at least, rather than if we had taken the last execution time to be the
1306 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001307 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1308 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001309 * @return A new job representing the execution criteria for this instantiation of the
1310 * recurring job.
1311 */
1312 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001313 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001314 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001315 long runEarly = 0L;
1316
1317 // If this periodic was rescheduled it won't have a deadline.
1318 if (periodicToReschedule.hasDeadlineConstraint()) {
1319 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1320 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001321 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001322 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001323 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1324 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001325
1326 if (DEBUG) {
1327 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1328 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1329 }
Christopher Tatea732f012017-10-26 17:26:53 -07001330 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1331 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1332 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001333 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001334 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001335 }
1336
1337 // JobCompletedListener implementations.
1338
1339 /**
1340 * A job just finished executing. We fetch the
1341 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1342 * whether we want to reschedule we readd it to the controllers.
1343 * @param jobStatus Completed job.
1344 * @param needsReschedule Whether the implementing class should reschedule this job.
1345 */
1346 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001347 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001348 if (DEBUG) {
1349 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1350 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001351
1352 // If the job wants to be rescheduled, we first need to make the next upcoming
1353 // job so we can transfer any appropriate state over from the previous job when
1354 // we stop it.
1355 final JobStatus rescheduledJob = needsReschedule
1356 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1357
Shreyas Basarge73f10252016-02-11 17:06:13 +00001358 // Do not write back immediately if this is a periodic job. The job may get lost if system
1359 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001360 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001361 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001362 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001363 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001364 // We still want to check for jobs to execute, because this job may have
1365 // scheduled a new job under the same job id, and now we can run it.
1366 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001367 return;
1368 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001369
1370 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001371 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001372 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001373 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001374 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001375 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001376 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001377 } else if (jobStatus.getJob().isPeriodic()) {
1378 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001379 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001380 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001381 } catch (SecurityException e) {
1382 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1383 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001384 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001385 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001386 jobStatus.unprepareLocked(ActivityManager.getService());
1387 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001388 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001389 }
1390
1391 // StateChangedListener implementations.
1392
1393 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001394 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1395 * some controller's state has changed, so as to run through the list of jobs and start/stop
1396 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001397 */
1398 @Override
1399 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001400 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001401 }
1402
1403 @Override
1404 public void onRunJobNow(JobStatus jobStatus) {
1405 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1406 }
1407
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001408 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001409
1410 public JobHandler(Looper looper) {
1411 super(looper);
1412 }
1413
1414 @Override
1415 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001416 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001417 if (!mReadyToRock) {
1418 return;
1419 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001420 switch (message.what) {
1421 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001422 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001423 // runNow can be null, which is a controller's way of indicating that its
1424 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001425 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001426 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001427 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001428 } else {
1429 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001430 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001431 } break;
1432 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001433 if (mReportedActive) {
1434 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001435 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001436 } else {
1437 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001438 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001439 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001440 break;
1441 case MSG_CHECK_JOB_GREEDY:
1442 queueReadyJobsForExecutionLocked();
1443 break;
1444 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001445 cancelJobImplLocked((JobStatus) message.obj, null,
1446 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001447 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001448 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001449 maybeRunPendingJobsLocked();
1450 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1451 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001452 }
1453 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001454 }
Christopher Tate7060b042014-06-09 19:50:00 -07001455
Dianne Hackborn6d068262017-05-16 13:14:37 -07001456 private void stopNonReadyActiveJobsLocked() {
1457 for (int i=0; i<mActiveServices.size(); i++) {
1458 JobServiceContext serviceContext = mActiveServices.get(i);
1459 final JobStatus running = serviceContext.getRunningJobLocked();
1460 if (running != null && !running.isReady()) {
1461 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001462 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1463 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001464 }
1465 }
1466 }
1467
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001468 /**
1469 * Run through list of jobs and execute all possible - at least one is expired so we do
1470 * as many as we can.
1471 */
1472 private void queueReadyJobsForExecutionLocked() {
1473 if (DEBUG) {
1474 Slog.d(TAG, "queuing all ready jobs for execution:");
1475 }
1476 noteJobsNonpending(mPendingJobs);
1477 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001478 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001479 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001480 mJobs.forEachJob(mReadyQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001481 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001482 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001483
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001484 if (DEBUG) {
1485 final int queuedJobs = mPendingJobs.size();
1486 if (queuedJobs == 0) {
1487 Slog.d(TAG, "No jobs pending.");
1488 } else {
1489 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001490 }
1491 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001492 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001493
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001494 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1495 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001496
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001497 @Override
1498 public void process(JobStatus job) {
1499 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001500 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001501 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001502 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001503 if (newReadyJobs == null) {
1504 newReadyJobs = new ArrayList<JobStatus>();
1505 }
1506 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001507 }
1508 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001509
1510 public void postProcess() {
1511 if (newReadyJobs != null) {
1512 noteJobsPending(newReadyJobs);
1513 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001514 if (mPendingJobs.size() > 1) {
1515 mPendingJobs.sort(mEnqueueTimeComparator);
1516 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001517 }
1518 newReadyJobs = null;
1519 }
1520 }
1521 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1522
1523 /**
1524 * The state of at least one job has changed. Here is where we could enforce various
1525 * policies on when we want to execute jobs.
1526 * Right now the policy is such:
1527 * If >1 of the ready jobs is idle mode we send all of them off
1528 * if more than 2 network connectivity jobs are ready we send them all off.
1529 * If more than 4 jobs total are ready we send them all off.
1530 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1531 */
1532 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1533 int chargingCount;
1534 int batteryNotLowCount;
1535 int storageNotLowCount;
1536 int idleCount;
1537 int backoffCount;
1538 int connectivityCount;
1539 int contentCount;
1540 List<JobStatus> runnableJobs;
1541
1542 public MaybeReadyJobQueueFunctor() {
1543 reset();
1544 }
1545
1546 // Functor method invoked for each job via JobStore.forEachJob()
1547 @Override
1548 public void process(JobStatus job) {
1549 if (isReadyToBeExecutedLocked(job)) {
1550 try {
1551 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1552 job.getJob().getService().getPackageName())) {
1553 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1554 + job.getJob().toString() + " -- package not allowed to start");
1555 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1556 return;
1557 }
1558 } catch (RemoteException e) {
1559 }
1560 if (job.getNumFailures() > 0) {
1561 backoffCount++;
1562 }
1563 if (job.hasIdleConstraint()) {
1564 idleCount++;
1565 }
1566 if (job.hasConnectivityConstraint()) {
1567 connectivityCount++;
1568 }
1569 if (job.hasChargingConstraint()) {
1570 chargingCount++;
1571 }
1572 if (job.hasBatteryNotLowConstraint()) {
1573 batteryNotLowCount++;
1574 }
1575 if (job.hasStorageNotLowConstraint()) {
1576 storageNotLowCount++;
1577 }
1578 if (job.hasContentTriggerConstraint()) {
1579 contentCount++;
1580 }
1581 if (runnableJobs == null) {
1582 runnableJobs = new ArrayList<>();
1583 }
1584 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001585 }
1586 }
1587
1588 public void postProcess() {
1589 if (backoffCount > 0 ||
1590 idleCount >= mConstants.MIN_IDLE_COUNT ||
1591 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1592 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1593 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1594 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1595 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1596 (runnableJobs != null
1597 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1598 if (DEBUG) {
1599 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1600 }
1601 noteJobsPending(runnableJobs);
1602 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001603 if (mPendingJobs.size() > 1) {
1604 mPendingJobs.sort(mEnqueueTimeComparator);
1605 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001606 } else {
1607 if (DEBUG) {
1608 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1609 }
1610 }
1611
1612 // Be ready for next time
1613 reset();
1614 }
1615
1616 private void reset() {
1617 chargingCount = 0;
1618 idleCount = 0;
1619 backoffCount = 0;
1620 connectivityCount = 0;
1621 batteryNotLowCount = 0;
1622 storageNotLowCount = 0;
1623 contentCount = 0;
1624 runnableJobs = null;
1625 }
1626 }
1627 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1628
1629 private void maybeQueueReadyJobsForExecutionLocked() {
1630 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1631
1632 noteJobsNonpending(mPendingJobs);
1633 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001634 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001635 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001636 mJobs.forEachJob(mMaybeQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001637 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001638 mMaybeQueueFunctor.postProcess();
1639 }
1640
Christopher Tatea732f012017-10-26 17:26:53 -07001641 private boolean updateStandbyHeartbeatLocked() {
1642 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1643 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1644 if (beatsElapsed > 0) {
1645 mHeartbeat += beatsElapsed;
1646 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1647 if (DEBUG_STANDBY) {
1648 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed + " to " + mHeartbeat);
1649 }
1650 return true;
1651 }
1652 return false;
1653 }
1654
1655 private void updateNextStandbyHeartbeatsLocked() {
1656 // don't update ACTIVE or NEVER bucket milestones
1657 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
1658 while (mHeartbeat >= mNextBucketHeartbeat[i]) {
1659 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1660 }
1661 if (DEBUG_STANDBY) {
1662 Slog.v(TAG, " Bucket " + i + " next heartbeat " + mNextBucketHeartbeat[i]);
1663 }
1664 }
1665 }
1666
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001667 /**
1668 * Criteria for moving a job into the pending queue:
1669 * - It's ready.
1670 * - It's not pending.
1671 * - It's not already running on a JSC.
1672 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001673 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001674 * - The component is enabled and runnable.
1675 */
1676 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001677 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001678
1679 if (DEBUG) {
1680 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1681 + " ready=" + jobReady);
1682 }
1683
1684 // This is a condition that is very likely to be false (most jobs that are
1685 // scheduled are sitting there, not ready yet) and very cheap to check (just
1686 // a few conditions on data in JobStatus).
1687 if (!jobReady) {
1688 return false;
1689 }
1690
1691 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001692
1693 final int userId = job.getUserId();
1694 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1695
1696 if (DEBUG) {
1697 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001698 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001699 }
1700
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001701 // These are also fairly cheap to check, though they typically will not
1702 // be conditions we fail.
1703 if (!jobExists || !userStarted) {
1704 return false;
1705 }
1706
1707 final boolean jobPending = mPendingJobs.contains(job);
1708 final boolean jobActive = isCurrentlyActiveLocked(job);
1709
1710 if (DEBUG) {
1711 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1712 + " pending=" + jobPending + " active=" + jobActive);
1713 }
1714
1715 // These can be a little more expensive (especially jobActive, since we need to
1716 // go through the array of all potentially active jobs), so we are doing them
1717 // later... but still before checking with the package manager!
1718 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001719 return false;
1720 }
1721
Christopher Tatea732f012017-10-26 17:26:53 -07001722 // If the app is in a non-active standby bucket, make sure we've waited
1723 // an appropriate amount of time since the last invocation
1724 if (mHeartbeat < mNextBucketHeartbeat[job.getStandbyBucket()]) {
1725 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
1726 if (job.getWhenStandbyDeferred() == 0) {
1727 if (DEBUG_STANDBY) {
1728 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
1729 + mNextBucketHeartbeat[job.getStandbyBucket()] + " for " + job);
1730 }
1731 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
1732 }
1733 return false;
1734 }
1735
1736 // The expensive check last: validate that the defined package+service is
1737 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001738 final boolean componentPresent;
1739 try {
1740 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1741 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1742 userId) != null);
1743 } catch (RemoteException e) {
1744 throw e.rethrowAsRuntimeException();
1745 }
1746
1747 if (DEBUG) {
1748 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1749 + " componentPresent=" + componentPresent);
1750 }
1751
1752 // Everything else checked out so far, so this is the final yes/no check
1753 return componentPresent;
1754 }
1755
1756 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001757 * Reconcile jobs in the pending queue against available execution contexts.
1758 * A controller can force a job into the pending queue even if it's already running, but
1759 * here is where we decide whether to actually execute it.
1760 */
1761 private void maybeRunPendingJobsLocked() {
1762 if (DEBUG) {
1763 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1764 }
1765 assignJobsToContextsLocked();
1766 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001767 }
1768
Dianne Hackborn807de782016-04-07 17:54:41 -07001769 private int adjustJobPriority(int curPriority, JobStatus job) {
1770 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1771 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001772 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001773 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001774 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001775 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1776 }
1777 }
1778 return curPriority;
1779 }
1780
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001781 private int evaluateJobPriorityLocked(JobStatus job) {
1782 int priority = job.getPriority();
1783 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001784 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001785 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001786 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1787 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001788 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001789 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001790 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001791 }
1792
Christopher Tate7060b042014-06-09 19:50:00 -07001793 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001794 * Takes jobs from pending queue and runs them on available contexts.
1795 * If no contexts are available, preempts lower priority jobs to
1796 * run higher priority ones.
1797 * Lock on mJobs before calling this function.
1798 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001799 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001800 if (DEBUG) {
1801 Slog.d(TAG, printPendingQueue());
1802 }
1803
Dianne Hackborn970510b2016-02-24 16:56:42 -08001804 int memLevel;
1805 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001806 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001807 } catch (RemoteException e) {
1808 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1809 }
1810 switch (memLevel) {
1811 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001812 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001813 break;
1814 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001815 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001816 break;
1817 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001818 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001819 break;
1820 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001821 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001822 break;
1823 }
1824
1825 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1826 boolean[] act = mTmpAssignAct;
1827 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1828 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001829 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001830 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1831 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001832 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001833 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001834 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001835 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1836 numForeground++;
1837 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001838 }
1839 act[i] = false;
1840 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001841 }
1842 if (DEBUG) {
1843 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1844 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001845 for (int i=0; i<mPendingJobs.size(); i++) {
1846 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001847
1848 // If job is already running, go to next job.
1849 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1850 if (jobRunningContext != -1) {
1851 continue;
1852 }
1853
Dianne Hackborn970510b2016-02-24 16:56:42 -08001854 final int priority = evaluateJobPriorityLocked(nextPending);
1855 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001856
Shreyas Basarge5db09082016-01-07 13:38:29 +00001857 // Find a context for nextPending. The context should be available OR
1858 // it should have lowest priority among all running jobs
1859 // (sharing the same Uid as nextPending)
1860 int minPriority = Integer.MAX_VALUE;
1861 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001862 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1863 JobStatus job = contextIdToJobMap[j];
1864 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001865 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001866 if ((numActive < mMaxActiveJobs ||
1867 (priority >= JobInfo.PRIORITY_TOP_APP &&
1868 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001869 (preferredUid == nextPending.getUid() ||
1870 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1871 // This slot is free, and we haven't yet hit the limit on
1872 // concurrent jobs... we can just throw the job in to here.
1873 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001874 break;
1875 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001876 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001877 // the context has a preferred Uid or we have reached the limit on
1878 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001879 continue;
1880 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001881 if (job.getUid() != nextPending.getUid()) {
1882 continue;
1883 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001884 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001885 continue;
1886 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001887 if (minPriority > nextPending.lastEvaluatedPriority) {
1888 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001889 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001890 }
1891 }
1892 if (minPriorityContextId != -1) {
1893 contextIdToJobMap[minPriorityContextId] = nextPending;
1894 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001895 numActive++;
1896 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1897 numForeground++;
1898 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001899 }
1900 }
1901 if (DEBUG) {
1902 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1903 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001904 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001905 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001906 boolean preservePreferredUid = false;
1907 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001908 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001909 if (js != null) {
1910 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001911 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001912 }
1913 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001914 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001915 preservePreferredUid = true;
1916 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001917 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001918 if (DEBUG) {
1919 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001920 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001921 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001922 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001923 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001924 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001925 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1926 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001927 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001928 if (mPendingJobs.remove(pendingJob)) {
1929 mJobPackageTracker.noteNonpending(pendingJob);
1930 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001931 }
1932 }
1933 if (!preservePreferredUid) {
1934 mActiveServices.get(i).clearPreferredUid();
1935 }
1936 }
1937 }
1938
1939 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1940 for (int i=0; i<map.length; i++) {
1941 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1942 return i;
1943 }
1944 }
1945 return -1;
1946 }
1947
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001948 final class LocalService implements JobSchedulerInternal {
1949
1950 /**
Christopher Tatea732f012017-10-26 17:26:53 -07001951 * The current bucket heartbeat ordinal
1952 */
1953 public long currentHeartbeat() {
1954 return getCurrentHeartbeat();
1955 }
1956
1957 /**
1958 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
1959 */
1960 public long nextHeartbeatForBucket(int bucket) {
1961 synchronized (mLock) {
1962 return mNextBucketHeartbeat[bucket];
1963 }
1964 }
1965
1966 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001967 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
1968 * jobs are always considered pending.
1969 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001970 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001971 public List<JobInfo> getSystemScheduledPendingJobs() {
1972 synchronized (mLock) {
1973 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
1974 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
1975 @Override
1976 public void process(JobStatus job) {
1977 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
1978 pendingJobs.add(job.getJob());
1979 }
1980 }
1981 });
1982 return pendingJobs;
1983 }
1984 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001985
1986 @Override
1987 public void addBackingUpUid(int uid) {
1988 synchronized (mLock) {
1989 // No need to actually do anything here, since for a full backup the
1990 // activity manager will kill the process which will kill the job (and
1991 // cause it to restart, but now it can't run).
1992 mBackingUpUids.put(uid, uid);
1993 }
1994 }
1995
1996 @Override
1997 public void removeBackingUpUid(int uid) {
1998 synchronized (mLock) {
1999 mBackingUpUids.delete(uid);
2000 // If there are any jobs for this uid, we need to rebuild the pending list
2001 // in case they are now ready to run.
2002 if (mJobs.countJobsForUid(uid) > 0) {
2003 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2004 }
2005 }
2006 }
2007
2008 @Override
2009 public void clearAllBackingUpUids() {
2010 synchronized (mLock) {
2011 if (mBackingUpUids.size() > 0) {
2012 mBackingUpUids.clear();
2013 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2014 }
2015 }
2016 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002017
2018 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002019 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002020 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002021 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002022 }
2023 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002024 }
2025
Shreyas Basarge5db09082016-01-07 13:38:29 +00002026 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002027 * Tracking of app assignments to standby buckets
2028 */
2029 final class StandbyTracker extends AppIdleStateChangeListener {
2030 final UsageStatsManagerInternal mUsageStats;
2031
2032 StandbyTracker(UsageStatsManagerInternal usageStats) {
2033 mUsageStats = usageStats;
2034 }
2035
2036 // AppIdleStateChangeListener interface for live updates
2037
2038 @Override
2039 public void onAppIdleStateChanged(final String packageName, final int userId,
2040 boolean idle, int bucket) {
2041 final int uid = mLocalPM.getPackageUid(packageName,
2042 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2043 if (uid < 0) {
2044 if (DEBUG_STANDBY) {
2045 Slog.i(TAG, "App idle state change for unknown app "
2046 + packageName + "/" + userId);
2047 }
2048 return;
2049 }
2050
2051 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2052 // update job bookkeeping out of band
2053 BackgroundThread.getHandler().post(() -> {
2054 if (DEBUG_STANDBY) {
2055 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2056 }
2057 synchronized (mLock) {
2058 // TODO: update to be more efficient once we can slice by source UID
2059 mJobs.forEachJob((JobStatus job) -> {
2060 if (job.getSourceUid() == uid) {
2061 job.setStandbyBucket(bucketIndex);
2062 }
2063 });
2064 onControllerStateChanged();
2065 }
2066 });
2067 }
2068
2069 @Override
2070 public void onParoleStateChanged(boolean isParoleOn) {
2071 // Unused
2072 }
2073 }
2074
2075 public static int standbyBucketToBucketIndex(int bucket) {
2076 // Normalize AppStandby constants to indices into our bookkeeping
2077 if (bucket == AppStandby.STANDBY_BUCKET_NEVER) return 4;
2078 else if (bucket >= AppStandby.STANDBY_BUCKET_RARE) return 3;
2079 else if (bucket >= AppStandby.STANDBY_BUCKET_FREQUENT) return 2;
2080 else if (bucket >= AppStandby.STANDBY_BUCKET_WORKING_SET) return 1;
2081 else return 0;
2082 }
2083
2084 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2085 UsageStatsManagerInternal usageStats = LocalServices.getService(
2086 UsageStatsManagerInternal.class);
2087 int bucket = usageStats != null
2088 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2089 : 0;
2090
2091 bucket = standbyBucketToBucketIndex(bucket);
2092
2093 if (DEBUG_STANDBY) {
2094 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2095 }
2096 return bucket;
2097 }
2098
2099 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002100 * Binder stub trampoline implementation
2101 */
2102 final class JobSchedulerStub extends IJobScheduler.Stub {
2103 /** Cache determination of whether a given app can persist jobs
2104 * key is uid of the calling app; value is undetermined/true/false
2105 */
2106 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2107
2108 // Enforce that only the app itself (or shared uid participant) can schedule a
2109 // job that runs one of the app's services, as well as verifying that the
2110 // named service properly requires the BIND_JOB_SERVICE permission
2111 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002112 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002113 final ComponentName service = job.getService();
2114 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002115 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002116 PackageManager.MATCH_DIRECT_BOOT_AWARE
2117 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002118 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002119 if (si == null) {
2120 throw new IllegalArgumentException("No such service " + service);
2121 }
Christopher Tate7060b042014-06-09 19:50:00 -07002122 if (si.applicationInfo.uid != uid) {
2123 throw new IllegalArgumentException("uid " + uid +
2124 " cannot schedule job in " + service.getPackageName());
2125 }
2126 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2127 throw new IllegalArgumentException("Scheduled service " + service
2128 + " does not require android.permission.BIND_JOB_SERVICE permission");
2129 }
Christopher Tate5568f542014-06-18 13:53:31 -07002130 } catch (RemoteException e) {
2131 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002132 }
2133 }
2134
2135 private boolean canPersistJobs(int pid, int uid) {
2136 // If we get this far we're good to go; all we need to do now is check
2137 // whether the app is allowed to persist its scheduled work.
2138 final boolean canPersist;
2139 synchronized (mPersistCache) {
2140 Boolean cached = mPersistCache.get(uid);
2141 if (cached != null) {
2142 canPersist = cached.booleanValue();
2143 } else {
2144 // Persisting jobs is tantamount to running at boot, so we permit
2145 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2146 // permission
2147 int result = getContext().checkPermission(
2148 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2149 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2150 mPersistCache.put(uid, canPersist);
2151 }
2152 }
2153 return canPersist;
2154 }
2155
2156 // IJobScheduler implementation
2157 @Override
2158 public int schedule(JobInfo job) throws RemoteException {
2159 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002160 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002161 }
2162 final int pid = Binder.getCallingPid();
2163 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002164 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002165
2166 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002167 if (job.isPersisted()) {
2168 if (!canPersistJobs(pid, uid)) {
2169 throw new IllegalArgumentException("Error: requested job be persisted without"
2170 + " holding RECEIVE_BOOT_COMPLETED permission.");
2171 }
2172 }
Christopher Tate7060b042014-06-09 19:50:00 -07002173
Jeff Sharkey785f4942016-07-14 10:31:15 -06002174 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2175 getContext().enforceCallingOrSelfPermission(
2176 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2177 }
2178
Christopher Tate7060b042014-06-09 19:50:00 -07002179 long ident = Binder.clearCallingIdentity();
2180 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002181 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2182 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002183 } finally {
2184 Binder.restoreCallingIdentity(ident);
2185 }
2186 }
2187
2188 // IJobScheduler implementation
2189 @Override
2190 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2191 if (DEBUG) {
2192 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2193 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002194 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002195 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002196
2197 enforceValidJobRequest(uid, job);
2198 if (job.isPersisted()) {
2199 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2200 }
2201 if (work == null) {
2202 throw new NullPointerException("work is null");
2203 }
2204
2205 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2206 getContext().enforceCallingOrSelfPermission(
2207 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2208 }
2209
2210 long ident = Binder.clearCallingIdentity();
2211 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002212 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2213 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002214 } finally {
2215 Binder.restoreCallingIdentity(ident);
2216 }
2217 }
2218
2219 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002220 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002221 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002222 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002223 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002224 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002225 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002226 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002227
2228 if (packageName == null) {
2229 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002230 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002231
2232 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2233 android.Manifest.permission.UPDATE_DEVICE_STATS);
2234 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2235 throw new SecurityException("Caller uid " + callerUid
2236 + " not permitted to schedule jobs for other apps");
2237 }
2238
Jeff Sharkey4f100402016-05-03 17:44:23 -06002239 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2240 getContext().enforceCallingOrSelfPermission(
2241 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2242 }
2243
Shreyas Basarge968ac752016-01-11 23:09:26 +00002244 long ident = Binder.clearCallingIdentity();
2245 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002246 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002247 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002248 } finally {
2249 Binder.restoreCallingIdentity(ident);
2250 }
2251 }
2252
2253 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002254 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2255 final int uid = Binder.getCallingUid();
2256
2257 long ident = Binder.clearCallingIdentity();
2258 try {
2259 return JobSchedulerService.this.getPendingJobs(uid);
2260 } finally {
2261 Binder.restoreCallingIdentity(ident);
2262 }
2263 }
2264
2265 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002266 public JobInfo getPendingJob(int jobId) throws RemoteException {
2267 final int uid = Binder.getCallingUid();
2268
2269 long ident = Binder.clearCallingIdentity();
2270 try {
2271 return JobSchedulerService.this.getPendingJob(uid, jobId);
2272 } finally {
2273 Binder.restoreCallingIdentity(ident);
2274 }
2275 }
2276
2277 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002278 public void cancelAll() throws RemoteException {
2279 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002280 long ident = Binder.clearCallingIdentity();
2281 try {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002282 JobSchedulerService.this.cancelJobsForUid(uid, "cancelAll() called by app");
Christopher Tate7060b042014-06-09 19:50:00 -07002283 } finally {
2284 Binder.restoreCallingIdentity(ident);
2285 }
2286 }
2287
2288 @Override
2289 public void cancel(int jobId) throws RemoteException {
2290 final int uid = Binder.getCallingUid();
2291
2292 long ident = Binder.clearCallingIdentity();
2293 try {
2294 JobSchedulerService.this.cancelJob(uid, jobId);
2295 } finally {
2296 Binder.restoreCallingIdentity(ident);
2297 }
2298 }
2299
2300 /**
2301 * "dumpsys" infrastructure
2302 */
2303 @Override
2304 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002305 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002306
2307 long identityToken = Binder.clearCallingIdentity();
2308 try {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002309 JobSchedulerService.this.dumpInternal(pw, args);
Christopher Tate7060b042014-06-09 19:50:00 -07002310 } finally {
2311 Binder.restoreCallingIdentity(identityToken);
2312 }
2313 }
Christopher Tate5d346052016-03-08 12:56:08 -08002314
2315 @Override
2316 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002317 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002318 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002319 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002320 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002321 };
2322
Christopher Tate5d346052016-03-08 12:56:08 -08002323 // Shell command infrastructure: run the given job immediately
2324 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2325 if (DEBUG) {
2326 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2327 + " " + jobId + " f=" + force);
2328 }
2329
2330 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002331 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2332 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002333 if (uid < 0) {
2334 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2335 }
2336
2337 synchronized (mLock) {
2338 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2339 if (js == null) {
2340 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2341 }
2342
2343 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2344 if (!js.isConstraintsSatisfied()) {
2345 js.overrideState = 0;
2346 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2347 }
2348
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002349 queueReadyJobsForExecutionLocked();
2350 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002351 }
2352 } catch (RemoteException e) {
2353 // can't happen
2354 }
2355 return 0;
2356 }
2357
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002358 // Shell command infrastructure: immediately timeout currently executing jobs
2359 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2360 boolean hasJobId, int jobId) {
2361 if (DEBUG) {
2362 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2363 }
2364
2365 synchronized (mLock) {
2366 boolean foundSome = false;
2367 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002368 final JobServiceContext jc = mActiveServices.get(i);
2369 final JobStatus js = jc.getRunningJobLocked();
2370 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId)) {
2371 foundSome = true;
2372 pw.print("Timing out: ");
2373 js.printUniqueId(pw);
2374 pw.print(" ");
2375 pw.println(js.getServiceComponent().flattenToShortString());
2376 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002377 }
2378 if (!foundSome) {
2379 pw.println("No matching executing jobs found.");
2380 }
2381 }
2382 return 0;
2383 }
2384
Christopher Tate8c67d122017-09-29 16:54:26 -07002385 // Shell command infrastructure: cancel a scheduled job
2386 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2387 boolean hasJobId, int jobId) {
2388 if (DEBUG) {
2389 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2390 }
2391
2392 int pkgUid = -1;
2393 try {
2394 IPackageManager pm = AppGlobals.getPackageManager();
2395 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2396 } catch (RemoteException e) { /* can't happen */ }
2397
2398 if (pkgUid < 0) {
2399 pw.println("Package " + pkgName + " not found.");
2400 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2401 }
2402
2403 if (!hasJobId) {
2404 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2405 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2406 pw.println("No matching jobs found.");
2407 }
2408 } else {
2409 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
2410 if (!cancelJob(pkgUid, jobId)) {
2411 pw.println("No matching job found.");
2412 }
2413 }
2414
2415 return 0;
2416 }
2417
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002418 void setMonitorBattery(boolean enabled) {
2419 synchronized (mLock) {
2420 if (mBatteryController != null) {
2421 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2422 }
2423 }
2424 }
2425
2426 int getBatterySeq() {
2427 synchronized (mLock) {
2428 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2429 }
2430 }
2431
2432 boolean getBatteryCharging() {
2433 synchronized (mLock) {
2434 return mBatteryController != null
2435 ? mBatteryController.getTracker().isOnStablePower() : false;
2436 }
2437 }
2438
2439 boolean getBatteryNotLow() {
2440 synchronized (mLock) {
2441 return mBatteryController != null
2442 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2443 }
2444 }
2445
Dianne Hackborn532ea262017-03-17 17:50:55 -07002446 int getStorageSeq() {
2447 synchronized (mLock) {
2448 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2449 }
2450 }
2451
2452 boolean getStorageNotLow() {
2453 synchronized (mLock) {
2454 return mStorageController != null
2455 ? mStorageController.getTracker().isStorageNotLow() : false;
2456 }
2457 }
2458
Christopher Tatea732f012017-10-26 17:26:53 -07002459 long getCurrentHeartbeat() {
2460 synchronized (mLock) {
2461 return mHeartbeat;
2462 }
2463 }
2464
Dianne Hackborn6d068262017-05-16 13:14:37 -07002465 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2466 try {
2467 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2468 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2469 if (uid < 0) {
2470 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2471 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2472 }
2473
2474 synchronized (mLock) {
2475 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2476 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2477 if (js == null) {
2478 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2479 pw.print("/jid"); pw.print(jobId); pw.println(")");
2480 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2481 }
2482
2483 boolean printed = false;
2484 if (mPendingJobs.contains(js)) {
2485 pw.print("pending");
2486 printed = true;
2487 }
2488 if (isCurrentlyActiveLocked(js)) {
2489 if (printed) {
2490 pw.print(" ");
2491 }
2492 printed = true;
2493 pw.println("active");
2494 }
2495 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2496 if (printed) {
2497 pw.print(" ");
2498 }
2499 printed = true;
2500 pw.println("user-stopped");
2501 }
2502 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2503 if (printed) {
2504 pw.print(" ");
2505 }
2506 printed = true;
2507 pw.println("backing-up");
2508 }
2509 boolean componentPresent = false;
2510 try {
2511 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2512 js.getServiceComponent(),
2513 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2514 js.getUserId()) != null);
2515 } catch (RemoteException e) {
2516 }
2517 if (!componentPresent) {
2518 if (printed) {
2519 pw.print(" ");
2520 }
2521 printed = true;
2522 pw.println("no-component");
2523 }
2524 if (js.isReady()) {
2525 if (printed) {
2526 pw.print(" ");
2527 }
2528 printed = true;
2529 pw.println("ready");
2530 }
2531 if (!printed) {
2532 pw.print("waiting");
2533 }
2534 pw.println();
2535 }
2536 } catch (RemoteException e) {
2537 // can't happen
2538 }
2539 return 0;
2540 }
2541
Shreyas Basarge5db09082016-01-07 13:38:29 +00002542 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2543 StringBuilder s = new StringBuilder(initial + ": ");
2544 for (int i=0; i<map.length; i++) {
2545 s.append("(")
2546 .append(map[i] == null? -1: map[i].getJobId())
2547 .append(map[i] == null? -1: map[i].getUid())
2548 .append(")" );
2549 }
2550 return s.toString();
2551 }
2552
2553 private String printPendingQueue() {
2554 StringBuilder s = new StringBuilder("Pending queue: ");
2555 Iterator<JobStatus> it = mPendingJobs.iterator();
2556 while (it.hasNext()) {
2557 JobStatus js = it.next();
2558 s.append("(")
2559 .append(js.getJob().getId())
2560 .append(", ")
2561 .append(js.getUid())
2562 .append(") ");
2563 }
2564 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002565 }
Christopher Tate7060b042014-06-09 19:50:00 -07002566
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002567 static void dumpHelp(PrintWriter pw) {
2568 pw.println("Job Scheduler (jobscheduler) dump options:");
2569 pw.println(" [-h] [package] ...");
2570 pw.println(" -h: print this help");
2571 pw.println(" [package] is an optional package name to limit the output to.");
2572 }
2573
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002574 void dumpInternal(final PrintWriter pw, String[] args) {
2575 int filterUid = -1;
2576 if (!ArrayUtils.isEmpty(args)) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002577 int opti = 0;
2578 while (opti < args.length) {
2579 String arg = args[opti];
2580 if ("-h".equals(arg)) {
2581 dumpHelp(pw);
2582 return;
2583 } else if ("-a".equals(arg)) {
2584 // Ignore, we always dump all.
2585 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2586 pw.println("Unknown option: " + arg);
2587 return;
2588 } else {
2589 break;
2590 }
2591 opti++;
2592 }
2593 if (opti < args.length) {
2594 String pkg = args[opti];
2595 try {
2596 filterUid = getContext().getPackageManager().getPackageUid(pkg,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002597 PackageManager.MATCH_ANY_USER);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002598 } catch (NameNotFoundException ignored) {
2599 pw.println("Invalid package: " + pkg);
2600 return;
2601 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002602 }
2603 }
2604
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002605 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07002606 final long nowElapsed = sElapsedRealtimeClock.millis();
2607 final long nowUptime = sUptimeMillisClock.millis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002608 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002609 mConstants.dump(pw);
2610 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002611 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002612 pw.print("Registered ");
2613 pw.print(mJobs.size());
2614 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002615 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002616 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2617 Collections.sort(jobs, new Comparator<JobStatus>() {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002618 @Override
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002619 public int compare(JobStatus o1, JobStatus o2) {
2620 int uid1 = o1.getUid();
2621 int uid2 = o2.getUid();
2622 int id1 = o1.getJobId();
2623 int id2 = o2.getJobId();
2624 if (uid1 != uid2) {
2625 return uid1 < uid2 ? -1 : 1;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002626 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002627 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Christopher Tate2f36fd62016-02-18 18:36:08 -08002628 }
2629 });
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002630 for (JobStatus job : jobs) {
2631 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2632 pw.println(job.toShortStringExceptUniqueId());
2633
2634 // Skip printing details if the caller requested a filter
2635 if (!job.shouldDump(filterUidFinal)) {
2636 continue;
2637 }
2638
Dianne Hackborn6d068262017-05-16 13:14:37 -07002639 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002640 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002641 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002642 pw.print(" (job=");
2643 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002644 pw.print(" user=");
2645 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002646 pw.print(" !pending=");
2647 pw.print(!mPendingJobs.contains(job));
2648 pw.print(" !active=");
2649 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002650 pw.print(" !backingup=");
2651 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002652 pw.print(" comp=");
2653 boolean componentPresent = false;
2654 try {
2655 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2656 job.getServiceComponent(),
2657 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2658 job.getUserId()) != null);
2659 } catch (RemoteException e) {
2660 }
2661 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002662 pw.println(")");
2663 }
Christopher Tate7060b042014-06-09 19:50:00 -07002664 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002665 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002666 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002667 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002668 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002669 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002670 }
2671 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002672 pw.println("Uid priority overrides:");
2673 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002674 int uid = mUidPriorityOverride.keyAt(i);
2675 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2676 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2677 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2678 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002679 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002680 if (mBackingUpUids.size() > 0) {
2681 pw.println();
2682 pw.println("Backing up uids:");
2683 boolean first = true;
2684 for (int i = 0; i < mBackingUpUids.size(); i++) {
2685 int uid = mBackingUpUids.keyAt(i);
2686 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2687 if (first) {
2688 pw.print(" ");
2689 first = false;
2690 } else {
2691 pw.print(", ");
2692 }
2693 pw.print(UserHandle.formatUid(uid));
2694 }
2695 }
2696 pw.println();
2697 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002698 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002699 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002700 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002701 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2702 pw.println();
2703 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002704 pw.println("Pending queue:");
2705 for (int i=0; i<mPendingJobs.size(); i++) {
2706 JobStatus job = mPendingJobs.get(i);
2707 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2708 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002709 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002710 int priority = evaluateJobPriorityLocked(job);
2711 if (priority != JobInfo.PRIORITY_DEFAULT) {
2712 pw.print(" Evaluated priority: "); pw.println(priority);
2713 }
2714 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002715 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002716 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002717 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002718 }
Christopher Tate7060b042014-06-09 19:50:00 -07002719 pw.println();
2720 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002721 for (int i=0; i<mActiveServices.size(); i++) {
2722 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002723 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002724 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002725 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002726 if (jsc.mStoppedReason != null) {
2727 pw.print("inactive since ");
2728 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2729 pw.print(", stopped because: ");
2730 pw.println(jsc.mStoppedReason);
2731 } else {
2732 pw.println("inactive");
2733 }
Christopher Tate7060b042014-06-09 19:50:00 -07002734 continue;
2735 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002736 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002737 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002738 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002739 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002740 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002741 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002742 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002743 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002744 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002745 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002746 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002747 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002748 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002749 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002750 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2751 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002752 }
2753 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002754 if (filterUid == -1) {
2755 pw.println();
2756 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2757 pw.print("mReportedActive="); pw.println(mReportedActive);
2758 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2759 }
Makoto Onukie7b02982017-08-24 14:23:36 -07002760 pw.println();
2761 pw.print("PersistStats: ");
2762 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07002763 }
2764 pw.println();
2765 }
2766}