blob: bd1dbf9c46e8468f2ac2f5187ea23572b12affc3 [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.job;
18
Christopher Tateb5c07882016-05-26 17:11:09 -070019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21
Christopher Tateee7805b2016-07-15 16:56:56 -070022import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070023import android.app.ActivityManager;
Christopher Tate5568f542014-06-18 13:53:31 -070024import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070025import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070026import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070027import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000028import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.app.job.JobScheduler;
30import android.app.job.JobService;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070031import android.app.job.JobWorkItem;
Amith Yamasaniafbccb72017-11-27 10:44:24 -080032import android.app.usage.UsageStatsManager;
Christopher Tatea732f012017-10-26 17:26:53 -070033import android.app.usage.UsageStatsManagerInternal;
34import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
Christopher Tate7060b042014-06-09 19:50:00 -070035import android.content.BroadcastReceiver;
36import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070037import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070038import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070041import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070042import android.content.pm.PackageManager;
Christopher Tatea732f012017-10-26 17:26:53 -070043import android.content.pm.PackageManagerInternal;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060044import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070045import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070046import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070047import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070048import android.os.BatteryStats;
Christopher Tate7060b042014-06-09 19:50:00 -070049import android.os.Binder;
50import android.os.Handler;
51import android.os.Looper;
52import android.os.Message;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070053import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070054import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080055import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070056import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070057import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070058import android.os.SystemClock;
59import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070060import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070061import android.provider.Settings;
62import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070063import android.util.Slog;
64import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080065import android.util.SparseIntArray;
66import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080067import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080068
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070069import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070070import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070071import com.android.internal.app.procstats.ProcessStats;
Christopher Tatea732f012017-10-26 17:26:53 -070072import com.android.internal.os.BackgroundThread;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070073import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060074import com.android.internal.util.DumpUtils;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080075import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070076import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080077import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080078import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
79import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Christopher Tate2f36fd62016-02-18 18:36:08 -080080import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080081import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070082import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070083import com.android.server.job.controllers.BatteryController;
84import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080085import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070086import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070087import com.android.server.job.controllers.IdleController;
88import com.android.server.job.controllers.JobStatus;
89import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070090import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070091import com.android.server.job.controllers.TimeController;
92
Jeff Sharkey822cbd12016-02-25 11:09:55 -070093import libcore.util.EmptyArray;
94
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070095import java.io.FileDescriptor;
96import java.io.PrintWriter;
97import java.time.Clock;
98import java.util.ArrayList;
99import java.util.Arrays;
100import java.util.Collections;
101import java.util.Comparator;
102import java.util.Iterator;
103import java.util.List;
104
Christopher Tate7060b042014-06-09 19:50:00 -0700105/**
106 * Responsible for taking jobs representing work to be performed by a client app, and determining
107 * based on the criteria specified when that job should be run against the client application's
108 * endpoint.
109 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
110 * about constraints, or the state of active jobs. It receives callbacks from the various
111 * controllers and completed jobs and operates accordingly.
112 *
113 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
114 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
115 * @hide
116 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800117public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700118 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800119 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700120 public static final boolean DEBUG = false;
Christopher Tatea732f012017-10-26 17:26:53 -0700121 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800122
Dianne Hackborn970510b2016-02-24 16:56:42 -0800123 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700124 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800125 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800126 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800127 /** The maximum number of jobs that we allow an unprivileged app to schedule */
128 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700129
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700130 @VisibleForTesting
131 public static Clock sSystemClock = Clock.systemUTC();
132 @VisibleForTesting
133 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
134 @VisibleForTesting
135 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800136
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800137 /** Global local for all job scheduler state. */
138 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700139 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700140 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700141 /** Tracking the standby bucket state of each app */
142 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700143 /** Tracking amount of time each package runs for. */
144 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700145
146 static final int MSG_JOB_EXPIRED = 0;
147 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700148 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000149 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700150
Christopher Tate7060b042014-06-09 19:50:00 -0700151 /**
152 * Track Services that have currently active or pending jobs. The index is provided by
153 * {@link JobStatus#getServiceToken()}
154 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700155 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700156 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700157 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800158 /** Need direct access to this for testing. */
159 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700160 /** Need direct access to this for testing. */
161 StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700162 /** Need directly for sending uid state changes */
163 private BackgroundJobsController mBackgroundJobsController;
Suprabh Shukla106203b2017-11-02 21:23:44 -0700164 private DeviceIdleJobsController mDeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700165 /**
166 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
167 * when ready to execute them.
168 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700169 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700170
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700171 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700172
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700173 final JobHandler mHandler;
174 final JobSchedulerStub mJobSchedulerStub;
175
Christopher Tatea732f012017-10-26 17:26:53 -0700176 PackageManagerInternal mLocalPM;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700177 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800178 DeviceIdleController.LocalService mLocalDeviceIdleController;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700179
180 /**
181 * Set to true once we are allowed to run third party apps.
182 */
183 boolean mReadyToRock;
184
Christopher Tate7060b042014-06-09 19:50:00 -0700185 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800186 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800187 */
188 boolean mReportedActive;
189
190 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800191 * Are we currently in device-wide standby parole?
192 */
193 volatile boolean mInParole;
194
195 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800196 * Current limit on the number of concurrent JobServiceContext entries we want to
197 * keep actively running a job.
198 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700199 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800200
201 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800202 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800203 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800204 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
205
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700206 /**
207 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
208 */
209 final SparseIntArray mBackingUpUids = new SparseIntArray();
210
Christopher Tatea732f012017-10-26 17:26:53 -0700211 /**
212 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
213 * next become runnable. Index into this array is by normalized bucket:
214 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
215 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
216 * and NEVER apps don't get them at all.
217 */
218 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
219 long mHeartbeat = 0;
220 long mLastHeartbeatTime = 0;
221
Dianne Hackborn970510b2016-02-24 16:56:42 -0800222 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
223
224 /**
225 * This array essentially stores the state of mActiveServices array.
226 * The ith index stores the job present on the ith JobServiceContext.
227 * We manipulate this array until we arrive at what jobs should be running on
228 * what JobServiceContext.
229 */
230 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
231 /**
232 * Indicates whether we need to act on this jobContext id
233 */
234 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
235 /**
236 * The uid whose jobs we would like to assign to a context.
237 */
238 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800239
240 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700241 * All times are in milliseconds. These constants are kept synchronized with the system
242 * global Settings. Any access to this class or its fields should be done while
243 * holding the JobSchedulerService.mLock lock.
244 */
245 private final class Constants extends ContentObserver {
246 // Key names stored in the settings value.
247 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
248 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800249 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700250 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700251 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
252 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
253 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
254 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
255 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
256 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
257 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
258 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
259 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
260 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700261 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
262 = "max_standard_reschedule_count";
263 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
264 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
265 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700266 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
267 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
268 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
269 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700270
271 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
272 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800273 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700274 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700275 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
276 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
277 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
278 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
279 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
280 private static final int DEFAULT_FG_JOB_COUNT = 4;
281 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
282 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700283 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700284 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700285 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
286 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
287 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
288 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700289 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000290 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
291 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700292 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700293
294 /**
295 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
296 * early.
297 */
298 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
299 /**
300 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
301 * things early.
302 */
303 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
304 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800305 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
306 * schedule things early.
307 */
308 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
309 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700310 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
311 * schedule things early.
312 */
313 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
314 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700315 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
316 * things early. 1 == Run connectivity jobs as soon as ready.
317 */
318 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
319 /**
320 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
321 * schedule things early.
322 */
323 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
324 /**
325 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
326 * running some work early. This (and thus the other min counts) is now set to 1, to
327 * prevent any batching at this level. Since we now do batching through doze, that is
328 * a much better mechanism.
329 */
330 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
331 /**
332 * This is the job execution factor that is considered to be heavy use of the system.
333 */
334 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
335 /**
336 * This is the job execution factor that is considered to be moderate use of the system.
337 */
338 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
339 /**
340 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
341 */
342 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
343 /**
344 * The maximum number of background jobs we allow when the system is in a normal
345 * memory state.
346 */
347 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
348 /**
349 * The maximum number of background jobs we allow when the system is in a moderate
350 * memory state.
351 */
352 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
353 /**
354 * The maximum number of background jobs we allow when the system is in a low
355 * memory state.
356 */
357 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
358 /**
359 * The maximum number of background jobs we allow when the system is in a critical
360 * memory state.
361 */
362 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700363 /**
364 * The maximum number of times we allow a job to have itself rescheduled before
365 * giving up on it, for standard jobs.
366 */
367 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
368 /**
369 * The maximum number of times we allow a job to have itself rescheduled before
370 * giving up on it, for jobs that are executing work.
371 */
372 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
373 /**
374 * The minimum backoff time to allow for linear backoff.
375 */
376 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
377 /**
378 * The minimum backoff time to allow for exponential backoff.
379 */
380 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700381 /**
382 * How often we recalculate runnability based on apps' standby bucket assignment.
383 * This should be prime relative to common time interval lengths such as a quarter-
384 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
385 */
386 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
387
388 /**
389 * Mapping: standby bucket -> number of heartbeats between each sweep of that
390 * bucket's jobs.
391 *
392 * Bucket assignments as recorded in the JobStatus objects are normalized to be
393 * indices into this array, rather than the raw constants used
394 * by AppIdleHistory.
395 */
396 final int[] STANDBY_BEATS = {
397 0,
398 DEFAULT_STANDBY_WORKING_BEATS,
399 DEFAULT_STANDBY_FREQUENT_BEATS,
400 DEFAULT_STANDBY_RARE_BEATS
401 };
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700402
403 private ContentResolver mResolver;
404 private final KeyValueListParser mParser = new KeyValueListParser(',');
405
406 public Constants(Handler handler) {
407 super(handler);
408 }
409
410 public void start(ContentResolver resolver) {
411 mResolver = resolver;
412 mResolver.registerContentObserver(Settings.Global.getUriFor(
413 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
414 updateConstants();
415 }
416
417 @Override
418 public void onChange(boolean selfChange, Uri uri) {
419 updateConstants();
420 }
421
422 private void updateConstants() {
423 synchronized (mLock) {
424 try {
425 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000426 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700427 } catch (IllegalArgumentException e) {
428 // Failed to parse the settings string, log this and move on
429 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000430 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700431 }
432
433 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
434 DEFAULT_MIN_IDLE_COUNT);
435 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
436 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800437 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
438 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700439 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
440 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700441 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
442 DEFAULT_MIN_CONNECTIVITY_COUNT);
443 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
444 DEFAULT_MIN_CONTENT_COUNT);
445 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
446 DEFAULT_MIN_READY_JOBS_COUNT);
447 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
448 DEFAULT_HEAVY_USE_FACTOR);
449 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
450 DEFAULT_MODERATE_USE_FACTOR);
451 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
452 DEFAULT_FG_JOB_COUNT);
453 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
454 DEFAULT_BG_NORMAL_JOB_COUNT);
455 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
456 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
457 }
458 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
459 DEFAULT_BG_MODERATE_JOB_COUNT);
460 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
461 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
462 }
463 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
464 DEFAULT_BG_LOW_JOB_COUNT);
465 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
466 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
467 }
468 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
469 DEFAULT_BG_CRITICAL_JOB_COUNT);
470 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
471 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
472 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700473 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
474 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
475 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
476 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800477 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700478 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800479 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700480 DEFAULT_MIN_EXP_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800481 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
Christopher Tatea732f012017-10-26 17:26:53 -0700482 DEFAULT_STANDBY_HEARTBEAT_TIME);
483 STANDBY_BEATS[1] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
484 DEFAULT_STANDBY_WORKING_BEATS);
485 STANDBY_BEATS[2] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
486 DEFAULT_STANDBY_FREQUENT_BEATS);
487 STANDBY_BEATS[3] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
488 DEFAULT_STANDBY_RARE_BEATS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700489 }
490 }
491
492 void dump(PrintWriter pw) {
493 pw.println(" Settings:");
494
495 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
496 pw.print(MIN_IDLE_COUNT); pw.println();
497
498 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
499 pw.print(MIN_CHARGING_COUNT); pw.println();
500
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800501 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
502 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
503
Dianne Hackborn532ea262017-03-17 17:50:55 -0700504 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
505 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
506
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700507 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
508 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
509
510 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
511 pw.print(MIN_CONTENT_COUNT); pw.println();
512
513 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
514 pw.print(MIN_READY_JOBS_COUNT); pw.println();
515
516 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
517 pw.print(HEAVY_USE_FACTOR); pw.println();
518
519 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
520 pw.print(MODERATE_USE_FACTOR); pw.println();
521
522 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
523 pw.print(FG_JOB_COUNT); pw.println();
524
525 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
526 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
527
528 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
529 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
530
531 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
532 pw.print(BG_LOW_JOB_COUNT); pw.println();
533
534 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
535 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700536
537 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
538 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
539
540 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
541 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
542
543 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
544 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
545
546 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
547 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Christopher Tatea732f012017-10-26 17:26:53 -0700548
549 pw.print(" "); pw.print(KEY_STANDBY_HEARTBEAT_TIME); pw.print("=");
550 pw.print(STANDBY_HEARTBEAT_TIME); pw.println();
551
552 pw.print(" standby_beats={");
553 pw.print(STANDBY_BEATS[0]);
554 for (int i = 1; i < STANDBY_BEATS.length; i++) {
555 pw.print(", ");
556 pw.print(STANDBY_BEATS[i]);
557 }
558 pw.println('}');
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700559 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800560
561 void dump(ProtoOutputStream proto, long fieldId) {
562 final long token = proto.start(fieldId);
563
564 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
565 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
566 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
567 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
568 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
569 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
570 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
571 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
572 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
573 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
574 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
575 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
576 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
577 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
578 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
579 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
580 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
581 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
582 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
583
584 for (int period : STANDBY_BEATS) {
585 proto.write(ConstantsProto.STANDBY_BEATS, period);
586 }
587
588 proto.end(token);
589 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700590 }
591
592 final Constants mConstants;
593
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700594 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
595 if (o1.enqueueTime < o2.enqueueTime) {
596 return -1;
597 }
598 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
599 };
600
601 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
602 int where = Collections.binarySearch(array, newItem, comparator);
603 if (where < 0) {
604 where = ~where;
605 }
606 array.add(where, newItem);
607 }
608
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700609 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700610 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
611 * still clean up. On reinstall the package will have a new uid.
612 */
613 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
614 @Override
615 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700616 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700617 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700618 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700619 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700620 final String pkgName = getPackageName(intent);
621 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
622
Christopher Tateee7805b2016-07-15 16:56:56 -0700623 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700624 // Purge the app's jobs if the whole package was just disabled. When this is
625 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700626 if (pkgName != null && pkgUid != -1) {
627 final String[] changedComponents = intent.getStringArrayExtra(
628 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
629 if (changedComponents != null) {
630 for (String component : changedComponents) {
631 if (component.equals(pkgName)) {
632 if (DEBUG) {
633 Slog.d(TAG, "Package state change: " + pkgName);
634 }
635 try {
636 final int userId = UserHandle.getUserId(pkgUid);
637 IPackageManager pm = AppGlobals.getPackageManager();
638 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
639 if (state == COMPONENT_ENABLED_STATE_DISABLED
640 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
641 if (DEBUG) {
642 Slog.d(TAG, "Removing jobs for package " + pkgName
643 + " in user " + userId);
644 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700645 cancelJobsForPackageAndUid(pkgName, pkgUid,
646 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700647 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700648 } catch (RemoteException|IllegalArgumentException e) {
649 /*
650 * IllegalArgumentException means that the package doesn't exist.
651 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
652 * behind outright uninstall, so by the time we try to act it's gone.
653 * We don't need to act on this PACKAGE_CHANGED when this happens;
654 * we'll get a PACKAGE_REMOVED later and clean up then.
655 *
656 * RemoteException can't actually happen; the package manager is
657 * running in this same process.
658 */
659 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700660 break;
661 }
662 }
663 }
664 } else {
665 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
666 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700667 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700668 // If this is an outright uninstall rather than the first half of an
669 // app update sequence, cancel the jobs associated with the app.
670 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
671 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
672 if (DEBUG) {
673 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
674 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700675 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700676 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700677 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700678 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
679 if (DEBUG) {
680 Slog.d(TAG, "Removing jobs for user: " + userId);
681 }
682 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700683 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
684 // Has this package scheduled any jobs, such that we will take action
685 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700686 if (pkgUid != -1) {
687 List<JobStatus> jobsForUid;
688 synchronized (mLock) {
689 jobsForUid = mJobs.getJobsByUid(pkgUid);
690 }
691 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
692 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
693 if (DEBUG) {
694 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
695 + pkgUid + " has jobs");
696 }
697 setResultCode(Activity.RESULT_OK);
698 break;
699 }
700 }
701 }
702 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
703 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700704 if (pkgUid != -1) {
705 if (DEBUG) {
706 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
707 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700708 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700709 }
Christopher Tate7060b042014-06-09 19:50:00 -0700710 }
711 }
712 };
713
Christopher Tateb5c07882016-05-26 17:11:09 -0700714 private String getPackageName(Intent intent) {
715 Uri uri = intent.getData();
716 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
717 return pkg;
718 }
719
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700720 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700721 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800722 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700723 }
724
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700725 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800726 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800727 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700728 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800729 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700730 synchronized (mLock) {
731 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
732 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700733 }
734
735 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla106203b2017-11-02 21:23:44 -0700736 synchronized (mLock) {
737 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
738 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700739 }
740
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700741 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800742 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700743 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800744 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700745 synchronized (mLock) {
746 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
747 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700748 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700749
750 @Override public void onUidCachedChanged(int uid, boolean cached) {
751 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700752 };
753
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800754 public Object getLock() {
755 return mLock;
756 }
757
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700758 public JobStore getJobStore() {
759 return mJobs;
760 }
761
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700762 @Override
763 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700764 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
765 // Let's kick any outstanding jobs for this user.
766 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
767 }
768
769 @Override
770 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700771 // Let's kick any outstanding jobs for this user.
772 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
773 }
774
775 @Override
776 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700777 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700778 }
779
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700780 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
781 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700782 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800783 if (ActivityManager.getService().isAppStartModeDisabled(uId,
784 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700785 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
786 + " -- package not allowed to start");
787 return JobScheduler.RESULT_FAILURE;
788 }
789 } catch (RemoteException e) {
790 }
Christopher Tatea732f012017-10-26 17:26:53 -0700791
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800792 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700793 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
794
795 if (work != null && toCancel != null) {
796 // Fast path: we are adding work to an existing job, and the JobInfo is not
797 // changing. We can just directly enqueue this work in to the job.
798 if (toCancel.getJob().equals(job)) {
Dianne Hackborn342e6032017-04-13 18:04:31 -0700799 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700800 return JobScheduler.RESULT_SUCCESS;
801 }
802 }
803
804 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
805 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800806 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800807 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800808 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
809 Slog.w(TAG, "Too many jobs for uid " + uId);
810 throw new IllegalStateException("Apps may not schedule more than "
811 + MAX_JOBS_PER_APP + " distinct jobs");
812 }
813 }
814
Dianne Hackborna47223f2017-03-30 13:49:13 -0700815 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700816 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700817
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700818 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700819 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700820 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700821 if (work != null) {
822 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700823 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700824 }
825 startTrackingJobLocked(jobStatus, toCancel);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700826
827 // If the job is immediately ready to run, then we can just immediately
828 // put it in the pending list and try to schedule it. This is especially
829 // important for jobs with a 0 deadline constraint, since they will happen a fair
830 // amount, we want to handle them as quickly as possible, and semantically we want to
831 // make sure we have started holding the wake lock for the job before returning to
832 // the caller.
833 // If the job is not yet ready to run, there is nothing more to do -- we are
834 // now just waiting for one of its controllers to change state and schedule
835 // the job appropriately.
836 if (isReadyToBeExecutedLocked(jobStatus)) {
837 // This is a new job, we can just immediately put it on the pending
838 // list and try to run it.
839 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700840 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700841 maybeRunPendingJobsLocked();
842 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800843 }
Christopher Tate7060b042014-06-09 19:50:00 -0700844 return JobScheduler.RESULT_SUCCESS;
845 }
846
847 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800848 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800849 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
850 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
851 for (int i = jobs.size() - 1; i >= 0; i--) {
852 JobStatus job = jobs.get(i);
853 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700854 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800855 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700856 }
Christopher Tate7060b042014-06-09 19:50:00 -0700857 }
858
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600859 public JobInfo getPendingJob(int uid, int jobId) {
860 synchronized (mLock) {
861 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
862 for (int i = jobs.size() - 1; i >= 0; i--) {
863 JobStatus job = jobs.get(i);
864 if (job.getJobId() == jobId) {
865 return job.getJob();
866 }
867 }
868 return null;
869 }
870 }
871
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700872 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800873 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700874 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
875 for (int i=0; i<jobsForUser.size(); i++) {
876 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700877 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700878 }
Christopher Tate7060b042014-06-09 19:50:00 -0700879 }
880 }
881
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700882 private void cancelJobsForNonExistentUsers() {
883 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
884 synchronized (mLock) {
885 mJobs.removeJobsOfNonUsers(umi.getUserIds());
886 }
887 }
888
Makoto Onukie7b96182017-08-30 14:53:16 -0700889 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
890 if ("android".equals(pkgName)) {
891 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
892 return;
893 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700894 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700895 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
896 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
897 final JobStatus job = jobsForUid.get(i);
898 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700899 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700900 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700901 }
902 }
903 }
904
Christopher Tate7060b042014-06-09 19:50:00 -0700905 /**
906 * Entry point from client to cancel all jobs originating from their uid.
907 * This will remove the job from the master list, and cancel the job if it was staged for
908 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700909 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800910 *
Christopher Tate7060b042014-06-09 19:50:00 -0700911 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700912 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700913 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700914 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700915 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700916 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700917
918 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800919 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700920 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
921 for (int i=0; i<jobsForUid.size(); i++) {
922 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700923 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700924 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700925 }
Christopher Tate7060b042014-06-09 19:50:00 -0700926 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700927 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700928 }
929
930 /**
931 * Entry point from client to cancel the job corresponding to the jobId provided.
932 * This will remove the job from the master list, and cancel the job if it was staged for
933 * execution or being executed.
934 * @param uid Uid of the calling client.
935 * @param jobId Id of the job, provided at schedule-time.
936 */
Makoto Onukid2bfec62018-01-12 13:58:01 -0800937 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -0700938 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800939 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700940 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700941 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -0800942 cancelJobImplLocked(toCancel, null,
943 "cancel() called by app, callingUid=" + callingUid
944 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700945 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700946 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -0700947 }
948 }
949
Dianne Hackborn729a3282017-06-09 16:06:01 -0700950 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700951 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
952 cancelled.unprepareLocked(ActivityManager.getService());
953 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
954 // Remove from pending queue.
955 if (mPendingJobs.remove(cancelled)) {
956 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -0700957 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700958 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -0700959 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700960 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -0700961 }
962
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800963 void updateUidState(int uid, int procState) {
964 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800965 if (procState == ActivityManager.PROCESS_STATE_TOP) {
966 // Only use this if we are exactly the top app. All others can live
967 // with just the foreground priority. This means that persistent processes
968 // can never be the top app priority... that is fine.
969 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -0800970 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800971 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800972 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -0800973 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800974 }
975 }
976 }
977
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700978 @Override
979 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800980 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700981 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -0600982 // When becoming idle, make sure no jobs are actively running,
983 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700984 for (int i=0; i<mActiveServices.size(); i++) {
985 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700986 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -0600987 if (executing != null
988 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700989 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
990 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700991 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700992 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700993 } else {
994 // When coming out of idle, allow thing to start back up.
995 if (mReadyToRock) {
996 if (mLocalDeviceIdleController != null) {
997 if (!mReportedActive) {
998 mReportedActive = true;
999 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001000 }
1001 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001002 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001003 }
1004 }
1005 }
1006 }
1007
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001008 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001009 // active is true if pending queue contains jobs OR some job is running.
1010 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001011 if (mPendingJobs.size() <= 0) {
1012 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001013 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001014 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001015 if (job != null
1016 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
1017 && !job.dozeWhitelisted) {
1018 // We will report active if we have a job running and it is not an exception
1019 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001020 active = true;
1021 break;
1022 }
1023 }
1024 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001025
1026 if (mReportedActive != active) {
1027 mReportedActive = active;
1028 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001029 mLocalDeviceIdleController.setJobsActive(active);
1030 }
1031 }
1032 }
1033
Christopher Tate7060b042014-06-09 19:50:00 -07001034 /**
1035 * Initializes the system service.
1036 * <p>
1037 * Subclasses must define a single argument constructor that accepts the context
1038 * and passes it to super.
1039 * </p>
1040 *
1041 * @param context The system server context.
1042 */
1043 public JobSchedulerService(Context context) {
1044 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001045
1046 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
1047
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001048 mHandler = new JobHandler(context.getMainLooper());
1049 mConstants = new Constants(mHandler);
1050 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001051
1052 // Set up the app standby bucketing tracker
1053 UsageStatsManagerInternal usageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1054 mStandbyTracker = new StandbyTracker(usageStats);
1055 usageStats.addAppIdleStateChangeListener(mStandbyTracker);
1056
1057 // The job store needs to call back
1058 publishLocalService(JobSchedulerInternal.class, new LocalService());
1059
1060 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001061 mJobs = JobStore.initAndGet(this);
1062
Christopher Tate7060b042014-06-09 19:50:00 -07001063 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001064 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -07001065 mControllers.add(ConnectivityController.get(this));
1066 mControllers.add(TimeController.get(this));
1067 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001068 mBatteryController = BatteryController.get(this);
1069 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001070 mStorageController = StorageController.get(this);
1071 mControllers.add(mStorageController);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001072 mControllers.add(BackgroundJobsController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -08001073 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001074 mControllers.add(ContentObserverController.get(this));
Suprabh Shukla106203b2017-11-02 21:23:44 -07001075 mDeviceIdleJobsController = DeviceIdleJobsController.get(this);
1076 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001077
1078 // If the job store determined that it can't yet reschedule persisted jobs,
1079 // we need to start watching the clock.
1080 if (!mJobs.jobTimesInflatedValid()) {
1081 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1082 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1083 }
Christopher Tate7060b042014-06-09 19:50:00 -07001084 }
1085
Christopher Tate616541d2017-07-26 14:27:38 -07001086 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1087 @Override
1088 public void onReceive(Context context, Intent intent) {
1089 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1090 // When we reach clock sanity, recalculate the temporal windows
1091 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001092 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001093 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1094
1095 // We've done our job now, so stop watching the time.
1096 context.unregisterReceiver(this);
1097
1098 // And kick off the work to update the affected jobs, using a secondary
1099 // thread instead of chugging away here on the main looper thread.
1100 FgThread.getHandler().post(mJobTimeUpdater);
1101 }
1102 }
1103 }
1104 };
1105
1106 private final Runnable mJobTimeUpdater = () -> {
1107 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1108 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1109 synchronized (mLock) {
1110 // Note: we intentionally both look up the existing affected jobs and replace them
1111 // with recalculated ones inside the same lock lifetime.
1112 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1113
1114 // Now, at each position [i], we have both the existing JobStatus
1115 // and the one that replaces it.
1116 final int N = toAdd.size();
1117 for (int i = 0; i < N; i++) {
1118 final JobStatus oldJob = toRemove.get(i);
1119 final JobStatus newJob = toAdd.get(i);
1120 if (DEBUG) {
1121 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1122 }
1123 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1124 }
1125 }
1126 };
1127
Christopher Tate7060b042014-06-09 19:50:00 -07001128 @Override
1129 public void onStart() {
1130 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1131 }
1132
1133 @Override
1134 public void onBootPhase(int phase) {
1135 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001136 mConstants.start(getContext().getContentResolver());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001137 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001138 final IntentFilter filter = new IntentFilter();
1139 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1140 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001141 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1142 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001143 filter.addDataScheme("package");
1144 getContext().registerReceiverAsUser(
1145 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1146 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1147 getContext().registerReceiverAsUser(
1148 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001149 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001150 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001151 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001152 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1153 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001154 } catch (RemoteException e) {
1155 // ignored; both services live in system_server
1156 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001157 // Remove any jobs that are not associated with any of the current users.
1158 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001159 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001160 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001161 // Let's go!
1162 mReadyToRock = true;
1163 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1164 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001165 mLocalDeviceIdleController
1166 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001167 // Create the "runners".
1168 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1169 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001170 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001171 getContext().getMainLooper()));
1172 }
1173 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001174 mJobs.forEachJob(new JobStatusFunctor() {
1175 @Override
1176 public void process(JobStatus job) {
1177 for (int controller = 0; controller < mControllers.size(); controller++) {
1178 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001179 sc.maybeStartTrackingJobLocked(job, null);
1180 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001181 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001182 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001183 // GO GO GO!
1184 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1185 }
Christopher Tate7060b042014-06-09 19:50:00 -07001186 }
1187 }
1188
1189 /**
1190 * Called when we have a job status object that we need to insert in our
1191 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1192 * about.
1193 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001194 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1195 if (!jobStatus.isPreparedLocked()) {
1196 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1197 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001198 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001199 final boolean update = mJobs.add(jobStatus);
1200 if (mReadyToRock) {
1201 for (int i = 0; i < mControllers.size(); i++) {
1202 StateController controller = mControllers.get(i);
1203 if (update) {
1204 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001205 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001206 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001207 }
Christopher Tate7060b042014-06-09 19:50:00 -07001208 }
1209 }
1210
1211 /**
1212 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1213 * object removed.
1214 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001215 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001216 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001217 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001218 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001219
1220 // Remove from store as well as controllers.
1221 final boolean removed = mJobs.remove(jobStatus, writeBack);
1222 if (removed && mReadyToRock) {
1223 for (int i=0; i<mControllers.size(); i++) {
1224 StateController controller = mControllers.get(i);
1225 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001226 }
1227 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001228 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001229 }
1230
Dianne Hackborn729a3282017-06-09 16:06:01 -07001231 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001232 for (int i=0; i<mActiveServices.size(); i++) {
1233 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001234 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001235 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001236 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001237 return true;
1238 }
1239 }
1240 return false;
1241 }
1242
1243 /**
1244 * @param job JobStatus we are querying against.
1245 * @return Whether or not the job represented by the status object is currently being run or
1246 * is pending.
1247 */
1248 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001249 for (int i=0; i<mActiveServices.size(); i++) {
1250 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001251 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001252 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1253 return true;
1254 }
1255 }
1256 return false;
1257 }
1258
Dianne Hackborn807de782016-04-07 17:54:41 -07001259 void noteJobsPending(List<JobStatus> jobs) {
1260 for (int i = jobs.size() - 1; i >= 0; i--) {
1261 JobStatus job = jobs.get(i);
1262 mJobPackageTracker.notePending(job);
1263 }
1264 }
1265
1266 void noteJobsNonpending(List<JobStatus> jobs) {
1267 for (int i = jobs.size() - 1; i >= 0; i--) {
1268 JobStatus job = jobs.get(i);
1269 mJobPackageTracker.noteNonpending(job);
1270 }
1271 }
1272
Christopher Tate7060b042014-06-09 19:50:00 -07001273 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001274 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1275 * specify an override deadline on a failed job (the failed job will run even though it's not
1276 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1277 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1278 *
Christopher Tate7060b042014-06-09 19:50:00 -07001279 * @param failureToReschedule Provided job status that we will reschedule.
1280 * @return A newly instantiated JobStatus with the same constraints as the last job except
1281 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001282 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001283 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001284 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001285 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001286 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001287 final JobInfo job = failureToReschedule.getJob();
1288
1289 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001290 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1291 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001292
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001293 if (failureToReschedule.hasWorkLocked()) {
1294 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1295 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1296 + backoffAttempts + " > work limit "
1297 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1298 return null;
1299 }
1300 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1301 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1302 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1303 return null;
1304 }
1305
Christopher Tate7060b042014-06-09 19:50:00 -07001306 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001307 case JobInfo.BACKOFF_POLICY_LINEAR: {
1308 long backoff = initialBackoffMillis;
1309 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1310 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1311 }
1312 delayMillis = backoff * backoffAttempts;
1313 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001314 default:
1315 if (DEBUG) {
1316 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1317 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001318 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1319 long backoff = initialBackoffMillis;
1320 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1321 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1322 }
1323 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1324 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001325 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001326 delayMillis =
1327 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001328 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1329 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001330 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001331 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001332 for (int ic=0; ic<mControllers.size(); ic++) {
1333 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001334 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001335 }
1336 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001337 }
1338
1339 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001340 * Called after a periodic has executed so we can reschedule it. We take the last execution
1341 * time of the job to be the time of completion (i.e. the time at which this function is
1342 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001343 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001344 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1345 * to underscheduling at least, rather than if we had taken the last execution time to be the
1346 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001347 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1348 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001349 * @return A new job representing the execution criteria for this instantiation of the
1350 * recurring job.
1351 */
1352 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001353 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001354 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001355 long runEarly = 0L;
1356
1357 // If this periodic was rescheduled it won't have a deadline.
1358 if (periodicToReschedule.hasDeadlineConstraint()) {
1359 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1360 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001361 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001362 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001363 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1364 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001365
1366 if (DEBUG) {
1367 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1368 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1369 }
Christopher Tatea732f012017-10-26 17:26:53 -07001370 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1371 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1372 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001373 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001374 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001375 }
1376
1377 // JobCompletedListener implementations.
1378
1379 /**
1380 * A job just finished executing. We fetch the
1381 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1382 * whether we want to reschedule we readd it to the controllers.
1383 * @param jobStatus Completed job.
1384 * @param needsReschedule Whether the implementing class should reschedule this job.
1385 */
1386 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001387 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001388 if (DEBUG) {
1389 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1390 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001391
1392 // If the job wants to be rescheduled, we first need to make the next upcoming
1393 // job so we can transfer any appropriate state over from the previous job when
1394 // we stop it.
1395 final JobStatus rescheduledJob = needsReschedule
1396 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1397
Shreyas Basarge73f10252016-02-11 17:06:13 +00001398 // Do not write back immediately if this is a periodic job. The job may get lost if system
1399 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001400 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001401 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001402 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001403 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001404 // We still want to check for jobs to execute, because this job may have
1405 // scheduled a new job under the same job id, and now we can run it.
1406 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001407 return;
1408 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001409
1410 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001411 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001412 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001413 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001414 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001415 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001416 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001417 } else if (jobStatus.getJob().isPeriodic()) {
1418 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001419 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001420 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001421 } catch (SecurityException e) {
1422 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1423 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001424 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001425 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001426 jobStatus.unprepareLocked(ActivityManager.getService());
1427 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001428 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001429 }
1430
1431 // StateChangedListener implementations.
1432
1433 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001434 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1435 * some controller's state has changed, so as to run through the list of jobs and start/stop
1436 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001437 */
1438 @Override
1439 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001440 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001441 }
1442
1443 @Override
1444 public void onRunJobNow(JobStatus jobStatus) {
1445 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1446 }
1447
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001448 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001449
1450 public JobHandler(Looper looper) {
1451 super(looper);
1452 }
1453
1454 @Override
1455 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001456 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001457 if (!mReadyToRock) {
1458 return;
1459 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001460 switch (message.what) {
1461 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001462 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001463 // runNow can be null, which is a controller's way of indicating that its
1464 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001465 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001466 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001467 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001468 } else {
1469 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001470 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001471 } break;
1472 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001473 if (mReportedActive) {
1474 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001475 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001476 } else {
1477 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001478 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001479 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001480 break;
1481 case MSG_CHECK_JOB_GREEDY:
1482 queueReadyJobsForExecutionLocked();
1483 break;
1484 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001485 cancelJobImplLocked((JobStatus) message.obj, null,
1486 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001487 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001488 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001489 maybeRunPendingJobsLocked();
1490 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1491 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001492 }
1493 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001494 }
Christopher Tate7060b042014-06-09 19:50:00 -07001495
Dianne Hackborn6d068262017-05-16 13:14:37 -07001496 private void stopNonReadyActiveJobsLocked() {
1497 for (int i=0; i<mActiveServices.size(); i++) {
1498 JobServiceContext serviceContext = mActiveServices.get(i);
1499 final JobStatus running = serviceContext.getRunningJobLocked();
1500 if (running != null && !running.isReady()) {
1501 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001502 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1503 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001504 }
1505 }
1506 }
1507
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001508 /**
1509 * Run through list of jobs and execute all possible - at least one is expired so we do
1510 * as many as we can.
1511 */
1512 private void queueReadyJobsForExecutionLocked() {
1513 if (DEBUG) {
1514 Slog.d(TAG, "queuing all ready jobs for execution:");
1515 }
1516 noteJobsNonpending(mPendingJobs);
1517 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001518 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001519 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001520 mJobs.forEachJob(mReadyQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001521 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001522 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001523
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001524 if (DEBUG) {
1525 final int queuedJobs = mPendingJobs.size();
1526 if (queuedJobs == 0) {
1527 Slog.d(TAG, "No jobs pending.");
1528 } else {
1529 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001530 }
1531 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001532 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001533
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001534 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1535 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001536
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001537 @Override
1538 public void process(JobStatus job) {
1539 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001540 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001541 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001542 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001543 if (newReadyJobs == null) {
1544 newReadyJobs = new ArrayList<JobStatus>();
1545 }
1546 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001547 }
1548 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001549
1550 public void postProcess() {
1551 if (newReadyJobs != null) {
1552 noteJobsPending(newReadyJobs);
1553 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001554 if (mPendingJobs.size() > 1) {
1555 mPendingJobs.sort(mEnqueueTimeComparator);
1556 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001557 }
1558 newReadyJobs = null;
1559 }
1560 }
1561 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1562
1563 /**
1564 * The state of at least one job has changed. Here is where we could enforce various
1565 * policies on when we want to execute jobs.
1566 * Right now the policy is such:
1567 * If >1 of the ready jobs is idle mode we send all of them off
1568 * if more than 2 network connectivity jobs are ready we send them all off.
1569 * If more than 4 jobs total are ready we send them all off.
1570 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1571 */
1572 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1573 int chargingCount;
1574 int batteryNotLowCount;
1575 int storageNotLowCount;
1576 int idleCount;
1577 int backoffCount;
1578 int connectivityCount;
1579 int contentCount;
1580 List<JobStatus> runnableJobs;
1581
1582 public MaybeReadyJobQueueFunctor() {
1583 reset();
1584 }
1585
1586 // Functor method invoked for each job via JobStore.forEachJob()
1587 @Override
1588 public void process(JobStatus job) {
1589 if (isReadyToBeExecutedLocked(job)) {
1590 try {
1591 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1592 job.getJob().getService().getPackageName())) {
1593 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1594 + job.getJob().toString() + " -- package not allowed to start");
1595 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1596 return;
1597 }
1598 } catch (RemoteException e) {
1599 }
1600 if (job.getNumFailures() > 0) {
1601 backoffCount++;
1602 }
1603 if (job.hasIdleConstraint()) {
1604 idleCount++;
1605 }
1606 if (job.hasConnectivityConstraint()) {
1607 connectivityCount++;
1608 }
1609 if (job.hasChargingConstraint()) {
1610 chargingCount++;
1611 }
1612 if (job.hasBatteryNotLowConstraint()) {
1613 batteryNotLowCount++;
1614 }
1615 if (job.hasStorageNotLowConstraint()) {
1616 storageNotLowCount++;
1617 }
1618 if (job.hasContentTriggerConstraint()) {
1619 contentCount++;
1620 }
1621 if (runnableJobs == null) {
1622 runnableJobs = new ArrayList<>();
1623 }
1624 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001625 }
1626 }
1627
1628 public void postProcess() {
1629 if (backoffCount > 0 ||
1630 idleCount >= mConstants.MIN_IDLE_COUNT ||
1631 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1632 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1633 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1634 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1635 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1636 (runnableJobs != null
1637 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1638 if (DEBUG) {
1639 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1640 }
1641 noteJobsPending(runnableJobs);
1642 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001643 if (mPendingJobs.size() > 1) {
1644 mPendingJobs.sort(mEnqueueTimeComparator);
1645 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001646 } else {
1647 if (DEBUG) {
1648 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1649 }
1650 }
1651
1652 // Be ready for next time
1653 reset();
1654 }
1655
1656 private void reset() {
1657 chargingCount = 0;
1658 idleCount = 0;
1659 backoffCount = 0;
1660 connectivityCount = 0;
1661 batteryNotLowCount = 0;
1662 storageNotLowCount = 0;
1663 contentCount = 0;
1664 runnableJobs = null;
1665 }
1666 }
1667 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1668
1669 private void maybeQueueReadyJobsForExecutionLocked() {
1670 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1671
1672 noteJobsNonpending(mPendingJobs);
1673 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001674 stopNonReadyActiveJobsLocked();
Christopher Tatea732f012017-10-26 17:26:53 -07001675 boolean updated = updateStandbyHeartbeatLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001676 mJobs.forEachJob(mMaybeQueueFunctor);
Christopher Tatea732f012017-10-26 17:26:53 -07001677 if (updated) updateNextStandbyHeartbeatsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001678 mMaybeQueueFunctor.postProcess();
1679 }
1680
Christopher Tatea732f012017-10-26 17:26:53 -07001681 private boolean updateStandbyHeartbeatLocked() {
1682 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1683 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1684 if (beatsElapsed > 0) {
1685 mHeartbeat += beatsElapsed;
1686 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1687 if (DEBUG_STANDBY) {
1688 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed + " to " + mHeartbeat);
1689 }
1690 return true;
1691 }
1692 return false;
1693 }
1694
1695 private void updateNextStandbyHeartbeatsLocked() {
1696 // don't update ACTIVE or NEVER bucket milestones
1697 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
1698 while (mHeartbeat >= mNextBucketHeartbeat[i]) {
1699 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1700 }
1701 if (DEBUG_STANDBY) {
1702 Slog.v(TAG, " Bucket " + i + " next heartbeat " + mNextBucketHeartbeat[i]);
1703 }
1704 }
1705 }
1706
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001707 /**
1708 * Criteria for moving a job into the pending queue:
1709 * - It's ready.
1710 * - It's not pending.
1711 * - It's not already running on a JSC.
1712 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001713 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001714 * - The component is enabled and runnable.
1715 */
1716 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001717 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001718
1719 if (DEBUG) {
1720 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1721 + " ready=" + jobReady);
1722 }
1723
1724 // This is a condition that is very likely to be false (most jobs that are
1725 // scheduled are sitting there, not ready yet) and very cheap to check (just
1726 // a few conditions on data in JobStatus).
1727 if (!jobReady) {
1728 return false;
1729 }
1730
1731 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001732
1733 final int userId = job.getUserId();
1734 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1735
1736 if (DEBUG) {
1737 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001738 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001739 }
1740
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001741 // These are also fairly cheap to check, though they typically will not
1742 // be conditions we fail.
1743 if (!jobExists || !userStarted) {
1744 return false;
1745 }
1746
1747 final boolean jobPending = mPendingJobs.contains(job);
1748 final boolean jobActive = isCurrentlyActiveLocked(job);
1749
1750 if (DEBUG) {
1751 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1752 + " pending=" + jobPending + " active=" + jobActive);
1753 }
1754
1755 // These can be a little more expensive (especially jobActive, since we need to
1756 // go through the array of all potentially active jobs), so we are doing them
1757 // later... but still before checking with the package manager!
1758 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001759 return false;
1760 }
1761
Christopher Tatea732f012017-10-26 17:26:53 -07001762 // If the app is in a non-active standby bucket, make sure we've waited
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001763 // an appropriate amount of time since the last invocation. During device-
1764 // wide parole, standby bucketing is ignored.
1765 if (!mInParole) {
1766 final int bucket = job.getStandbyBucket();
1767 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
1768 // Only skip this job if it's still waiting for the end of its (initial) nominal
1769 // bucket interval. Once it's waited that long, we let it go ahead and clear.
1770 // The final (NEVER) bucket is special; we never age those apps' jobs into
1771 // runnability.
1772 if (bucket >= mConstants.STANDBY_BEATS.length
1773 || (mHeartbeat < job.getBaseHeartbeat() + mConstants.STANDBY_BEATS[bucket])) {
1774 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
1775 if (job.getWhenStandbyDeferred() == 0) {
1776 if (DEBUG_STANDBY) {
1777 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
1778 + mNextBucketHeartbeat[job.getStandbyBucket()] + " for " + job);
1779 }
1780 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tate0c4d7682017-12-06 15:10:22 -08001781 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001782 return false;
1783 } else {
1784 if (DEBUG_STANDBY) {
1785 Slog.v(TAG, "Bucket deferred job aged into runnability at "
1786 + mHeartbeat + " : " + job);
1787 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08001788 }
Christopher Tatea732f012017-10-26 17:26:53 -07001789 }
Christopher Tatea732f012017-10-26 17:26:53 -07001790 }
1791
1792 // The expensive check last: validate that the defined package+service is
1793 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001794 final boolean componentPresent;
1795 try {
1796 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1797 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1798 userId) != null);
1799 } catch (RemoteException e) {
1800 throw e.rethrowAsRuntimeException();
1801 }
1802
1803 if (DEBUG) {
1804 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1805 + " componentPresent=" + componentPresent);
1806 }
1807
1808 // Everything else checked out so far, so this is the final yes/no check
1809 return componentPresent;
1810 }
1811
1812 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001813 * Reconcile jobs in the pending queue against available execution contexts.
1814 * A controller can force a job into the pending queue even if it's already running, but
1815 * here is where we decide whether to actually execute it.
1816 */
1817 private void maybeRunPendingJobsLocked() {
1818 if (DEBUG) {
1819 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1820 }
1821 assignJobsToContextsLocked();
1822 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001823 }
1824
Dianne Hackborn807de782016-04-07 17:54:41 -07001825 private int adjustJobPriority(int curPriority, JobStatus job) {
1826 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1827 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001828 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001829 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001830 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001831 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1832 }
1833 }
1834 return curPriority;
1835 }
1836
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001837 private int evaluateJobPriorityLocked(JobStatus job) {
1838 int priority = job.getPriority();
1839 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001840 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001841 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001842 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1843 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001844 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001845 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001846 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001847 }
1848
Christopher Tate7060b042014-06-09 19:50:00 -07001849 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001850 * Takes jobs from pending queue and runs them on available contexts.
1851 * If no contexts are available, preempts lower priority jobs to
1852 * run higher priority ones.
1853 * Lock on mJobs before calling this function.
1854 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001855 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001856 if (DEBUG) {
1857 Slog.d(TAG, printPendingQueue());
1858 }
1859
Dianne Hackborn970510b2016-02-24 16:56:42 -08001860 int memLevel;
1861 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001862 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001863 } catch (RemoteException e) {
1864 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1865 }
1866 switch (memLevel) {
1867 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001868 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001869 break;
1870 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001871 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001872 break;
1873 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001874 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001875 break;
1876 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001877 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001878 break;
1879 }
1880
1881 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1882 boolean[] act = mTmpAssignAct;
1883 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
1884 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001885 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001886 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
1887 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001888 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001889 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001890 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001891 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
1892 numForeground++;
1893 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001894 }
1895 act[i] = false;
1896 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001897 }
1898 if (DEBUG) {
1899 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
1900 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001901 for (int i=0; i<mPendingJobs.size(); i++) {
1902 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001903
1904 // If job is already running, go to next job.
1905 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
1906 if (jobRunningContext != -1) {
1907 continue;
1908 }
1909
Dianne Hackborn970510b2016-02-24 16:56:42 -08001910 final int priority = evaluateJobPriorityLocked(nextPending);
1911 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001912
Shreyas Basarge5db09082016-01-07 13:38:29 +00001913 // Find a context for nextPending. The context should be available OR
1914 // it should have lowest priority among all running jobs
1915 // (sharing the same Uid as nextPending)
1916 int minPriority = Integer.MAX_VALUE;
1917 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001918 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
1919 JobStatus job = contextIdToJobMap[j];
1920 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00001921 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001922 if ((numActive < mMaxActiveJobs ||
1923 (priority >= JobInfo.PRIORITY_TOP_APP &&
1924 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08001925 (preferredUid == nextPending.getUid() ||
1926 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
1927 // This slot is free, and we haven't yet hit the limit on
1928 // concurrent jobs... we can just throw the job in to here.
1929 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001930 break;
1931 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00001932 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08001933 // the context has a preferred Uid or we have reached the limit on
1934 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00001935 continue;
1936 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001937 if (job.getUid() != nextPending.getUid()) {
1938 continue;
1939 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001940 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001941 continue;
1942 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001943 if (minPriority > nextPending.lastEvaluatedPriority) {
1944 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001945 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00001946 }
1947 }
1948 if (minPriorityContextId != -1) {
1949 contextIdToJobMap[minPriorityContextId] = nextPending;
1950 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001951 numActive++;
1952 if (priority >= JobInfo.PRIORITY_TOP_APP) {
1953 numForeground++;
1954 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001955 }
1956 }
1957 if (DEBUG) {
1958 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
1959 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001960 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08001961 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001962 boolean preservePreferredUid = false;
1963 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001964 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001965 if (js != null) {
1966 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001967 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00001968 }
1969 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001970 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00001971 preservePreferredUid = true;
1972 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001973 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00001974 if (DEBUG) {
1975 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001976 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001977 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001978 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001979 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001980 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001981 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
1982 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00001983 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001984 if (mPendingJobs.remove(pendingJob)) {
1985 mJobPackageTracker.noteNonpending(pendingJob);
1986 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00001987 }
1988 }
1989 if (!preservePreferredUid) {
1990 mActiveServices.get(i).clearPreferredUid();
1991 }
1992 }
1993 }
1994
1995 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
1996 for (int i=0; i<map.length; i++) {
1997 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
1998 return i;
1999 }
2000 }
2001 return -1;
2002 }
2003
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002004 final class LocalService implements JobSchedulerInternal {
2005
2006 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002007 * The current bucket heartbeat ordinal
2008 */
2009 public long currentHeartbeat() {
2010 return getCurrentHeartbeat();
2011 }
2012
2013 /**
2014 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2015 */
2016 public long nextHeartbeatForBucket(int bucket) {
2017 synchronized (mLock) {
2018 return mNextBucketHeartbeat[bucket];
2019 }
2020 }
2021
2022 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002023 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2024 * jobs are always considered pending.
2025 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002026 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002027 public List<JobInfo> getSystemScheduledPendingJobs() {
2028 synchronized (mLock) {
2029 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
2030 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
2031 @Override
2032 public void process(JobStatus job) {
2033 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2034 pendingJobs.add(job.getJob());
2035 }
2036 }
2037 });
2038 return pendingJobs;
2039 }
2040 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002041
2042 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002043 public void cancelJobsForUid(int uid, String reason) {
2044 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2045 }
2046
2047 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002048 public void addBackingUpUid(int uid) {
2049 synchronized (mLock) {
2050 // No need to actually do anything here, since for a full backup the
2051 // activity manager will kill the process which will kill the job (and
2052 // cause it to restart, but now it can't run).
2053 mBackingUpUids.put(uid, uid);
2054 }
2055 }
2056
2057 @Override
2058 public void removeBackingUpUid(int uid) {
2059 synchronized (mLock) {
2060 mBackingUpUids.delete(uid);
2061 // If there are any jobs for this uid, we need to rebuild the pending list
2062 // in case they are now ready to run.
2063 if (mJobs.countJobsForUid(uid) > 0) {
2064 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2065 }
2066 }
2067 }
2068
2069 @Override
2070 public void clearAllBackingUpUids() {
2071 synchronized (mLock) {
2072 if (mBackingUpUids.size() > 0) {
2073 mBackingUpUids.clear();
2074 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2075 }
2076 }
2077 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002078
2079 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002080 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002081 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002082 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002083 }
2084 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002085 }
2086
Shreyas Basarge5db09082016-01-07 13:38:29 +00002087 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002088 * Tracking of app assignments to standby buckets
2089 */
2090 final class StandbyTracker extends AppIdleStateChangeListener {
2091 final UsageStatsManagerInternal mUsageStats;
2092
2093 StandbyTracker(UsageStatsManagerInternal usageStats) {
2094 mUsageStats = usageStats;
2095 }
2096
2097 // AppIdleStateChangeListener interface for live updates
2098
2099 @Override
2100 public void onAppIdleStateChanged(final String packageName, final int userId,
2101 boolean idle, int bucket) {
2102 final int uid = mLocalPM.getPackageUid(packageName,
2103 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2104 if (uid < 0) {
2105 if (DEBUG_STANDBY) {
2106 Slog.i(TAG, "App idle state change for unknown app "
2107 + packageName + "/" + userId);
2108 }
2109 return;
2110 }
2111
2112 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2113 // update job bookkeeping out of band
2114 BackgroundThread.getHandler().post(() -> {
2115 if (DEBUG_STANDBY) {
2116 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2117 }
2118 synchronized (mLock) {
2119 // TODO: update to be more efficient once we can slice by source UID
2120 mJobs.forEachJob((JobStatus job) -> {
2121 if (job.getSourceUid() == uid) {
2122 job.setStandbyBucket(bucketIndex);
2123 }
2124 });
2125 onControllerStateChanged();
2126 }
2127 });
2128 }
2129
2130 @Override
2131 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002132 if (DEBUG_STANDBY) {
2133 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2134 }
2135 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002136 }
2137 }
2138
2139 public static int standbyBucketToBucketIndex(int bucket) {
2140 // Normalize AppStandby constants to indices into our bookkeeping
Amith Yamasaniafbccb72017-11-27 10:44:24 -08002141 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return 4;
2142 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) return 3;
2143 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) return 2;
2144 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return 1;
Christopher Tatea732f012017-10-26 17:26:53 -07002145 else return 0;
2146 }
2147
2148 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2149 UsageStatsManagerInternal usageStats = LocalServices.getService(
2150 UsageStatsManagerInternal.class);
2151 int bucket = usageStats != null
2152 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2153 : 0;
2154
2155 bucket = standbyBucketToBucketIndex(bucket);
2156
2157 if (DEBUG_STANDBY) {
2158 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2159 }
2160 return bucket;
2161 }
2162
2163 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002164 * Binder stub trampoline implementation
2165 */
2166 final class JobSchedulerStub extends IJobScheduler.Stub {
2167 /** Cache determination of whether a given app can persist jobs
2168 * key is uid of the calling app; value is undetermined/true/false
2169 */
2170 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2171
2172 // Enforce that only the app itself (or shared uid participant) can schedule a
2173 // job that runs one of the app's services, as well as verifying that the
2174 // named service properly requires the BIND_JOB_SERVICE permission
2175 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002176 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002177 final ComponentName service = job.getService();
2178 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002179 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002180 PackageManager.MATCH_DIRECT_BOOT_AWARE
2181 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002182 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002183 if (si == null) {
2184 throw new IllegalArgumentException("No such service " + service);
2185 }
Christopher Tate7060b042014-06-09 19:50:00 -07002186 if (si.applicationInfo.uid != uid) {
2187 throw new IllegalArgumentException("uid " + uid +
2188 " cannot schedule job in " + service.getPackageName());
2189 }
2190 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2191 throw new IllegalArgumentException("Scheduled service " + service
2192 + " does not require android.permission.BIND_JOB_SERVICE permission");
2193 }
Christopher Tate5568f542014-06-18 13:53:31 -07002194 } catch (RemoteException e) {
2195 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002196 }
2197 }
2198
2199 private boolean canPersistJobs(int pid, int uid) {
2200 // If we get this far we're good to go; all we need to do now is check
2201 // whether the app is allowed to persist its scheduled work.
2202 final boolean canPersist;
2203 synchronized (mPersistCache) {
2204 Boolean cached = mPersistCache.get(uid);
2205 if (cached != null) {
2206 canPersist = cached.booleanValue();
2207 } else {
2208 // Persisting jobs is tantamount to running at boot, so we permit
2209 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2210 // permission
2211 int result = getContext().checkPermission(
2212 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2213 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2214 mPersistCache.put(uid, canPersist);
2215 }
2216 }
2217 return canPersist;
2218 }
2219
2220 // IJobScheduler implementation
2221 @Override
2222 public int schedule(JobInfo job) throws RemoteException {
2223 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002224 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002225 }
2226 final int pid = Binder.getCallingPid();
2227 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002228 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002229
2230 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002231 if (job.isPersisted()) {
2232 if (!canPersistJobs(pid, uid)) {
2233 throw new IllegalArgumentException("Error: requested job be persisted without"
2234 + " holding RECEIVE_BOOT_COMPLETED permission.");
2235 }
2236 }
Christopher Tate7060b042014-06-09 19:50:00 -07002237
Jeff Sharkey785f4942016-07-14 10:31:15 -06002238 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2239 getContext().enforceCallingOrSelfPermission(
2240 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2241 }
2242
Christopher Tate7060b042014-06-09 19:50:00 -07002243 long ident = Binder.clearCallingIdentity();
2244 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002245 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2246 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002247 } finally {
2248 Binder.restoreCallingIdentity(ident);
2249 }
2250 }
2251
2252 // IJobScheduler implementation
2253 @Override
2254 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2255 if (DEBUG) {
2256 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2257 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002258 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002259 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002260
2261 enforceValidJobRequest(uid, job);
2262 if (job.isPersisted()) {
2263 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2264 }
2265 if (work == null) {
2266 throw new NullPointerException("work is null");
2267 }
2268
2269 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2270 getContext().enforceCallingOrSelfPermission(
2271 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2272 }
2273
2274 long ident = Binder.clearCallingIdentity();
2275 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002276 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2277 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002278 } finally {
2279 Binder.restoreCallingIdentity(ident);
2280 }
2281 }
2282
2283 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002284 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002285 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002286 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002287 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002288 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002289 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002290 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002291
2292 if (packageName == null) {
2293 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002294 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002295
2296 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2297 android.Manifest.permission.UPDATE_DEVICE_STATS);
2298 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2299 throw new SecurityException("Caller uid " + callerUid
2300 + " not permitted to schedule jobs for other apps");
2301 }
2302
Jeff Sharkey4f100402016-05-03 17:44:23 -06002303 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2304 getContext().enforceCallingOrSelfPermission(
2305 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2306 }
2307
Shreyas Basarge968ac752016-01-11 23:09:26 +00002308 long ident = Binder.clearCallingIdentity();
2309 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002310 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002311 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002312 } finally {
2313 Binder.restoreCallingIdentity(ident);
2314 }
2315 }
2316
2317 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002318 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2319 final int uid = Binder.getCallingUid();
2320
2321 long ident = Binder.clearCallingIdentity();
2322 try {
2323 return JobSchedulerService.this.getPendingJobs(uid);
2324 } finally {
2325 Binder.restoreCallingIdentity(ident);
2326 }
2327 }
2328
2329 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002330 public JobInfo getPendingJob(int jobId) throws RemoteException {
2331 final int uid = Binder.getCallingUid();
2332
2333 long ident = Binder.clearCallingIdentity();
2334 try {
2335 return JobSchedulerService.this.getPendingJob(uid, jobId);
2336 } finally {
2337 Binder.restoreCallingIdentity(ident);
2338 }
2339 }
2340
2341 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002342 public void cancelAll() throws RemoteException {
2343 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002344 long ident = Binder.clearCallingIdentity();
2345 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002346 JobSchedulerService.this.cancelJobsForUid(uid,
2347 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002348 } finally {
2349 Binder.restoreCallingIdentity(ident);
2350 }
2351 }
2352
2353 @Override
2354 public void cancel(int jobId) throws RemoteException {
2355 final int uid = Binder.getCallingUid();
2356
2357 long ident = Binder.clearCallingIdentity();
2358 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002359 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002360 } finally {
2361 Binder.restoreCallingIdentity(ident);
2362 }
2363 }
2364
2365 /**
2366 * "dumpsys" infrastructure
2367 */
2368 @Override
2369 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002370 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002371
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002372 int filterUid = -1;
2373 boolean proto = false;
2374 if (!ArrayUtils.isEmpty(args)) {
2375 int opti = 0;
2376 while (opti < args.length) {
2377 String arg = args[opti];
2378 if ("-h".equals(arg)) {
2379 dumpHelp(pw);
2380 return;
2381 } else if ("-a".equals(arg)) {
2382 // Ignore, we always dump all.
2383 } else if ("--proto".equals(arg)) {
2384 proto = true;
2385 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2386 pw.println("Unknown option: " + arg);
2387 return;
2388 } else {
2389 break;
2390 }
2391 opti++;
2392 }
2393 if (opti < args.length) {
2394 String pkg = args[opti];
2395 try {
2396 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2397 PackageManager.MATCH_ANY_USER);
2398 } catch (NameNotFoundException ignored) {
2399 pw.println("Invalid package: " + pkg);
2400 return;
2401 }
2402 }
2403 }
2404
Christopher Tate7060b042014-06-09 19:50:00 -07002405 long identityToken = Binder.clearCallingIdentity();
2406 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002407 if (proto) {
2408 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2409 } else {
2410 JobSchedulerService.this.dumpInternal(pw, filterUid);
2411 }
Christopher Tate7060b042014-06-09 19:50:00 -07002412 } finally {
2413 Binder.restoreCallingIdentity(identityToken);
2414 }
2415 }
Christopher Tate5d346052016-03-08 12:56:08 -08002416
2417 @Override
2418 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002419 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002420 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002421 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002422 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002423 };
2424
Christopher Tate5d346052016-03-08 12:56:08 -08002425 // Shell command infrastructure: run the given job immediately
2426 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2427 if (DEBUG) {
2428 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2429 + " " + jobId + " f=" + force);
2430 }
2431
2432 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002433 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2434 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002435 if (uid < 0) {
2436 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2437 }
2438
2439 synchronized (mLock) {
2440 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2441 if (js == null) {
2442 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2443 }
2444
2445 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2446 if (!js.isConstraintsSatisfied()) {
2447 js.overrideState = 0;
2448 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2449 }
2450
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002451 queueReadyJobsForExecutionLocked();
2452 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002453 }
2454 } catch (RemoteException e) {
2455 // can't happen
2456 }
2457 return 0;
2458 }
2459
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002460 // Shell command infrastructure: immediately timeout currently executing jobs
2461 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2462 boolean hasJobId, int jobId) {
2463 if (DEBUG) {
2464 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2465 }
2466
2467 synchronized (mLock) {
2468 boolean foundSome = false;
2469 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002470 final JobServiceContext jc = mActiveServices.get(i);
2471 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002472 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002473 foundSome = true;
2474 pw.print("Timing out: ");
2475 js.printUniqueId(pw);
2476 pw.print(" ");
2477 pw.println(js.getServiceComponent().flattenToShortString());
2478 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002479 }
2480 if (!foundSome) {
2481 pw.println("No matching executing jobs found.");
2482 }
2483 }
2484 return 0;
2485 }
2486
Christopher Tate8c67d122017-09-29 16:54:26 -07002487 // Shell command infrastructure: cancel a scheduled job
2488 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2489 boolean hasJobId, int jobId) {
2490 if (DEBUG) {
2491 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2492 }
2493
2494 int pkgUid = -1;
2495 try {
2496 IPackageManager pm = AppGlobals.getPackageManager();
2497 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2498 } catch (RemoteException e) { /* can't happen */ }
2499
2500 if (pkgUid < 0) {
2501 pw.println("Package " + pkgName + " not found.");
2502 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2503 }
2504
2505 if (!hasJobId) {
2506 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2507 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2508 pw.println("No matching jobs found.");
2509 }
2510 } else {
2511 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002512 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002513 pw.println("No matching job found.");
2514 }
2515 }
2516
2517 return 0;
2518 }
2519
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002520 void setMonitorBattery(boolean enabled) {
2521 synchronized (mLock) {
2522 if (mBatteryController != null) {
2523 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2524 }
2525 }
2526 }
2527
2528 int getBatterySeq() {
2529 synchronized (mLock) {
2530 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2531 }
2532 }
2533
2534 boolean getBatteryCharging() {
2535 synchronized (mLock) {
2536 return mBatteryController != null
2537 ? mBatteryController.getTracker().isOnStablePower() : false;
2538 }
2539 }
2540
2541 boolean getBatteryNotLow() {
2542 synchronized (mLock) {
2543 return mBatteryController != null
2544 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2545 }
2546 }
2547
Dianne Hackborn532ea262017-03-17 17:50:55 -07002548 int getStorageSeq() {
2549 synchronized (mLock) {
2550 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2551 }
2552 }
2553
2554 boolean getStorageNotLow() {
2555 synchronized (mLock) {
2556 return mStorageController != null
2557 ? mStorageController.getTracker().isStorageNotLow() : false;
2558 }
2559 }
2560
Christopher Tatea732f012017-10-26 17:26:53 -07002561 long getCurrentHeartbeat() {
2562 synchronized (mLock) {
2563 return mHeartbeat;
2564 }
2565 }
2566
Dianne Hackborn6d068262017-05-16 13:14:37 -07002567 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2568 try {
2569 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2570 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2571 if (uid < 0) {
2572 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2573 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2574 }
2575
2576 synchronized (mLock) {
2577 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2578 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2579 if (js == null) {
2580 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2581 pw.print("/jid"); pw.print(jobId); pw.println(")");
2582 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2583 }
2584
2585 boolean printed = false;
2586 if (mPendingJobs.contains(js)) {
2587 pw.print("pending");
2588 printed = true;
2589 }
2590 if (isCurrentlyActiveLocked(js)) {
2591 if (printed) {
2592 pw.print(" ");
2593 }
2594 printed = true;
2595 pw.println("active");
2596 }
2597 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2598 if (printed) {
2599 pw.print(" ");
2600 }
2601 printed = true;
2602 pw.println("user-stopped");
2603 }
2604 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2605 if (printed) {
2606 pw.print(" ");
2607 }
2608 printed = true;
2609 pw.println("backing-up");
2610 }
2611 boolean componentPresent = false;
2612 try {
2613 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2614 js.getServiceComponent(),
2615 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2616 js.getUserId()) != null);
2617 } catch (RemoteException e) {
2618 }
2619 if (!componentPresent) {
2620 if (printed) {
2621 pw.print(" ");
2622 }
2623 printed = true;
2624 pw.println("no-component");
2625 }
2626 if (js.isReady()) {
2627 if (printed) {
2628 pw.print(" ");
2629 }
2630 printed = true;
2631 pw.println("ready");
2632 }
2633 if (!printed) {
2634 pw.print("waiting");
2635 }
2636 pw.println();
2637 }
2638 } catch (RemoteException e) {
2639 // can't happen
2640 }
2641 return 0;
2642 }
2643
Shreyas Basarge5db09082016-01-07 13:38:29 +00002644 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2645 StringBuilder s = new StringBuilder(initial + ": ");
2646 for (int i=0; i<map.length; i++) {
2647 s.append("(")
2648 .append(map[i] == null? -1: map[i].getJobId())
2649 .append(map[i] == null? -1: map[i].getUid())
2650 .append(")" );
2651 }
2652 return s.toString();
2653 }
2654
2655 private String printPendingQueue() {
2656 StringBuilder s = new StringBuilder("Pending queue: ");
2657 Iterator<JobStatus> it = mPendingJobs.iterator();
2658 while (it.hasNext()) {
2659 JobStatus js = it.next();
2660 s.append("(")
2661 .append(js.getJob().getId())
2662 .append(", ")
2663 .append(js.getUid())
2664 .append(") ");
2665 }
2666 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002667 }
Christopher Tate7060b042014-06-09 19:50:00 -07002668
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002669 static void dumpHelp(PrintWriter pw) {
2670 pw.println("Job Scheduler (jobscheduler) dump options:");
2671 pw.println(" [-h] [package] ...");
2672 pw.println(" -h: print this help");
2673 pw.println(" [package] is an optional package name to limit the output to.");
2674 }
2675
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002676 /** Sort jobs by caller UID, then by Job ID. */
2677 private static void sortJobs(List<JobStatus> jobs) {
2678 Collections.sort(jobs, new Comparator<JobStatus>() {
2679 @Override
2680 public int compare(JobStatus o1, JobStatus o2) {
2681 int uid1 = o1.getUid();
2682 int uid2 = o2.getUid();
2683 int id1 = o1.getJobId();
2684 int id2 = o2.getJobId();
2685 if (uid1 != uid2) {
2686 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002687 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002688 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002689 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002690 });
2691 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002692
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002693 void dumpInternal(final PrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002694 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07002695 final long nowElapsed = sElapsedRealtimeClock.millis();
2696 final long nowUptime = sUptimeMillisClock.millis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002697 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002698 mConstants.dump(pw);
2699 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002700 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002701 pw.print("Registered ");
2702 pw.print(mJobs.size());
2703 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002704 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002705 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002706 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002707 for (JobStatus job : jobs) {
2708 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2709 pw.println(job.toShortStringExceptUniqueId());
2710
2711 // Skip printing details if the caller requested a filter
2712 if (!job.shouldDump(filterUidFinal)) {
2713 continue;
2714 }
2715
Dianne Hackborn6d068262017-05-16 13:14:37 -07002716 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002717 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002718 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002719 pw.print(" (job=");
2720 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002721 pw.print(" user=");
2722 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002723 pw.print(" !pending=");
2724 pw.print(!mPendingJobs.contains(job));
2725 pw.print(" !active=");
2726 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002727 pw.print(" !backingup=");
2728 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002729 pw.print(" comp=");
2730 boolean componentPresent = false;
2731 try {
2732 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2733 job.getServiceComponent(),
2734 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2735 job.getUserId()) != null);
2736 } catch (RemoteException e) {
2737 }
2738 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002739 pw.println(")");
2740 }
Christopher Tate7060b042014-06-09 19:50:00 -07002741 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002742 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002743 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002744 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002745 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002746 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002747 }
2748 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002749 pw.println("Uid priority overrides:");
2750 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002751 int uid = mUidPriorityOverride.keyAt(i);
2752 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2753 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2754 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2755 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002756 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002757 if (mBackingUpUids.size() > 0) {
2758 pw.println();
2759 pw.println("Backing up uids:");
2760 boolean first = true;
2761 for (int i = 0; i < mBackingUpUids.size(); i++) {
2762 int uid = mBackingUpUids.keyAt(i);
2763 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2764 if (first) {
2765 pw.print(" ");
2766 first = false;
2767 } else {
2768 pw.print(", ");
2769 }
2770 pw.print(UserHandle.formatUid(uid));
2771 }
2772 }
2773 pw.println();
2774 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002775 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002776 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002777 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002778 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2779 pw.println();
2780 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002781 pw.println("Pending queue:");
2782 for (int i=0; i<mPendingJobs.size(); i++) {
2783 JobStatus job = mPendingJobs.get(i);
2784 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2785 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002786 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002787 int priority = evaluateJobPriorityLocked(job);
2788 if (priority != JobInfo.PRIORITY_DEFAULT) {
2789 pw.print(" Evaluated priority: "); pw.println(priority);
2790 }
2791 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002792 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002793 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002794 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002795 }
Christopher Tate7060b042014-06-09 19:50:00 -07002796 pw.println();
2797 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002798 for (int i=0; i<mActiveServices.size(); i++) {
2799 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002800 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002801 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07002802 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07002803 if (jsc.mStoppedReason != null) {
2804 pw.print("inactive since ");
2805 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
2806 pw.print(", stopped because: ");
2807 pw.println(jsc.mStoppedReason);
2808 } else {
2809 pw.println("inactive");
2810 }
Christopher Tate7060b042014-06-09 19:50:00 -07002811 continue;
2812 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07002813 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08002814 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002815 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002816 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002817 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002818 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002819 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002820 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002821 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002822 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002823 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002824 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002825 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002826 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07002827 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
2828 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07002829 }
2830 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002831 if (filterUid == -1) {
2832 pw.println();
2833 pw.print("mReadyToRock="); pw.println(mReadyToRock);
2834 pw.print("mReportedActive="); pw.println(mReportedActive);
2835 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
2836 }
Makoto Onukie7b02982017-08-24 14:23:36 -07002837 pw.println();
2838 pw.print("PersistStats: ");
2839 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07002840 }
2841 pw.println();
2842 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002843
2844 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
2845 ProtoOutputStream proto = new ProtoOutputStream(fd);
2846 final int filterUidFinal = UserHandle.getAppId(filterUid);
2847 final long nowElapsed = sElapsedRealtimeClock.millis();
2848 final long nowUptime = sUptimeMillisClock.millis();
2849
2850 synchronized (mLock) {
2851 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
2852 for (int u : mStartedUsers) {
2853 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
2854 }
2855 if (mJobs.size() > 0) {
2856 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
2857 sortJobs(jobs);
2858 for (JobStatus job : jobs) {
2859 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
2860 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
2861
2862 // Skip printing details if the caller requested a filter
2863 if (!job.shouldDump(filterUidFinal)) {
2864 continue;
2865 }
2866
2867 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
2868
2869 // isReadyToBeExecuted
2870 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
2871 job.isReady());
2872 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
2873 ArrayUtils.contains(mStartedUsers, job.getUserId()));
2874 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
2875 mPendingJobs.contains(job));
2876 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
2877 isCurrentlyActiveLocked(job));
2878 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
2879 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
2880 boolean componentPresent = false;
2881 try {
2882 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2883 job.getServiceComponent(),
2884 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2885 job.getUserId()) != null);
2886 } catch (RemoteException e) {
2887 }
2888 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
2889 componentPresent);
2890
2891 proto.end(rjToken);
2892 }
2893 }
2894 for (StateController controller : mControllers) {
2895 controller.dumpControllerStateLocked(
2896 proto, JobSchedulerServiceDumpProto.CONTROLLERS, filterUidFinal);
2897 }
2898 for (int i=0; i< mUidPriorityOverride.size(); i++) {
2899 int uid = mUidPriorityOverride.keyAt(i);
2900 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2901 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
2902 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
2903 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
2904 mUidPriorityOverride.valueAt(i));
2905 proto.end(pToken);
2906 }
2907 }
2908 for (int i = 0; i < mBackingUpUids.size(); i++) {
2909 int uid = mBackingUpUids.keyAt(i);
2910 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2911 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
2912 }
2913 }
2914
2915 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
2916 filterUidFinal);
2917 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
2918 filterUidFinal);
2919
2920 for (JobStatus job : mPendingJobs) {
2921 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
2922
2923 job.writeToShortProto(proto, PendingJob.INFO);
2924 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
2925 int priority = evaluateJobPriorityLocked(job);
2926 if (priority != JobInfo.PRIORITY_DEFAULT) {
2927 proto.write(PendingJob.EVALUATED_PRIORITY, priority);
2928 }
2929 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
2930
2931 proto.end(pjToken);
2932 }
2933 for (JobServiceContext jsc : mActiveServices) {
2934 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
2935 final JobStatus job = jsc.getRunningJobLocked();
2936
2937 if (job == null) {
2938 final long ijToken = proto.start(ActiveJob.INACTIVE);
2939
2940 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
2941 nowElapsed - jsc.mStoppedTime);
2942 if (jsc.mStoppedReason != null) {
2943 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
2944 jsc.mStoppedReason);
2945 }
2946
2947 proto.end(ijToken);
2948 } else {
2949 final long rjToken = proto.start(ActiveJob.RUNNING);
2950
2951 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
2952
2953 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
2954 nowElapsed - jsc.getExecutionStartTimeElapsed());
2955 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
2956 jsc.getTimeoutElapsed() - nowElapsed);
2957
2958 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
2959
2960 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
2961 if (priority != JobInfo.PRIORITY_DEFAULT) {
2962 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY, priority);
2963 }
2964
2965 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
2966 nowUptime - job.madeActive);
2967 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
2968 job.madeActive - job.madePending);
2969
2970 proto.end(rjToken);
2971 }
2972 proto.end(ajToken);
2973 }
2974 if (filterUid == -1) {
2975 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
2976 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
2977 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
2978 }
2979 }
2980
2981 proto.flush();
2982 }
Christopher Tate7060b042014-06-09 19:50:00 -07002983}