blob: 6608cad19d618e0c526467a01572887cdcbdb37a [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.job;
18
Christopher Tateb5c07882016-05-26 17:11:09 -070019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21
Christopher Tate435c2f42018-01-18 12:59:15 -080022import android.annotation.UserIdInt;
Christopher Tateee7805b2016-07-15 16:56:56 -070023import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070024import android.app.ActivityManager;
Makoto Onuki15407842018-01-19 14:23:11 -080025import android.app.ActivityManagerInternal;
Christopher Tated1aebb32018-01-31 13:24:14 -080026import android.app.AlarmManager;
Christopher Tate5568f542014-06-18 13:53:31 -070027import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070029import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070030import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000031import android.app.job.JobParameters;
Tej Singh33a412b2018-03-16 18:43:59 -070032import android.app.job.JobProtoEnums;
Christopher Tate7060b042014-06-09 19:50:00 -070033import android.app.job.JobScheduler;
34import android.app.job.JobService;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070035import android.app.job.JobWorkItem;
Amith Yamasaniafbccb72017-11-27 10:44:24 -080036import android.app.usage.UsageStatsManager;
Christopher Tatea732f012017-10-26 17:26:53 -070037import android.app.usage.UsageStatsManagerInternal;
38import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
Christopher Tate7060b042014-06-09 19:50:00 -070039import android.content.BroadcastReceiver;
40import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070041import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070042import android.content.Context;
43import android.content.Intent;
44import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070045import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070046import android.content.pm.PackageManager;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060047import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070048import android.content.pm.PackageManagerInternal;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070049import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070050import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070051import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070052import android.os.BatteryStats;
Amith Yamasani977e11f2018-02-16 11:29:54 -080053import android.os.BatteryStatsInternal;
Christopher Tate7060b042014-06-09 19:50:00 -070054import android.os.Binder;
55import android.os.Handler;
56import android.os.Looper;
57import android.os.Message;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070058import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070059import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080060import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070061import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070062import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070063import android.os.SystemClock;
64import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070065import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070066import android.provider.Settings;
Amith Yamasani977e11f2018-02-16 11:29:54 -080067import android.text.format.DateUtils;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070068import android.util.KeyValueListParser;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070069import android.util.Log;
Christopher Tate7060b042014-06-09 19:50:00 -070070import android.util.Slog;
71import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080072import android.util.SparseIntArray;
Tej Singhd5747a62018-01-08 20:57:35 -080073import android.util.StatsLog;
Dianne Hackborn970510b2016-02-24 16:56:42 -080074import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080075import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080076
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070077import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070078import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070079import com.android.internal.app.procstats.ProcessStats;
Christopher Tatea732f012017-10-26 17:26:53 -070080import com.android.internal.os.BackgroundThread;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070081import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060082import com.android.internal.util.DumpUtils;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -070083import com.android.internal.util.IndentingPrintWriter;
Makoto Onuki15407842018-01-19 14:23:11 -080084import com.android.internal.util.Preconditions;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070085import com.android.server.AppStateTracker;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080086import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070087import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080088import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080089import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
90import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Makoto Onukib5d5e972018-02-20 14:44:20 -080091import com.android.server.job.JobSchedulerServiceDumpProto.RegisteredJob;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070092import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070093import com.android.server.job.controllers.BatteryController;
94import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080095import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070096import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070097import com.android.server.job.controllers.IdleController;
98import com.android.server.job.controllers.JobStatus;
99import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700100import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -0700101import com.android.server.job.controllers.TimeController;
102
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700103import libcore.util.EmptyArray;
104
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700105import java.io.FileDescriptor;
106import java.io.PrintWriter;
107import java.time.Clock;
108import java.util.ArrayList;
109import java.util.Arrays;
110import java.util.Collections;
111import java.util.Comparator;
Christopher Tate325768c2018-03-07 16:07:56 -0800112import java.util.HashMap;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700113import java.util.Iterator;
114import java.util.List;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -0700115import java.util.function.Consumer;
Makoto Onuki15407842018-01-19 14:23:11 -0800116import java.util.function.Predicate;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700117
Christopher Tate7060b042014-06-09 19:50:00 -0700118/**
119 * Responsible for taking jobs representing work to be performed by a client app, and determining
120 * based on the criteria specified when that job should be run against the client application's
121 * endpoint.
122 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
123 * about constraints, or the state of active jobs. It receives callbacks from the various
124 * controllers and completed jobs and operates accordingly.
125 *
126 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
127 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
128 * @hide
129 */
Jeff Sharkey4d89e422018-03-29 18:22:41 -0600130public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700131 implements StateChangedListener, JobCompletedListener {
Jeff Sharkey01bb5302018-02-21 20:12:40 -0700132 public static final String TAG = "JobScheduler";
133 public static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Christopher Tatea732f012017-10-26 17:26:53 -0700134 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800135
Dianne Hackborn970510b2016-02-24 16:56:42 -0800136 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700137 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800138 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800139 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800140 /** The maximum number of jobs that we allow an unprivileged app to schedule */
141 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700142
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700143 @VisibleForTesting
144 public static Clock sSystemClock = Clock.systemUTC();
145 @VisibleForTesting
146 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
147 @VisibleForTesting
148 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800149
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800150 /** Global local for all job scheduler state. */
151 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700152 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700153 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700154 /** Tracking the standby bucket state of each app */
155 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700156 /** Tracking amount of time each package runs for. */
157 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700158
159 static final int MSG_JOB_EXPIRED = 0;
160 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700161 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000162 static final int MSG_CHECK_JOB_GREEDY = 3;
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800163 static final int MSG_UID_STATE_CHANGED = 4;
164 static final int MSG_UID_GONE = 5;
165 static final int MSG_UID_ACTIVE = 6;
166 static final int MSG_UID_IDLE = 7;
Christopher Tate7060b042014-06-09 19:50:00 -0700167
Christopher Tate7060b042014-06-09 19:50:00 -0700168 /**
169 * Track Services that have currently active or pending jobs. The index is provided by
170 * {@link JobStatus#getServiceToken()}
171 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700172 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700173
Christopher Tate7060b042014-06-09 19:50:00 -0700174 /** List of controllers that will notify this service of updates to jobs. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700175 private final List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800176 /** Need direct access to this for testing. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700177 private final BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700178 /** Need direct access to this for testing. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700179 private final StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700180 /** Need directly for sending uid state changes */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700181 private final DeviceIdleJobsController mDeviceIdleJobsController;
182
Christopher Tate7060b042014-06-09 19:50:00 -0700183 /**
184 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
185 * when ready to execute them.
186 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700187 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700188
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700189 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700190
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700191 final JobHandler mHandler;
192 final JobSchedulerStub mJobSchedulerStub;
193
Christopher Tatea732f012017-10-26 17:26:53 -0700194 PackageManagerInternal mLocalPM;
Makoto Onuki15407842018-01-19 14:23:11 -0800195 ActivityManagerInternal mActivityManagerInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700196 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800197 DeviceIdleController.LocalService mLocalDeviceIdleController;
Makoto Onukie4918212018-02-06 11:30:15 -0800198 AppStateTracker mAppStateTracker;
Christopher Tated1aebb32018-01-31 13:24:14 -0800199 final UsageStatsManagerInternal mUsageStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700200
201 /**
202 * Set to true once we are allowed to run third party apps.
203 */
204 boolean mReadyToRock;
205
Christopher Tate7060b042014-06-09 19:50:00 -0700206 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800207 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800208 */
209 boolean mReportedActive;
210
211 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800212 * Are we currently in device-wide standby parole?
213 */
214 volatile boolean mInParole;
215
216 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800217 * Current limit on the number of concurrent JobServiceContext entries we want to
218 * keep actively running a job.
219 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700220 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800221
222 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800223 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800224 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800225 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
226
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700227 /**
228 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
229 */
230 final SparseIntArray mBackingUpUids = new SparseIntArray();
231
Christopher Tatea732f012017-10-26 17:26:53 -0700232 /**
233 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
234 * next become runnable. Index into this array is by normalized bucket:
235 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
236 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
237 * and NEVER apps don't get them at all.
238 */
239 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
240 long mHeartbeat = 0;
Christopher Tated1aebb32018-01-31 13:24:14 -0800241 long mLastHeartbeatTime = sElapsedRealtimeClock.millis();
242
Christopher Tate325768c2018-03-07 16:07:56 -0800243 /**
244 * Named indices into the STANDBY_BEATS array, for clarity in referring to
245 * specific buckets' bookkeeping.
246 */
247 static final int ACTIVE_INDEX = 0;
248 static final int WORKING_INDEX = 1;
249 static final int FREQUENT_INDEX = 2;
250 static final int RARE_INDEX = 3;
Christopher Tatef2159712018-03-27 16:04:14 -0700251 static final int NEVER_INDEX = 4;
Christopher Tate325768c2018-03-07 16:07:56 -0800252
253 /**
254 * Bookkeeping about when jobs last run. We keep our own record in heartbeat time,
255 * rather than rely on Usage Stats' timestamps, because heartbeat time can be
256 * manipulated for testing purposes and we need job runnability to track that rather
257 * than real time.
258 *
259 * Outer SparseArray slices by user handle; inner map of package name to heartbeat
260 * is a HashMap<> rather than ArrayMap<> because we expect O(hundreds) of keys
261 * and it will be accessed in a known-hot code path.
262 */
263 final SparseArray<HashMap<String, Long>> mLastJobHeartbeats = new SparseArray<>();
264
Christopher Tated1aebb32018-01-31 13:24:14 -0800265 static final String HEARTBEAT_TAG = "*job.heartbeat*";
266 final HeartbeatAlarmListener mHeartbeatAlarm = new HeartbeatAlarmListener();
Christopher Tatea732f012017-10-26 17:26:53 -0700267
Dianne Hackborn970510b2016-02-24 16:56:42 -0800268 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
269
270 /**
271 * This array essentially stores the state of mActiveServices array.
272 * The ith index stores the job present on the ith JobServiceContext.
273 * We manipulate this array until we arrive at what jobs should be running on
274 * what JobServiceContext.
275 */
276 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
277 /**
278 * Indicates whether we need to act on this jobContext id
279 */
280 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
281 /**
282 * The uid whose jobs we would like to assign to a context.
283 */
284 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800285
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700286 private class ConstantsObserver extends ContentObserver {
287 private ContentResolver mResolver;
288
289 public ConstantsObserver(Handler handler) {
290 super(handler);
291 }
292
293 public void start(ContentResolver resolver) {
294 mResolver = resolver;
295 mResolver.registerContentObserver(Settings.Global.getUriFor(
296 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
297 updateConstants();
298 }
299
300 @Override
301 public void onChange(boolean selfChange, Uri uri) {
302 updateConstants();
303 }
304
305 private void updateConstants() {
306 synchronized (mLock) {
307 try {
308 mConstants.updateConstantsLocked(Settings.Global.getString(mResolver,
309 Settings.Global.JOB_SCHEDULER_CONSTANTS));
310 } catch (IllegalArgumentException e) {
311 // Failed to parse the settings string, log this and move on
312 // with defaults.
313 Slog.e(TAG, "Bad jobscheduler settings", e);
314 }
315 }
316
317 // Reset the heartbeat alarm based on the new heartbeat duration
318 setNextHeartbeatAlarm();
319 }
320 }
321
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800322 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700323 * All times are in milliseconds. These constants are kept synchronized with the system
324 * global Settings. Any access to this class or its fields should be done while
325 * holding the JobSchedulerService.mLock lock.
326 */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700327 public static class Constants {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700328 // Key names stored in the settings value.
329 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
330 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800331 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700332 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700333 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
334 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
335 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
336 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
337 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
338 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
339 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
340 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
341 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
342 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700343 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
344 = "max_standard_reschedule_count";
345 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
346 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
347 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700348 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
349 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
350 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
351 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700352 private static final String KEY_CONN_CONGESTION_DELAY_FRAC = "conn_congestion_delay_frac";
353 private static final String KEY_CONN_PREFETCH_RELAX_FRAC = "conn_prefetch_relax_frac";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700354
355 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
356 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800357 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700358 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700359 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
360 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
361 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
362 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
363 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
364 private static final int DEFAULT_FG_JOB_COUNT = 4;
365 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
366 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700367 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700368 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700369 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
370 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
371 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
372 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700373 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000374 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
375 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700376 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700377 private static final float DEFAULT_CONN_CONGESTION_DELAY_FRAC = 0.5f;
378 private static final float DEFAULT_CONN_PREFETCH_RELAX_FRAC = 0.5f;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700379
380 /**
381 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
382 * early.
383 */
384 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
385 /**
386 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
387 * things early.
388 */
389 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
390 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800391 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
392 * schedule things early.
393 */
394 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
395 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700396 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
397 * schedule things early.
398 */
399 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
400 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700401 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
402 * things early. 1 == Run connectivity jobs as soon as ready.
403 */
404 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
405 /**
406 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
407 * schedule things early.
408 */
409 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
410 /**
411 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
412 * running some work early. This (and thus the other min counts) is now set to 1, to
413 * prevent any batching at this level. Since we now do batching through doze, that is
414 * a much better mechanism.
415 */
416 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
417 /**
418 * This is the job execution factor that is considered to be heavy use of the system.
419 */
420 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
421 /**
422 * This is the job execution factor that is considered to be moderate use of the system.
423 */
424 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
425 /**
426 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
427 */
428 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
429 /**
430 * The maximum number of background jobs we allow when the system is in a normal
431 * memory state.
432 */
433 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
434 /**
435 * The maximum number of background jobs we allow when the system is in a moderate
436 * memory state.
437 */
438 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
439 /**
440 * The maximum number of background jobs we allow when the system is in a low
441 * memory state.
442 */
443 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
444 /**
445 * The maximum number of background jobs we allow when the system is in a critical
446 * memory state.
447 */
448 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700449 /**
450 * The maximum number of times we allow a job to have itself rescheduled before
451 * giving up on it, for standard jobs.
452 */
453 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
454 /**
455 * The maximum number of times we allow a job to have itself rescheduled before
456 * giving up on it, for jobs that are executing work.
457 */
458 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
459 /**
460 * The minimum backoff time to allow for linear backoff.
461 */
462 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
463 /**
464 * The minimum backoff time to allow for exponential backoff.
465 */
466 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700467 /**
468 * How often we recalculate runnability based on apps' standby bucket assignment.
469 * This should be prime relative to common time interval lengths such as a quarter-
470 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
471 */
472 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700473 /**
474 * Mapping: standby bucket -> number of heartbeats between each sweep of that
475 * bucket's jobs.
476 *
477 * Bucket assignments as recorded in the JobStatus objects are normalized to be
478 * indices into this array, rather than the raw constants used
479 * by AppIdleHistory.
480 */
481 final int[] STANDBY_BEATS = {
482 0,
483 DEFAULT_STANDBY_WORKING_BEATS,
484 DEFAULT_STANDBY_FREQUENT_BEATS,
485 DEFAULT_STANDBY_RARE_BEATS
486 };
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700487 /**
488 * The fraction of a job's running window that must pass before we
489 * consider running it when the network is congested.
490 */
491 public float CONN_CONGESTION_DELAY_FRAC = DEFAULT_CONN_CONGESTION_DELAY_FRAC;
492 /**
493 * The fraction of a prefetch job's running window that must pass before
494 * we consider matching it against a metered network.
495 */
496 public float CONN_PREFETCH_RELAX_FRAC = DEFAULT_CONN_PREFETCH_RELAX_FRAC;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700497
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700498 private final KeyValueListParser mParser = new KeyValueListParser(',');
499
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700500 void updateConstantsLocked(String value) {
501 try {
502 mParser.setString(value);
503 } catch (Exception e) {
504 // Failed to parse the settings string, log this and move on
505 // with defaults.
506 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700507 }
Christopher Tated1aebb32018-01-31 13:24:14 -0800508
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700509 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
510 DEFAULT_MIN_IDLE_COUNT);
511 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
512 DEFAULT_MIN_CHARGING_COUNT);
513 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
514 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
515 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
516 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
517 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
518 DEFAULT_MIN_CONNECTIVITY_COUNT);
519 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
520 DEFAULT_MIN_CONTENT_COUNT);
521 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
522 DEFAULT_MIN_READY_JOBS_COUNT);
523 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
524 DEFAULT_HEAVY_USE_FACTOR);
525 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
526 DEFAULT_MODERATE_USE_FACTOR);
527 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
528 DEFAULT_FG_JOB_COUNT);
529 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
530 DEFAULT_BG_NORMAL_JOB_COUNT);
531 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
532 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
533 }
534 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
535 DEFAULT_BG_MODERATE_JOB_COUNT);
536 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
537 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
538 }
539 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
540 DEFAULT_BG_LOW_JOB_COUNT);
541 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
542 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
543 }
544 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
545 DEFAULT_BG_CRITICAL_JOB_COUNT);
546 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
547 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
548 }
549 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
550 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
551 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
552 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
553 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
554 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
555 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
556 DEFAULT_MIN_EXP_BACKOFF_TIME);
557 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
558 DEFAULT_STANDBY_HEARTBEAT_TIME);
Christopher Tate325768c2018-03-07 16:07:56 -0800559 STANDBY_BEATS[WORKING_INDEX] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700560 DEFAULT_STANDBY_WORKING_BEATS);
Christopher Tate325768c2018-03-07 16:07:56 -0800561 STANDBY_BEATS[FREQUENT_INDEX] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700562 DEFAULT_STANDBY_FREQUENT_BEATS);
Christopher Tate325768c2018-03-07 16:07:56 -0800563 STANDBY_BEATS[RARE_INDEX] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700564 DEFAULT_STANDBY_RARE_BEATS);
565 CONN_CONGESTION_DELAY_FRAC = mParser.getFloat(KEY_CONN_CONGESTION_DELAY_FRAC,
566 DEFAULT_CONN_CONGESTION_DELAY_FRAC);
567 CONN_PREFETCH_RELAX_FRAC = mParser.getFloat(KEY_CONN_PREFETCH_RELAX_FRAC,
568 DEFAULT_CONN_PREFETCH_RELAX_FRAC);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700569 }
570
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700571 void dump(IndentingPrintWriter pw) {
572 pw.println("Settings:");
573 pw.increaseIndent();
574 pw.printPair(KEY_MIN_IDLE_COUNT, MIN_IDLE_COUNT).println();
575 pw.printPair(KEY_MIN_CHARGING_COUNT, MIN_CHARGING_COUNT).println();
576 pw.printPair(KEY_MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT).println();
577 pw.printPair(KEY_MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT).println();
578 pw.printPair(KEY_MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT).println();
579 pw.printPair(KEY_MIN_CONTENT_COUNT, MIN_CONTENT_COUNT).println();
580 pw.printPair(KEY_MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT).println();
581 pw.printPair(KEY_HEAVY_USE_FACTOR, HEAVY_USE_FACTOR).println();
582 pw.printPair(KEY_MODERATE_USE_FACTOR, MODERATE_USE_FACTOR).println();
583 pw.printPair(KEY_FG_JOB_COUNT, FG_JOB_COUNT).println();
584 pw.printPair(KEY_BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT).println();
585 pw.printPair(KEY_BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT).println();
586 pw.printPair(KEY_BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT).println();
587 pw.printPair(KEY_BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT).println();
588 pw.printPair(KEY_MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT).println();
589 pw.printPair(KEY_MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT).println();
590 pw.printPair(KEY_MIN_LINEAR_BACKOFF_TIME, MIN_LINEAR_BACKOFF_TIME).println();
591 pw.printPair(KEY_MIN_EXP_BACKOFF_TIME, MIN_EXP_BACKOFF_TIME).println();
592 pw.printPair(KEY_STANDBY_HEARTBEAT_TIME, STANDBY_HEARTBEAT_TIME).println();
593 pw.print("standby_beats={");
Christopher Tatea732f012017-10-26 17:26:53 -0700594 pw.print(STANDBY_BEATS[0]);
595 for (int i = 1; i < STANDBY_BEATS.length; i++) {
596 pw.print(", ");
597 pw.print(STANDBY_BEATS[i]);
598 }
599 pw.println('}');
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700600 pw.printPair(KEY_CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC).println();
601 pw.printPair(KEY_CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC).println();
602 pw.decreaseIndent();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700603 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800604
605 void dump(ProtoOutputStream proto, long fieldId) {
606 final long token = proto.start(fieldId);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800607 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
608 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
609 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
610 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
611 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
612 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
613 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
614 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
615 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
616 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
617 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
618 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
619 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
620 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
621 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
622 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
623 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
624 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
625 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800626 for (int period : STANDBY_BEATS) {
627 proto.write(ConstantsProto.STANDBY_BEATS, period);
628 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700629 proto.write(ConstantsProto.CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC);
630 proto.write(ConstantsProto.CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800631 proto.end(token);
632 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700633 }
634
635 final Constants mConstants;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700636 final ConstantsObserver mConstantsObserver;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700637
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700638 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
639 if (o1.enqueueTime < o2.enqueueTime) {
640 return -1;
641 }
642 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
643 };
644
645 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
646 int where = Collections.binarySearch(array, newItem, comparator);
647 if (where < 0) {
648 where = ~where;
649 }
650 array.add(where, newItem);
651 }
652
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700653 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700654 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
655 * still clean up. On reinstall the package will have a new uid.
656 */
657 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
658 @Override
659 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700660 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700661 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700662 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700663 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700664 final String pkgName = getPackageName(intent);
665 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
666
Christopher Tateee7805b2016-07-15 16:56:56 -0700667 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700668 // Purge the app's jobs if the whole package was just disabled. When this is
669 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700670 if (pkgName != null && pkgUid != -1) {
671 final String[] changedComponents = intent.getStringArrayExtra(
672 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
673 if (changedComponents != null) {
674 for (String component : changedComponents) {
675 if (component.equals(pkgName)) {
676 if (DEBUG) {
677 Slog.d(TAG, "Package state change: " + pkgName);
678 }
679 try {
680 final int userId = UserHandle.getUserId(pkgUid);
681 IPackageManager pm = AppGlobals.getPackageManager();
682 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
683 if (state == COMPONENT_ENABLED_STATE_DISABLED
684 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
685 if (DEBUG) {
686 Slog.d(TAG, "Removing jobs for package " + pkgName
687 + " in user " + userId);
688 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700689 cancelJobsForPackageAndUid(pkgName, pkgUid,
690 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700691 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700692 } catch (RemoteException|IllegalArgumentException e) {
693 /*
694 * IllegalArgumentException means that the package doesn't exist.
695 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
696 * behind outright uninstall, so by the time we try to act it's gone.
697 * We don't need to act on this PACKAGE_CHANGED when this happens;
698 * we'll get a PACKAGE_REMOVED later and clean up then.
699 *
700 * RemoteException can't actually happen; the package manager is
701 * running in this same process.
702 */
703 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700704 break;
705 }
706 }
707 }
708 } else {
709 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
710 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700711 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700712 // If this is an outright uninstall rather than the first half of an
713 // app update sequence, cancel the jobs associated with the app.
714 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
715 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
716 if (DEBUG) {
717 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
718 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700719 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700720 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700721 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700722 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
723 if (DEBUG) {
724 Slog.d(TAG, "Removing jobs for user: " + userId);
725 }
726 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700727 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
728 // Has this package scheduled any jobs, such that we will take action
729 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700730 if (pkgUid != -1) {
731 List<JobStatus> jobsForUid;
732 synchronized (mLock) {
733 jobsForUid = mJobs.getJobsByUid(pkgUid);
734 }
735 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
736 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
737 if (DEBUG) {
738 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
739 + pkgUid + " has jobs");
740 }
741 setResultCode(Activity.RESULT_OK);
742 break;
743 }
744 }
745 }
746 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
747 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700748 if (pkgUid != -1) {
749 if (DEBUG) {
750 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
751 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700752 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700753 }
Christopher Tate7060b042014-06-09 19:50:00 -0700754 }
755 }
756 };
757
Christopher Tateb5c07882016-05-26 17:11:09 -0700758 private String getPackageName(Intent intent) {
759 Uri uri = intent.getData();
760 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
761 return pkg;
762 }
763
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700764 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700765 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800766 mHandler.obtainMessage(MSG_UID_STATE_CHANGED, uid, procState).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700767 }
768
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700769 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800770 mHandler.obtainMessage(MSG_UID_GONE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700771 }
772
773 @Override public void onUidActive(int uid) throws RemoteException {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800774 mHandler.obtainMessage(MSG_UID_ACTIVE, uid, 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700775 }
776
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700777 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800778 mHandler.obtainMessage(MSG_UID_IDLE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700779 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700780
781 @Override public void onUidCachedChanged(int uid, boolean cached) {
782 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700783 };
784
Jeff Sharkey4d89e422018-03-29 18:22:41 -0600785 public Context getTestableContext() {
786 return getContext();
787 }
788
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800789 public Object getLock() {
790 return mLock;
791 }
792
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700793 public JobStore getJobStore() {
794 return mJobs;
795 }
796
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700797 public Constants getConstants() {
798 return mConstants;
799 }
800
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700801 @Override
802 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700803 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
804 // Let's kick any outstanding jobs for this user.
805 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
806 }
807
808 @Override
809 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700810 // Let's kick any outstanding jobs for this user.
811 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
812 }
813
814 @Override
815 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700816 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700817 }
818
Makoto Onuki15407842018-01-19 14:23:11 -0800819 /**
Makoto Onukie4918212018-02-06 11:30:15 -0800820 * Return whether an UID is active or idle.
Makoto Onuki15407842018-01-19 14:23:11 -0800821 */
Makoto Onukie4918212018-02-06 11:30:15 -0800822 private boolean isUidActive(int uid) {
823 return mAppStateTracker.isUidActiveSynced(uid);
Makoto Onuki15407842018-01-19 14:23:11 -0800824 }
825
Makoto Onukie4918212018-02-06 11:30:15 -0800826 private final Predicate<Integer> mIsUidActivePredicate = this::isUidActive;
Makoto Onuki15407842018-01-19 14:23:11 -0800827
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700828 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
829 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700830 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800831 if (ActivityManager.getService().isAppStartModeDisabled(uId,
832 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700833 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
834 + " -- package not allowed to start");
835 return JobScheduler.RESULT_FAILURE;
836 }
837 } catch (RemoteException e) {
838 }
Christopher Tatea732f012017-10-26 17:26:53 -0700839
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800840 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700841 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
842
843 if (work != null && toCancel != null) {
844 // Fast path: we are adding work to an existing job, and the JobInfo is not
845 // changing. We can just directly enqueue this work in to the job.
846 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -0800847
Dianne Hackborn342e6032017-04-13 18:04:31 -0700848 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Makoto Onuki15407842018-01-19 14:23:11 -0800849
850 // If any of work item is enqueued when the source is in the foreground,
851 // exempt the entire job.
Makoto Onukie4918212018-02-06 11:30:15 -0800852 toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800853
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700854 return JobScheduler.RESULT_SUCCESS;
855 }
856 }
857
858 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -0800859
860 // Give exemption if the source is in the foreground just now.
861 // Note if it's a sync job, this method is called on the handler so it's not exactly
862 // the state when requestSync() was called, but that should be fine because of the
863 // 1 minute foreground grace period.
Makoto Onukie4918212018-02-06 11:30:15 -0800864 jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800865
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700866 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800867 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800868 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800869 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
870 Slog.w(TAG, "Too many jobs for uid " + uId);
871 throw new IllegalStateException("Apps may not schedule more than "
872 + MAX_JOBS_PER_APP + " distinct jobs");
873 }
874 }
875
Dianne Hackborna47223f2017-03-30 13:49:13 -0700876 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700877 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700878
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700879 if (work != null) {
880 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700881 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700882 }
Christopher Tate44b50852018-10-05 15:53:50 -0700883
884 if (toCancel != null) {
885 // Implicitly replaces the existing job record with the new instance
886 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
887 } else {
888 startTrackingJobLocked(jobStatus, null);
889 }
Tej Singhd5747a62018-01-08 20:57:35 -0800890 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -0800891 uId, null, jobStatus.getBatteryName(),
Tej Singh33a412b2018-03-16 18:43:59 -0700892 StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
893 JobProtoEnums.STOP_REASON_CANCELLED);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700894
895 // If the job is immediately ready to run, then we can just immediately
896 // put it in the pending list and try to schedule it. This is especially
897 // important for jobs with a 0 deadline constraint, since they will happen a fair
898 // amount, we want to handle them as quickly as possible, and semantically we want to
899 // make sure we have started holding the wake lock for the job before returning to
900 // the caller.
901 // If the job is not yet ready to run, there is nothing more to do -- we are
902 // now just waiting for one of its controllers to change state and schedule
903 // the job appropriately.
904 if (isReadyToBeExecutedLocked(jobStatus)) {
905 // This is a new job, we can just immediately put it on the pending
906 // list and try to run it.
907 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700908 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700909 maybeRunPendingJobsLocked();
910 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800911 }
Christopher Tate7060b042014-06-09 19:50:00 -0700912 return JobScheduler.RESULT_SUCCESS;
913 }
914
915 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800916 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800917 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
918 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
919 for (int i = jobs.size() - 1; i >= 0; i--) {
920 JobStatus job = jobs.get(i);
921 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700922 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800923 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700924 }
Christopher Tate7060b042014-06-09 19:50:00 -0700925 }
926
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600927 public JobInfo getPendingJob(int uid, int jobId) {
928 synchronized (mLock) {
929 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
930 for (int i = jobs.size() - 1; i >= 0; i--) {
931 JobStatus job = jobs.get(i);
932 if (job.getJobId() == jobId) {
933 return job.getJob();
934 }
935 }
936 return null;
937 }
938 }
939
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700940 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800941 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700942 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
943 for (int i=0; i<jobsForUser.size(); i++) {
944 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700945 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700946 }
Christopher Tate7060b042014-06-09 19:50:00 -0700947 }
948 }
949
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700950 private void cancelJobsForNonExistentUsers() {
951 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
952 synchronized (mLock) {
953 mJobs.removeJobsOfNonUsers(umi.getUserIds());
954 }
955 }
956
Makoto Onukie7b96182017-08-30 14:53:16 -0700957 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
958 if ("android".equals(pkgName)) {
959 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
960 return;
961 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700962 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700963 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
964 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
965 final JobStatus job = jobsForUid.get(i);
966 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700967 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700968 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700969 }
970 }
971 }
972
Christopher Tate7060b042014-06-09 19:50:00 -0700973 /**
974 * Entry point from client to cancel all jobs originating from their uid.
975 * This will remove the job from the master list, and cancel the job if it was staged for
976 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700977 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800978 *
Christopher Tate7060b042014-06-09 19:50:00 -0700979 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700980 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700981 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700982 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700983 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700984 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700985
986 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800987 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700988 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
989 for (int i=0; i<jobsForUid.size(); i++) {
990 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700991 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700992 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700993 }
Christopher Tate7060b042014-06-09 19:50:00 -0700994 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700995 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700996 }
997
998 /**
999 * Entry point from client to cancel the job corresponding to the jobId provided.
1000 * This will remove the job from the master list, and cancel the job if it was staged for
1001 * execution or being executed.
1002 * @param uid Uid of the calling client.
1003 * @param jobId Id of the job, provided at schedule-time.
1004 */
Makoto Onukid2bfec62018-01-12 13:58:01 -08001005 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -07001006 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001007 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -07001008 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001009 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -08001010 cancelJobImplLocked(toCancel, null,
1011 "cancel() called by app, callingUid=" + callingUid
1012 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001013 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001014 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -07001015 }
1016 }
1017
Christopher Tate44b50852018-10-05 15:53:50 -07001018 /**
1019 * Cancel the given job, stopping it if it's currently executing. If {@code incomingJob}
1020 * is null, the cancelled job is removed outright from the system. If
1021 * {@code incomingJob} is non-null, it replaces {@code cancelled} in the store of
1022 * currently scheduled jobs.
1023 */
Dianne Hackborn729a3282017-06-09 16:06:01 -07001024 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001025 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
1026 cancelled.unprepareLocked(ActivityManager.getService());
1027 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
1028 // Remove from pending queue.
1029 if (mPendingJobs.remove(cancelled)) {
1030 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -07001031 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001032 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -07001033 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Christopher Tate44b50852018-10-05 15:53:50 -07001034 // If this is a replacement, bring in the new version of the job
1035 if (incomingJob != null) {
1036 if (DEBUG) Slog.i(TAG, "Tracking replacement job " + incomingJob.toShortString());
1037 startTrackingJobLocked(incomingJob, cancelled);
1038 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001039 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001040 }
1041
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001042 void updateUidState(int uid, int procState) {
1043 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001044 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1045 // Only use this if we are exactly the top app. All others can live
1046 // with just the foreground priority. This means that persistent processes
1047 // can never be the top app priority... that is fine.
1048 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001049 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001050 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001051 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001052 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001053 }
1054 }
1055 }
1056
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001057 @Override
1058 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001059 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001060 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001061 // When becoming idle, make sure no jobs are actively running,
1062 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001063 for (int i=0; i<mActiveServices.size(); i++) {
1064 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001065 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001066 if (executing != null
1067 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001068 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1069 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001070 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001071 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001072 } else {
1073 // When coming out of idle, allow thing to start back up.
1074 if (mReadyToRock) {
1075 if (mLocalDeviceIdleController != null) {
1076 if (!mReportedActive) {
1077 mReportedActive = true;
1078 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001079 }
1080 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001081 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001082 }
1083 }
1084 }
1085 }
1086
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001087 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001088 // active is true if pending queue contains jobs OR some job is running.
1089 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001090 if (mPendingJobs.size() <= 0) {
1091 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001092 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001093 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001094 if (job != null
1095 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
Christopher Tate20afddd2018-02-28 15:19:19 -08001096 && !job.dozeWhitelisted
1097 && !job.uidActive) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001098 // We will report active if we have a job running and it is not an exception
1099 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001100 active = true;
1101 break;
1102 }
1103 }
1104 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001105
1106 if (mReportedActive != active) {
1107 mReportedActive = active;
1108 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001109 mLocalDeviceIdleController.setJobsActive(active);
1110 }
1111 }
1112 }
1113
Christopher Tated117b292018-01-05 17:32:36 -08001114 void reportAppUsage(String packageName, int userId) {
1115 // This app just transitioned into interactive use or near equivalent, so we should
1116 // take a look at its job state for feedback purposes.
1117 }
1118
Christopher Tate7060b042014-06-09 19:50:00 -07001119 /**
1120 * Initializes the system service.
1121 * <p>
1122 * Subclasses must define a single argument constructor that accepts the context
1123 * and passes it to super.
1124 * </p>
1125 *
1126 * @param context The system server context.
1127 */
1128 public JobSchedulerService(Context context) {
1129 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001130
1131 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Makoto Onuki15407842018-01-19 14:23:11 -08001132 mActivityManagerInternal = Preconditions.checkNotNull(
1133 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001134
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001135 mHandler = new JobHandler(context.getMainLooper());
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001136 mConstants = new Constants();
1137 mConstantsObserver = new ConstantsObserver(mHandler);
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001138 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001139
1140 // Set up the app standby bucketing tracker
Christopher Tated1aebb32018-01-31 13:24:14 -08001141 mStandbyTracker = new StandbyTracker();
1142 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1143 mUsageStats.addAppIdleStateChangeListener(mStandbyTracker);
Christopher Tatea732f012017-10-26 17:26:53 -07001144
1145 // The job store needs to call back
1146 publishLocalService(JobSchedulerInternal.class, new LocalService());
1147
1148 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001149 mJobs = JobStore.initAndGet(this);
1150
Christopher Tate7060b042014-06-09 19:50:00 -07001151 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001152 mControllers = new ArrayList<StateController>();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001153 mControllers.add(new ConnectivityController(this));
1154 mControllers.add(new TimeController(this));
1155 mControllers.add(new IdleController(this));
1156 mBatteryController = new BatteryController(this);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001157 mControllers.add(mBatteryController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001158 mStorageController = new StorageController(this);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001159 mControllers.add(mStorageController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001160 mControllers.add(new BackgroundJobsController(this));
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001161 mControllers.add(new ContentObserverController(this));
1162 mDeviceIdleJobsController = new DeviceIdleJobsController(this);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001163 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001164
1165 // If the job store determined that it can't yet reschedule persisted jobs,
1166 // we need to start watching the clock.
1167 if (!mJobs.jobTimesInflatedValid()) {
1168 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1169 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1170 }
Christopher Tate7060b042014-06-09 19:50:00 -07001171 }
1172
Christopher Tate616541d2017-07-26 14:27:38 -07001173 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1174 @Override
1175 public void onReceive(Context context, Intent intent) {
1176 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1177 // When we reach clock sanity, recalculate the temporal windows
1178 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001179 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001180 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1181
1182 // We've done our job now, so stop watching the time.
1183 context.unregisterReceiver(this);
1184
1185 // And kick off the work to update the affected jobs, using a secondary
1186 // thread instead of chugging away here on the main looper thread.
1187 FgThread.getHandler().post(mJobTimeUpdater);
1188 }
1189 }
1190 }
1191 };
1192
1193 private final Runnable mJobTimeUpdater = () -> {
1194 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1195 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1196 synchronized (mLock) {
1197 // Note: we intentionally both look up the existing affected jobs and replace them
1198 // with recalculated ones inside the same lock lifetime.
1199 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1200
1201 // Now, at each position [i], we have both the existing JobStatus
1202 // and the one that replaces it.
1203 final int N = toAdd.size();
1204 for (int i = 0; i < N; i++) {
1205 final JobStatus oldJob = toRemove.get(i);
1206 final JobStatus newJob = toAdd.get(i);
1207 if (DEBUG) {
1208 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1209 }
1210 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1211 }
1212 }
1213 };
1214
Christopher Tate7060b042014-06-09 19:50:00 -07001215 @Override
1216 public void onStart() {
1217 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1218 }
1219
1220 @Override
1221 public void onBootPhase(int phase) {
1222 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001223 mConstantsObserver.start(getContext().getContentResolver());
Makoto Onuki15407842018-01-19 14:23:11 -08001224
Makoto Onukie4918212018-02-06 11:30:15 -08001225 mAppStateTracker = Preconditions.checkNotNull(
1226 LocalServices.getService(AppStateTracker.class));
Christopher Tated1aebb32018-01-31 13:24:14 -08001227 setNextHeartbeatAlarm();
Makoto Onuki15407842018-01-19 14:23:11 -08001228
Shreyas Basarge5db09082016-01-07 13:38:29 +00001229 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001230 final IntentFilter filter = new IntentFilter();
1231 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1232 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001233 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1234 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001235 filter.addDataScheme("package");
1236 getContext().registerReceiverAsUser(
1237 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1238 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1239 getContext().registerReceiverAsUser(
1240 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001241 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001242 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001243 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001244 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1245 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001246 } catch (RemoteException e) {
1247 // ignored; both services live in system_server
1248 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001249 // Remove any jobs that are not associated with any of the current users.
1250 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001251 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001252 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001253 // Let's go!
1254 mReadyToRock = true;
1255 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1256 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001257 mLocalDeviceIdleController
1258 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001259 // Create the "runners".
1260 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1261 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001262 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001263 getContext().getMainLooper()));
1264 }
1265 // Attach jobs to their controllers.
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001266 mJobs.forEachJob((job) -> {
1267 for (int controller = 0; controller < mControllers.size(); controller++) {
1268 final StateController sc = mControllers.get(controller);
1269 sc.maybeStartTrackingJobLocked(job, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001270 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001271 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001272 // GO GO GO!
1273 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1274 }
Christopher Tate7060b042014-06-09 19:50:00 -07001275 }
1276 }
1277
1278 /**
1279 * Called when we have a job status object that we need to insert in our
1280 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1281 * about.
1282 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001283 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1284 if (!jobStatus.isPreparedLocked()) {
1285 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1286 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001287 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001288 final boolean update = mJobs.add(jobStatus);
1289 if (mReadyToRock) {
1290 for (int i = 0; i < mControllers.size(); i++) {
1291 StateController controller = mControllers.get(i);
1292 if (update) {
1293 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001294 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001295 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001296 }
Christopher Tate7060b042014-06-09 19:50:00 -07001297 }
1298 }
1299
1300 /**
1301 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1302 * object removed.
1303 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001304 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001305 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001306 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001307 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001308
1309 // Remove from store as well as controllers.
1310 final boolean removed = mJobs.remove(jobStatus, writeBack);
1311 if (removed && mReadyToRock) {
1312 for (int i=0; i<mControllers.size(); i++) {
1313 StateController controller = mControllers.get(i);
1314 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001315 }
1316 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001317 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001318 }
1319
Dianne Hackborn729a3282017-06-09 16:06:01 -07001320 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001321 for (int i=0; i<mActiveServices.size(); i++) {
1322 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001323 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001324 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001325 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001326 return true;
1327 }
1328 }
1329 return false;
1330 }
1331
1332 /**
1333 * @param job JobStatus we are querying against.
1334 * @return Whether or not the job represented by the status object is currently being run or
1335 * is pending.
1336 */
1337 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001338 for (int i=0; i<mActiveServices.size(); i++) {
1339 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001340 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001341 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1342 return true;
1343 }
1344 }
1345 return false;
1346 }
1347
Dianne Hackborn807de782016-04-07 17:54:41 -07001348 void noteJobsPending(List<JobStatus> jobs) {
1349 for (int i = jobs.size() - 1; i >= 0; i--) {
1350 JobStatus job = jobs.get(i);
1351 mJobPackageTracker.notePending(job);
1352 }
1353 }
1354
1355 void noteJobsNonpending(List<JobStatus> jobs) {
1356 for (int i = jobs.size() - 1; i >= 0; i--) {
1357 JobStatus job = jobs.get(i);
1358 mJobPackageTracker.noteNonpending(job);
1359 }
1360 }
1361
Christopher Tate7060b042014-06-09 19:50:00 -07001362 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001363 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1364 * specify an override deadline on a failed job (the failed job will run even though it's not
1365 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1366 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1367 *
Christopher Tate7060b042014-06-09 19:50:00 -07001368 * @param failureToReschedule Provided job status that we will reschedule.
1369 * @return A newly instantiated JobStatus with the same constraints as the last job except
1370 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001371 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001372 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001373 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001374 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001375 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001376 final JobInfo job = failureToReschedule.getJob();
1377
1378 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001379 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1380 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001381
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001382 if (failureToReschedule.hasWorkLocked()) {
1383 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1384 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1385 + backoffAttempts + " > work limit "
1386 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1387 return null;
1388 }
1389 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1390 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1391 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1392 return null;
1393 }
1394
Christopher Tate7060b042014-06-09 19:50:00 -07001395 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001396 case JobInfo.BACKOFF_POLICY_LINEAR: {
1397 long backoff = initialBackoffMillis;
1398 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1399 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1400 }
1401 delayMillis = backoff * backoffAttempts;
1402 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001403 default:
1404 if (DEBUG) {
1405 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1406 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001407 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1408 long backoff = initialBackoffMillis;
1409 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1410 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1411 }
1412 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1413 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001414 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001415 delayMillis =
1416 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001417 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1418 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001419 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001420 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001421 for (int ic=0; ic<mControllers.size(); ic++) {
1422 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001423 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001424 }
1425 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001426 }
1427
1428 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001429 * Called after a periodic has executed so we can reschedule it. We take the last execution
1430 * time of the job to be the time of completion (i.e. the time at which this function is
1431 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001432 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001433 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1434 * to underscheduling at least, rather than if we had taken the last execution time to be the
1435 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001436 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1437 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001438 * @return A new job representing the execution criteria for this instantiation of the
1439 * recurring job.
1440 */
1441 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001442 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001443 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001444 long runEarly = 0L;
1445
1446 // If this periodic was rescheduled it won't have a deadline.
1447 if (periodicToReschedule.hasDeadlineConstraint()) {
1448 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1449 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001450 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001451 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001452 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1453 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001454
1455 if (DEBUG) {
1456 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1457 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1458 }
Christopher Tatea732f012017-10-26 17:26:53 -07001459 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1460 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1461 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001462 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001463 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001464 }
1465
Christopher Tate325768c2018-03-07 16:07:56 -08001466 /*
1467 * We default to "long enough ago that every bucket's jobs are immediately runnable" to
1468 * avoid starvation of apps in uncommon-use buckets that might arise from repeated
1469 * reboot behavior.
1470 */
Christopher Tated1aebb32018-01-31 13:24:14 -08001471 long heartbeatWhenJobsLastRun(String packageName, final @UserIdInt int userId) {
Christopher Tate325768c2018-03-07 16:07:56 -08001472 // The furthest back in pre-boot time that we need to bother with
1473 long heartbeat = -mConstants.STANDBY_BEATS[RARE_INDEX];
1474 boolean cacheHit = false;
Christopher Tated1aebb32018-01-31 13:24:14 -08001475 synchronized (mLock) {
Christopher Tate325768c2018-03-07 16:07:56 -08001476 HashMap<String, Long> jobPackages = mLastJobHeartbeats.get(userId);
1477 if (jobPackages != null) {
1478 long cachedValue = jobPackages.getOrDefault(packageName, Long.MAX_VALUE);
1479 if (cachedValue < Long.MAX_VALUE) {
1480 cacheHit = true;
1481 heartbeat = cachedValue;
1482 }
1483 }
1484 if (!cacheHit) {
1485 // We haven't seen it yet; ask usage stats about it
1486 final long timeSinceJob = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
1487 if (timeSinceJob < Long.MAX_VALUE) {
1488 // Usage stats knows about it from before, so calculate back from that
1489 // and go from there.
1490 heartbeat = mHeartbeat - (timeSinceJob / mConstants.STANDBY_HEARTBEAT_TIME);
1491 }
1492 // If usage stats returned its "not found" MAX_VALUE, we still have the
1493 // negative default 'heartbeat' value we established above
1494 setLastJobHeartbeatLocked(packageName, userId, heartbeat);
1495 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001496 }
1497 if (DEBUG_STANDBY) {
Christopher Tate325768c2018-03-07 16:07:56 -08001498 Slog.v(TAG, "Last job heartbeat " + heartbeat + " for "
1499 + packageName + "/" + userId);
Christopher Tated1aebb32018-01-31 13:24:14 -08001500 }
1501 return heartbeat;
1502 }
1503
1504 long heartbeatWhenJobsLastRun(JobStatus job) {
1505 return heartbeatWhenJobsLastRun(job.getSourcePackageName(), job.getSourceUserId());
1506 }
1507
Christopher Tate325768c2018-03-07 16:07:56 -08001508 void setLastJobHeartbeatLocked(String packageName, int userId, long heartbeat) {
1509 HashMap<String, Long> jobPackages = mLastJobHeartbeats.get(userId);
1510 if (jobPackages == null) {
1511 jobPackages = new HashMap<>();
1512 mLastJobHeartbeats.put(userId, jobPackages);
1513 }
1514 jobPackages.put(packageName, heartbeat);
1515 }
1516
Christopher Tate7060b042014-06-09 19:50:00 -07001517 // JobCompletedListener implementations.
1518
1519 /**
1520 * A job just finished executing. We fetch the
1521 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
Christopher Tate325768c2018-03-07 16:07:56 -08001522 * whether we want to reschedule we re-add it to the controllers.
Christopher Tate7060b042014-06-09 19:50:00 -07001523 * @param jobStatus Completed job.
1524 * @param needsReschedule Whether the implementing class should reschedule this job.
1525 */
1526 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001527 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001528 if (DEBUG) {
1529 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1530 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001531
1532 // If the job wants to be rescheduled, we first need to make the next upcoming
1533 // job so we can transfer any appropriate state over from the previous job when
1534 // we stop it.
1535 final JobStatus rescheduledJob = needsReschedule
1536 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1537
Shreyas Basarge73f10252016-02-11 17:06:13 +00001538 // Do not write back immediately if this is a periodic job. The job may get lost if system
1539 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001540 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001541 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001542 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001543 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001544 // We still want to check for jobs to execute, because this job may have
1545 // scheduled a new job under the same job id, and now we can run it.
1546 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001547 return;
1548 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001549
1550 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001551 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001552 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001553 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001554 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001555 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001556 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001557 } else if (jobStatus.getJob().isPeriodic()) {
1558 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001559 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001560 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001561 } catch (SecurityException e) {
1562 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1563 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001564 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001565 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001566 jobStatus.unprepareLocked(ActivityManager.getService());
1567 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001568 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001569 }
1570
1571 // StateChangedListener implementations.
1572
1573 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001574 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1575 * some controller's state has changed, so as to run through the list of jobs and start/stop
1576 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001577 */
1578 @Override
1579 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001580 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001581 }
1582
1583 @Override
1584 public void onRunJobNow(JobStatus jobStatus) {
1585 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1586 }
1587
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001588 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001589
1590 public JobHandler(Looper looper) {
1591 super(looper);
1592 }
1593
1594 @Override
1595 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001596 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001597 if (!mReadyToRock) {
1598 return;
1599 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001600 switch (message.what) {
1601 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001602 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001603 // runNow can be null, which is a controller's way of indicating that its
1604 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001605 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001606 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001607 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001608 } else {
1609 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001610 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001611 } break;
1612 case MSG_CHECK_JOB:
Kulwinder Singhde0a0152018-08-31 13:14:03 +05301613 removeMessages(MSG_CHECK_JOB);
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001614 if (mReportedActive) {
1615 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001616 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001617 } else {
1618 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001619 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001620 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001621 break;
1622 case MSG_CHECK_JOB_GREEDY:
1623 queueReadyJobsForExecutionLocked();
1624 break;
1625 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001626 cancelJobImplLocked((JobStatus) message.obj, null,
1627 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001628 break;
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001629
1630 case MSG_UID_STATE_CHANGED: {
1631 final int uid = message.arg1;
1632 final int procState = message.arg2;
1633 updateUidState(uid, procState);
1634 break;
1635 }
1636 case MSG_UID_GONE: {
1637 final int uid = message.arg1;
1638 final boolean disabled = message.arg2 != 0;
1639 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1640 if (disabled) {
1641 cancelJobsForUid(uid, "uid gone");
1642 }
1643 synchronized (mLock) {
1644 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1645 }
1646 break;
1647 }
1648 case MSG_UID_ACTIVE: {
1649 final int uid = message.arg1;
1650 synchronized (mLock) {
1651 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
1652 }
1653 break;
1654 }
1655 case MSG_UID_IDLE: {
1656 final int uid = message.arg1;
1657 final boolean disabled = message.arg2 != 0;
1658 if (disabled) {
1659 cancelJobsForUid(uid, "app uid idle");
1660 }
1661 synchronized (mLock) {
1662 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1663 }
1664 break;
1665 }
1666
Matthew Williams75fc5252014-09-02 16:17:53 -07001667 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001668 maybeRunPendingJobsLocked();
1669 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
Christopher Tate7060b042014-06-09 19:50:00 -07001670 }
1671 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001672 }
Christopher Tate7060b042014-06-09 19:50:00 -07001673
Dianne Hackborn6d068262017-05-16 13:14:37 -07001674 private void stopNonReadyActiveJobsLocked() {
1675 for (int i=0; i<mActiveServices.size(); i++) {
1676 JobServiceContext serviceContext = mActiveServices.get(i);
1677 final JobStatus running = serviceContext.getRunningJobLocked();
1678 if (running != null && !running.isReady()) {
1679 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001680 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1681 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001682 }
1683 }
1684 }
1685
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001686 /**
1687 * Run through list of jobs and execute all possible - at least one is expired so we do
1688 * as many as we can.
1689 */
1690 private void queueReadyJobsForExecutionLocked() {
1691 if (DEBUG) {
1692 Slog.d(TAG, "queuing all ready jobs for execution:");
1693 }
1694 noteJobsNonpending(mPendingJobs);
1695 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001696 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001697 mJobs.forEachJob(mReadyQueueFunctor);
1698 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001699
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001700 if (DEBUG) {
1701 final int queuedJobs = mPendingJobs.size();
1702 if (queuedJobs == 0) {
1703 Slog.d(TAG, "No jobs pending.");
1704 } else {
1705 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001706 }
1707 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001708 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001709
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001710 final class ReadyJobQueueFunctor implements Consumer<JobStatus> {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001711 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001712
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001713 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001714 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001715 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001716 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001717 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001718 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001719 if (newReadyJobs == null) {
1720 newReadyJobs = new ArrayList<JobStatus>();
1721 }
1722 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001723 }
1724 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001725
1726 public void postProcess() {
1727 if (newReadyJobs != null) {
1728 noteJobsPending(newReadyJobs);
1729 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001730 if (mPendingJobs.size() > 1) {
1731 mPendingJobs.sort(mEnqueueTimeComparator);
1732 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001733 }
1734 newReadyJobs = null;
1735 }
1736 }
1737 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1738
1739 /**
1740 * The state of at least one job has changed. Here is where we could enforce various
1741 * policies on when we want to execute jobs.
1742 * Right now the policy is such:
1743 * If >1 of the ready jobs is idle mode we send all of them off
1744 * if more than 2 network connectivity jobs are ready we send them all off.
1745 * If more than 4 jobs total are ready we send them all off.
1746 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1747 */
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001748 final class MaybeReadyJobQueueFunctor implements Consumer<JobStatus> {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001749 int chargingCount;
1750 int batteryNotLowCount;
1751 int storageNotLowCount;
1752 int idleCount;
1753 int backoffCount;
1754 int connectivityCount;
1755 int contentCount;
1756 List<JobStatus> runnableJobs;
1757
1758 public MaybeReadyJobQueueFunctor() {
1759 reset();
1760 }
1761
1762 // Functor method invoked for each job via JobStore.forEachJob()
1763 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001764 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001765 if (isReadyToBeExecutedLocked(job)) {
1766 try {
1767 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1768 job.getJob().getService().getPackageName())) {
1769 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1770 + job.getJob().toString() + " -- package not allowed to start");
1771 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1772 return;
1773 }
1774 } catch (RemoteException e) {
1775 }
1776 if (job.getNumFailures() > 0) {
1777 backoffCount++;
1778 }
1779 if (job.hasIdleConstraint()) {
1780 idleCount++;
1781 }
1782 if (job.hasConnectivityConstraint()) {
1783 connectivityCount++;
1784 }
1785 if (job.hasChargingConstraint()) {
1786 chargingCount++;
1787 }
1788 if (job.hasBatteryNotLowConstraint()) {
1789 batteryNotLowCount++;
1790 }
1791 if (job.hasStorageNotLowConstraint()) {
1792 storageNotLowCount++;
1793 }
1794 if (job.hasContentTriggerConstraint()) {
1795 contentCount++;
1796 }
1797 if (runnableJobs == null) {
1798 runnableJobs = new ArrayList<>();
1799 }
1800 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001801 }
1802 }
1803
1804 public void postProcess() {
1805 if (backoffCount > 0 ||
1806 idleCount >= mConstants.MIN_IDLE_COUNT ||
1807 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1808 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1809 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1810 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1811 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1812 (runnableJobs != null
1813 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1814 if (DEBUG) {
1815 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1816 }
1817 noteJobsPending(runnableJobs);
1818 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001819 if (mPendingJobs.size() > 1) {
1820 mPendingJobs.sort(mEnqueueTimeComparator);
1821 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001822 } else {
1823 if (DEBUG) {
1824 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1825 }
1826 }
1827
1828 // Be ready for next time
1829 reset();
1830 }
1831
1832 private void reset() {
1833 chargingCount = 0;
1834 idleCount = 0;
1835 backoffCount = 0;
1836 connectivityCount = 0;
1837 batteryNotLowCount = 0;
1838 storageNotLowCount = 0;
1839 contentCount = 0;
1840 runnableJobs = null;
1841 }
1842 }
1843 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1844
1845 private void maybeQueueReadyJobsForExecutionLocked() {
1846 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1847
1848 noteJobsNonpending(mPendingJobs);
1849 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001850 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001851 mJobs.forEachJob(mMaybeQueueFunctor);
1852 mMaybeQueueFunctor.postProcess();
1853 }
1854
Christopher Tated1aebb32018-01-31 13:24:14 -08001855 /**
1856 * Heartbeat tracking. The heartbeat alarm is intentionally non-wakeup.
1857 */
1858 class HeartbeatAlarmListener implements AlarmManager.OnAlarmListener {
1859
1860 @Override
1861 public void onAlarm() {
1862 synchronized (mLock) {
1863 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1864 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1865 if (beatsElapsed > 0) {
1866 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1867 advanceHeartbeatLocked(beatsElapsed);
1868 }
Christopher Tatea732f012017-10-26 17:26:53 -07001869 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001870 setNextHeartbeatAlarm();
Christopher Tatea732f012017-10-26 17:26:53 -07001871 }
Christopher Tatea732f012017-10-26 17:26:53 -07001872 }
1873
Christopher Tated1aebb32018-01-31 13:24:14 -08001874 // Intentionally does not touch the alarm timing
1875 void advanceHeartbeatLocked(long beatsElapsed) {
1876 mHeartbeat += beatsElapsed;
1877 if (DEBUG_STANDBY) {
1878 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed
1879 + " to " + mHeartbeat);
1880 }
1881 // Don't update ACTIVE or NEVER bucket milestones. Note that mHeartbeat
1882 // will be equal to mNextBucketHeartbeat[bucket] for one beat, during which
1883 // new jobs scheduled by apps in that bucket will be permitted to run
1884 // immediately.
1885 boolean didAdvanceBucket = false;
Christopher Tatea732f012017-10-26 17:26:53 -07001886 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
Christopher Tated1aebb32018-01-31 13:24:14 -08001887 // Did we reach or cross a bucket boundary?
1888 if (mHeartbeat >= mNextBucketHeartbeat[i]) {
1889 didAdvanceBucket = true;
1890 }
1891 while (mHeartbeat > mNextBucketHeartbeat[i]) {
Christopher Tatea732f012017-10-26 17:26:53 -07001892 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1893 }
1894 if (DEBUG_STANDBY) {
Christopher Tated1aebb32018-01-31 13:24:14 -08001895 Slog.v(TAG, " Bucket " + i + " next heartbeat "
1896 + mNextBucketHeartbeat[i]);
Christopher Tatea732f012017-10-26 17:26:53 -07001897 }
1898 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001899
1900 if (didAdvanceBucket) {
1901 if (DEBUG_STANDBY) {
1902 Slog.v(TAG, "Hit bucket boundary; reevaluating job runnability");
1903 }
1904 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1905 }
1906 }
1907
1908 void setNextHeartbeatAlarm() {
1909 final long heartbeatLength;
1910 synchronized (mLock) {
1911 heartbeatLength = mConstants.STANDBY_HEARTBEAT_TIME;
1912 }
1913 final long now = sElapsedRealtimeClock.millis();
1914 final long nextBeatOrdinal = (now + heartbeatLength) / heartbeatLength;
1915 final long nextHeartbeat = nextBeatOrdinal * heartbeatLength;
1916 if (DEBUG_STANDBY) {
1917 Slog.i(TAG, "Setting heartbeat alarm for " + nextHeartbeat
1918 + " = " + TimeUtils.formatDuration(nextHeartbeat - now));
1919 }
1920 AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1921 am.setExact(AlarmManager.ELAPSED_REALTIME, nextHeartbeat,
1922 HEARTBEAT_TAG, mHeartbeatAlarm, mHandler);
Christopher Tatea732f012017-10-26 17:26:53 -07001923 }
1924
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001925 /**
1926 * Criteria for moving a job into the pending queue:
1927 * - It's ready.
1928 * - It's not pending.
1929 * - It's not already running on a JSC.
1930 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001931 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001932 * - The component is enabled and runnable.
1933 */
1934 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001935 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001936
1937 if (DEBUG) {
1938 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1939 + " ready=" + jobReady);
1940 }
1941
1942 // This is a condition that is very likely to be false (most jobs that are
1943 // scheduled are sitting there, not ready yet) and very cheap to check (just
1944 // a few conditions on data in JobStatus).
1945 if (!jobReady) {
Christopher Tate20afddd2018-02-28 15:19:19 -08001946 if (job.getSourcePackageName().equals("android.jobscheduler.cts.jobtestapp")) {
1947 Slog.v(TAG, " NOT READY: " + job);
1948 }
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001949 return false;
1950 }
1951
1952 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001953
1954 final int userId = job.getUserId();
1955 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1956
1957 if (DEBUG) {
1958 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001959 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001960 }
1961
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001962 // These are also fairly cheap to check, though they typically will not
1963 // be conditions we fail.
1964 if (!jobExists || !userStarted) {
1965 return false;
1966 }
1967
1968 final boolean jobPending = mPendingJobs.contains(job);
1969 final boolean jobActive = isCurrentlyActiveLocked(job);
1970
1971 if (DEBUG) {
1972 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1973 + " pending=" + jobPending + " active=" + jobActive);
1974 }
1975
1976 // These can be a little more expensive (especially jobActive, since we need to
1977 // go through the array of all potentially active jobs), so we are doing them
1978 // later... but still before checking with the package manager!
1979 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001980 return false;
1981 }
1982
Christopher Tatea732f012017-10-26 17:26:53 -07001983 // If the app is in a non-active standby bucket, make sure we've waited
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001984 // an appropriate amount of time since the last invocation. During device-
1985 // wide parole, standby bucketing is ignored.
Makoto Onuki959acb52018-01-26 14:10:03 -08001986 //
Christopher Tate20afddd2018-02-28 15:19:19 -08001987 // Jobs in 'active' apps are not subject to standby, nor are jobs that are
1988 // specifically marked as exempt.
1989 if (DEBUG_STANDBY) {
1990 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1991 + " parole=" + mInParole + " active=" + job.uidActive
1992 + " exempt=" + job.getJob().isExemptedFromAppStandby());
1993 }
1994 if (!mInParole
1995 && !job.uidActive
1996 && !job.getJob().isExemptedFromAppStandby()) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001997 final int bucket = job.getStandbyBucket();
Christopher Tate20afddd2018-02-28 15:19:19 -08001998 if (DEBUG_STANDBY) {
1999 Slog.v(TAG, " bucket=" + bucket + " heartbeat=" + mHeartbeat
2000 + " next=" + mNextBucketHeartbeat[bucket]);
2001 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002002 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
Christopher Tated1aebb32018-01-31 13:24:14 -08002003 // Only skip this job if the app is still waiting for the end of its nominal
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002004 // bucket interval. Once it's waited that long, we let it go ahead and clear.
2005 // The final (NEVER) bucket is special; we never age those apps' jobs into
2006 // runnability.
Christopher Tated1aebb32018-01-31 13:24:14 -08002007 final long appLastRan = heartbeatWhenJobsLastRun(job);
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002008 if (bucket >= mConstants.STANDBY_BEATS.length
Christopher Tated1aebb32018-01-31 13:24:14 -08002009 || (mHeartbeat > appLastRan
2010 && mHeartbeat < appLastRan + mConstants.STANDBY_BEATS[bucket])) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002011 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
2012 if (job.getWhenStandbyDeferred() == 0) {
2013 if (DEBUG_STANDBY) {
2014 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
Christopher Tated1aebb32018-01-31 13:24:14 -08002015 + (appLastRan + mConstants.STANDBY_BEATS[bucket])
2016 + " for " + job);
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002017 }
2018 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tate0c4d7682017-12-06 15:10:22 -08002019 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002020 return false;
2021 } else {
2022 if (DEBUG_STANDBY) {
2023 Slog.v(TAG, "Bucket deferred job aged into runnability at "
2024 + mHeartbeat + " : " + job);
2025 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08002026 }
Christopher Tatea732f012017-10-26 17:26:53 -07002027 }
Christopher Tatea732f012017-10-26 17:26:53 -07002028 }
2029
2030 // The expensive check last: validate that the defined package+service is
2031 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002032 final boolean componentPresent;
2033 try {
2034 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2035 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2036 userId) != null);
2037 } catch (RemoteException e) {
2038 throw e.rethrowAsRuntimeException();
2039 }
2040
2041 if (DEBUG) {
2042 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2043 + " componentPresent=" + componentPresent);
2044 }
2045
2046 // Everything else checked out so far, so this is the final yes/no check
2047 return componentPresent;
2048 }
2049
2050 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002051 * Reconcile jobs in the pending queue against available execution contexts.
2052 * A controller can force a job into the pending queue even if it's already running, but
2053 * here is where we decide whether to actually execute it.
2054 */
2055 private void maybeRunPendingJobsLocked() {
2056 if (DEBUG) {
2057 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
2058 }
2059 assignJobsToContextsLocked();
2060 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07002061 }
2062
Dianne Hackborn807de782016-04-07 17:54:41 -07002063 private int adjustJobPriority(int curPriority, JobStatus job) {
2064 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
2065 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002066 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002067 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002068 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002069 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
2070 }
2071 }
2072 return curPriority;
2073 }
2074
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002075 private int evaluateJobPriorityLocked(JobStatus job) {
2076 int priority = job.getPriority();
2077 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002078 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002079 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002080 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
2081 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002082 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002083 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002084 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002085 }
2086
Christopher Tate7060b042014-06-09 19:50:00 -07002087 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00002088 * Takes jobs from pending queue and runs them on available contexts.
2089 * If no contexts are available, preempts lower priority jobs to
2090 * run higher priority ones.
2091 * Lock on mJobs before calling this function.
2092 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08002093 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002094 if (DEBUG) {
2095 Slog.d(TAG, printPendingQueue());
2096 }
2097
Dianne Hackborn970510b2016-02-24 16:56:42 -08002098 int memLevel;
2099 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002100 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002101 } catch (RemoteException e) {
2102 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
2103 }
2104 switch (memLevel) {
2105 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002106 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002107 break;
2108 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002109 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002110 break;
2111 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002112 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002113 break;
2114 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002115 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002116 break;
2117 }
2118
2119 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
2120 boolean[] act = mTmpAssignAct;
2121 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
2122 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002123 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002124 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
2125 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002126 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002127 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002128 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002129 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
2130 numForeground++;
2131 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002132 }
2133 act[i] = false;
2134 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002135 }
2136 if (DEBUG) {
2137 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
2138 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002139 for (int i=0; i<mPendingJobs.size(); i++) {
2140 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002141
2142 // If job is already running, go to next job.
2143 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
2144 if (jobRunningContext != -1) {
2145 continue;
2146 }
2147
Dianne Hackborn970510b2016-02-24 16:56:42 -08002148 final int priority = evaluateJobPriorityLocked(nextPending);
2149 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002150
Shreyas Basarge5db09082016-01-07 13:38:29 +00002151 // Find a context for nextPending. The context should be available OR
2152 // it should have lowest priority among all running jobs
2153 // (sharing the same Uid as nextPending)
2154 int minPriority = Integer.MAX_VALUE;
2155 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002156 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
2157 JobStatus job = contextIdToJobMap[j];
2158 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00002159 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002160 if ((numActive < mMaxActiveJobs ||
2161 (priority >= JobInfo.PRIORITY_TOP_APP &&
2162 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08002163 (preferredUid == nextPending.getUid() ||
2164 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
2165 // This slot is free, and we haven't yet hit the limit on
2166 // concurrent jobs... we can just throw the job in to here.
2167 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002168 break;
2169 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00002170 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08002171 // the context has a preferred Uid or we have reached the limit on
2172 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00002173 continue;
2174 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002175 if (job.getUid() != nextPending.getUid()) {
2176 continue;
2177 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002178 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002179 continue;
2180 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002181 if (minPriority > nextPending.lastEvaluatedPriority) {
2182 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002183 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00002184 }
2185 }
2186 if (minPriorityContextId != -1) {
2187 contextIdToJobMap[minPriorityContextId] = nextPending;
2188 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002189 numActive++;
2190 if (priority >= JobInfo.PRIORITY_TOP_APP) {
2191 numForeground++;
2192 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002193 }
2194 }
2195 if (DEBUG) {
2196 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
2197 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002198 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002199 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002200 boolean preservePreferredUid = false;
2201 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002202 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002203 if (js != null) {
2204 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002205 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00002206 }
2207 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07002208 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002209 preservePreferredUid = true;
2210 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002211 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00002212 if (DEBUG) {
2213 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002214 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002215 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002216 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002217 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002218 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002219 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
2220 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002221 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002222 if (mPendingJobs.remove(pendingJob)) {
2223 mJobPackageTracker.noteNonpending(pendingJob);
2224 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002225 }
2226 }
2227 if (!preservePreferredUid) {
2228 mActiveServices.get(i).clearPreferredUid();
2229 }
2230 }
2231 }
2232
2233 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
2234 for (int i=0; i<map.length; i++) {
2235 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
2236 return i;
2237 }
2238 }
2239 return -1;
2240 }
2241
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002242 final class LocalService implements JobSchedulerInternal {
2243
2244 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002245 * The current bucket heartbeat ordinal
2246 */
2247 public long currentHeartbeat() {
2248 return getCurrentHeartbeat();
2249 }
2250
2251 /**
2252 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2253 */
2254 public long nextHeartbeatForBucket(int bucket) {
2255 synchronized (mLock) {
2256 return mNextBucketHeartbeat[bucket];
2257 }
2258 }
2259
2260 /**
Christopher Tate435c2f42018-01-18 12:59:15 -08002261 * Heartbeat ordinal for the given app. This is typically the heartbeat at which
2262 * the app last ran jobs, so that a newly-scheduled job in an app that hasn't run
2263 * jobs in a long time is immediately runnable even if the app is bucketed into
2264 * an infrequent time allocation.
2265 */
2266 public long baseHeartbeatForApp(String packageName, @UserIdInt int userId,
2267 final int appStandbyBucket) {
2268 if (appStandbyBucket == 0 ||
2269 appStandbyBucket >= mConstants.STANDBY_BEATS.length) {
2270 // ACTIVE => everything can be run right away
2271 // NEVER => we won't run them anyway, so let them go in the future
2272 // as soon as the app enters normal use
Christopher Tated1aebb32018-01-31 13:24:14 -08002273 if (DEBUG_STANDBY) {
2274 Slog.v(TAG, "Base heartbeat forced ZERO for new job in "
2275 + packageName + "/" + userId);
2276 }
Christopher Tate435c2f42018-01-18 12:59:15 -08002277 return 0;
2278 }
2279
Christopher Tated1aebb32018-01-31 13:24:14 -08002280 final long baseHeartbeat = heartbeatWhenJobsLastRun(packageName, userId);
2281 if (DEBUG_STANDBY) {
2282 Slog.v(TAG, "Base heartbeat " + baseHeartbeat + " for new job in "
2283 + packageName + "/" + userId);
2284 }
2285 return baseHeartbeat;
Christopher Tate435c2f42018-01-18 12:59:15 -08002286 }
2287
Christopher Tate325768c2018-03-07 16:07:56 -08002288 public void noteJobStart(String packageName, int userId) {
2289 synchronized (mLock) {
2290 setLastJobHeartbeatLocked(packageName, userId, mHeartbeat);
2291 }
2292 }
2293
Christopher Tate435c2f42018-01-18 12:59:15 -08002294 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002295 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2296 * jobs are always considered pending.
2297 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002298 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002299 public List<JobInfo> getSystemScheduledPendingJobs() {
2300 synchronized (mLock) {
2301 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002302 mJobs.forEachJob(Process.SYSTEM_UID, (job) -> {
2303 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2304 pendingJobs.add(job.getJob());
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002305 }
2306 });
2307 return pendingJobs;
2308 }
2309 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002310
2311 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002312 public void cancelJobsForUid(int uid, String reason) {
2313 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2314 }
2315
2316 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002317 public void addBackingUpUid(int uid) {
2318 synchronized (mLock) {
2319 // No need to actually do anything here, since for a full backup the
2320 // activity manager will kill the process which will kill the job (and
2321 // cause it to restart, but now it can't run).
2322 mBackingUpUids.put(uid, uid);
2323 }
2324 }
2325
2326 @Override
2327 public void removeBackingUpUid(int uid) {
2328 synchronized (mLock) {
2329 mBackingUpUids.delete(uid);
2330 // If there are any jobs for this uid, we need to rebuild the pending list
2331 // in case they are now ready to run.
2332 if (mJobs.countJobsForUid(uid) > 0) {
2333 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2334 }
2335 }
2336 }
2337
2338 @Override
2339 public void clearAllBackingUpUids() {
2340 synchronized (mLock) {
2341 if (mBackingUpUids.size() > 0) {
2342 mBackingUpUids.clear();
2343 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2344 }
2345 }
2346 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002347
2348 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002349 public void reportAppUsage(String packageName, int userId) {
2350 JobSchedulerService.this.reportAppUsage(packageName, userId);
2351 }
2352
2353 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002354 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002355 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002356 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002357 }
2358 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002359 }
2360
Shreyas Basarge5db09082016-01-07 13:38:29 +00002361 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002362 * Tracking of app assignments to standby buckets
2363 */
2364 final class StandbyTracker extends AppIdleStateChangeListener {
Christopher Tate435c2f42018-01-18 12:59:15 -08002365
Christopher Tatea732f012017-10-26 17:26:53 -07002366 // AppIdleStateChangeListener interface for live updates
2367
2368 @Override
Christopher Tate435c2f42018-01-18 12:59:15 -08002369 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08002370 boolean idle, int bucket, int reason) {
Christopher Tatea732f012017-10-26 17:26:53 -07002371 final int uid = mLocalPM.getPackageUid(packageName,
2372 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2373 if (uid < 0) {
2374 if (DEBUG_STANDBY) {
2375 Slog.i(TAG, "App idle state change for unknown app "
2376 + packageName + "/" + userId);
2377 }
2378 return;
2379 }
2380
2381 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2382 // update job bookkeeping out of band
2383 BackgroundThread.getHandler().post(() -> {
2384 if (DEBUG_STANDBY) {
2385 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2386 }
2387 synchronized (mLock) {
Christopher Tate93defea2018-02-20 15:57:17 -08002388 mJobs.forEachJobForSourceUid(uid, job -> {
2389 // double-check uid vs package name to disambiguate shared uids
2390 if (packageName.equals(job.getSourcePackageName())) {
2391 job.setStandbyBucket(bucketIndex);
2392 }
2393 });
Christopher Tatea732f012017-10-26 17:26:53 -07002394 onControllerStateChanged();
2395 }
2396 });
2397 }
2398
2399 @Override
2400 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002401 if (DEBUG_STANDBY) {
2402 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2403 }
2404 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002405 }
Christopher Tated117b292018-01-05 17:32:36 -08002406
2407 @Override
2408 public void onUserInteractionStarted(String packageName, int userId) {
2409 final int uid = mLocalPM.getPackageUid(packageName,
2410 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2411 if (uid < 0) {
2412 // Quietly ignore; the case is already logged elsewhere
2413 return;
2414 }
2415
Amith Yamasani977e11f2018-02-16 11:29:54 -08002416 long sinceLast = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2417 if (sinceLast > 2 * DateUtils.DAY_IN_MILLIS) {
2418 // Too long ago, not worth logging
2419 sinceLast = 0L;
2420 }
Christopher Tated117b292018-01-05 17:32:36 -08002421 final DeferredJobCounter counter = new DeferredJobCounter();
2422 synchronized (mLock) {
2423 mJobs.forEachJobForSourceUid(uid, counter);
2424 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08002425 if (counter.numDeferred() > 0 || sinceLast > 0) {
2426 BatteryStatsInternal mBatteryStatsInternal = LocalServices.getService
2427 (BatteryStatsInternal.class);
2428 mBatteryStatsInternal.noteJobsDeferred(uid, counter.numDeferred(), sinceLast);
2429 }
Christopher Tated117b292018-01-05 17:32:36 -08002430 }
2431 }
2432
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002433 static class DeferredJobCounter implements Consumer<JobStatus> {
Christopher Tated117b292018-01-05 17:32:36 -08002434 private int mDeferred = 0;
2435
2436 public int numDeferred() {
2437 return mDeferred;
2438 }
2439
2440 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002441 public void accept(JobStatus job) {
Christopher Tated117b292018-01-05 17:32:36 -08002442 if (job.getWhenStandbyDeferred() > 0) {
2443 mDeferred++;
2444 }
2445 }
Christopher Tatea732f012017-10-26 17:26:53 -07002446 }
2447
2448 public static int standbyBucketToBucketIndex(int bucket) {
2449 // Normalize AppStandby constants to indices into our bookkeeping
Christopher Tatef2159712018-03-27 16:04:14 -07002450 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return NEVER_INDEX;
2451 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) return RARE_INDEX;
2452 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return FREQUENT_INDEX;
2453 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) return WORKING_INDEX;
2454 else return ACTIVE_INDEX;
Christopher Tatea732f012017-10-26 17:26:53 -07002455 }
2456
Christopher Tated1aebb32018-01-31 13:24:14 -08002457 // Static to support external callers
Christopher Tatea732f012017-10-26 17:26:53 -07002458 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2459 UsageStatsManagerInternal usageStats = LocalServices.getService(
2460 UsageStatsManagerInternal.class);
2461 int bucket = usageStats != null
2462 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2463 : 0;
2464
2465 bucket = standbyBucketToBucketIndex(bucket);
2466
2467 if (DEBUG_STANDBY) {
2468 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2469 }
2470 return bucket;
2471 }
2472
2473 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002474 * Binder stub trampoline implementation
2475 */
2476 final class JobSchedulerStub extends IJobScheduler.Stub {
2477 /** Cache determination of whether a given app can persist jobs
2478 * key is uid of the calling app; value is undetermined/true/false
2479 */
2480 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2481
2482 // Enforce that only the app itself (or shared uid participant) can schedule a
2483 // job that runs one of the app's services, as well as verifying that the
2484 // named service properly requires the BIND_JOB_SERVICE permission
2485 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002486 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002487 final ComponentName service = job.getService();
2488 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002489 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002490 PackageManager.MATCH_DIRECT_BOOT_AWARE
2491 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002492 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002493 if (si == null) {
2494 throw new IllegalArgumentException("No such service " + service);
2495 }
Christopher Tate7060b042014-06-09 19:50:00 -07002496 if (si.applicationInfo.uid != uid) {
2497 throw new IllegalArgumentException("uid " + uid +
2498 " cannot schedule job in " + service.getPackageName());
2499 }
2500 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2501 throw new IllegalArgumentException("Scheduled service " + service
2502 + " does not require android.permission.BIND_JOB_SERVICE permission");
2503 }
Christopher Tate5568f542014-06-18 13:53:31 -07002504 } catch (RemoteException e) {
2505 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002506 }
2507 }
2508
2509 private boolean canPersistJobs(int pid, int uid) {
2510 // If we get this far we're good to go; all we need to do now is check
2511 // whether the app is allowed to persist its scheduled work.
2512 final boolean canPersist;
2513 synchronized (mPersistCache) {
2514 Boolean cached = mPersistCache.get(uid);
2515 if (cached != null) {
2516 canPersist = cached.booleanValue();
2517 } else {
2518 // Persisting jobs is tantamount to running at boot, so we permit
2519 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2520 // permission
2521 int result = getContext().checkPermission(
2522 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2523 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2524 mPersistCache.put(uid, canPersist);
2525 }
2526 }
2527 return canPersist;
2528 }
2529
Makoto Onuki959acb52018-01-26 14:10:03 -08002530 private void validateJobFlags(JobInfo job, int callingUid) {
2531 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2532 getContext().enforceCallingOrSelfPermission(
2533 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2534 }
2535 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
2536 if (callingUid != Process.SYSTEM_UID) {
2537 throw new SecurityException("Job has invalid flags");
2538 }
Makoto Onuki2b5811a2018-02-08 11:09:42 -08002539 if (job.isPeriodic()) {
2540 Slog.wtf(TAG, "Periodic jobs mustn't have"
2541 + " FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
Makoto Onuki959acb52018-01-26 14:10:03 -08002542 }
2543 }
2544 }
2545
Christopher Tate7060b042014-06-09 19:50:00 -07002546 // IJobScheduler implementation
2547 @Override
2548 public int schedule(JobInfo job) throws RemoteException {
2549 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002550 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002551 }
2552 final int pid = Binder.getCallingPid();
2553 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002554 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002555
2556 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002557 if (job.isPersisted()) {
2558 if (!canPersistJobs(pid, uid)) {
2559 throw new IllegalArgumentException("Error: requested job be persisted without"
2560 + " holding RECEIVE_BOOT_COMPLETED permission.");
2561 }
2562 }
Christopher Tate7060b042014-06-09 19:50:00 -07002563
Makoto Onuki959acb52018-01-26 14:10:03 -08002564 validateJobFlags(job, uid);
Jeff Sharkey785f4942016-07-14 10:31:15 -06002565
Christopher Tate7060b042014-06-09 19:50:00 -07002566 long ident = Binder.clearCallingIdentity();
2567 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002568 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2569 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002570 } finally {
2571 Binder.restoreCallingIdentity(ident);
2572 }
2573 }
2574
2575 // IJobScheduler implementation
2576 @Override
2577 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2578 if (DEBUG) {
2579 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2580 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002581 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002582 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002583
2584 enforceValidJobRequest(uid, job);
2585 if (job.isPersisted()) {
2586 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2587 }
2588 if (work == null) {
2589 throw new NullPointerException("work is null");
2590 }
2591
Makoto Onuki959acb52018-01-26 14:10:03 -08002592 validateJobFlags(job, uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002593
2594 long ident = Binder.clearCallingIdentity();
2595 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002596 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2597 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002598 } finally {
2599 Binder.restoreCallingIdentity(ident);
2600 }
2601 }
2602
2603 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002604 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002605 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002606 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002607 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002608 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002609 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002610 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002611
2612 if (packageName == null) {
2613 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002614 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002615
2616 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2617 android.Manifest.permission.UPDATE_DEVICE_STATS);
2618 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2619 throw new SecurityException("Caller uid " + callerUid
2620 + " not permitted to schedule jobs for other apps");
2621 }
2622
Makoto Onuki959acb52018-01-26 14:10:03 -08002623 validateJobFlags(job, callerUid);
Jeff Sharkey4f100402016-05-03 17:44:23 -06002624
Shreyas Basarge968ac752016-01-11 23:09:26 +00002625 long ident = Binder.clearCallingIdentity();
2626 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002627 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002628 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002629 } finally {
2630 Binder.restoreCallingIdentity(ident);
2631 }
2632 }
2633
2634 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002635 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2636 final int uid = Binder.getCallingUid();
2637
2638 long ident = Binder.clearCallingIdentity();
2639 try {
2640 return JobSchedulerService.this.getPendingJobs(uid);
2641 } finally {
2642 Binder.restoreCallingIdentity(ident);
2643 }
2644 }
2645
2646 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002647 public JobInfo getPendingJob(int jobId) throws RemoteException {
2648 final int uid = Binder.getCallingUid();
2649
2650 long ident = Binder.clearCallingIdentity();
2651 try {
2652 return JobSchedulerService.this.getPendingJob(uid, jobId);
2653 } finally {
2654 Binder.restoreCallingIdentity(ident);
2655 }
2656 }
2657
2658 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002659 public void cancelAll() throws RemoteException {
2660 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002661 long ident = Binder.clearCallingIdentity();
2662 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002663 JobSchedulerService.this.cancelJobsForUid(uid,
2664 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002665 } finally {
2666 Binder.restoreCallingIdentity(ident);
2667 }
2668 }
2669
2670 @Override
2671 public void cancel(int jobId) throws RemoteException {
2672 final int uid = Binder.getCallingUid();
2673
2674 long ident = Binder.clearCallingIdentity();
2675 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002676 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002677 } finally {
2678 Binder.restoreCallingIdentity(ident);
2679 }
2680 }
2681
2682 /**
2683 * "dumpsys" infrastructure
2684 */
2685 @Override
2686 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002687 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002688
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002689 int filterUid = -1;
2690 boolean proto = false;
2691 if (!ArrayUtils.isEmpty(args)) {
2692 int opti = 0;
2693 while (opti < args.length) {
2694 String arg = args[opti];
2695 if ("-h".equals(arg)) {
2696 dumpHelp(pw);
2697 return;
2698 } else if ("-a".equals(arg)) {
2699 // Ignore, we always dump all.
2700 } else if ("--proto".equals(arg)) {
2701 proto = true;
2702 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2703 pw.println("Unknown option: " + arg);
2704 return;
2705 } else {
2706 break;
2707 }
2708 opti++;
2709 }
2710 if (opti < args.length) {
2711 String pkg = args[opti];
2712 try {
2713 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2714 PackageManager.MATCH_ANY_USER);
2715 } catch (NameNotFoundException ignored) {
2716 pw.println("Invalid package: " + pkg);
2717 return;
2718 }
2719 }
2720 }
2721
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002722 final long identityToken = Binder.clearCallingIdentity();
Christopher Tate7060b042014-06-09 19:50:00 -07002723 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002724 if (proto) {
2725 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2726 } else {
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002727 JobSchedulerService.this.dumpInternal(new IndentingPrintWriter(pw, " "),
2728 filterUid);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002729 }
Christopher Tate7060b042014-06-09 19:50:00 -07002730 } finally {
2731 Binder.restoreCallingIdentity(identityToken);
2732 }
2733 }
Christopher Tate5d346052016-03-08 12:56:08 -08002734
2735 @Override
2736 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002737 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002738 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002739 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002740 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002741 };
2742
Christopher Tate5d346052016-03-08 12:56:08 -08002743 // Shell command infrastructure: run the given job immediately
2744 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2745 if (DEBUG) {
2746 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2747 + " " + jobId + " f=" + force);
2748 }
2749
2750 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002751 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2752 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002753 if (uid < 0) {
2754 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2755 }
2756
2757 synchronized (mLock) {
2758 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2759 if (js == null) {
2760 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2761 }
2762
2763 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2764 if (!js.isConstraintsSatisfied()) {
2765 js.overrideState = 0;
2766 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2767 }
2768
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002769 queueReadyJobsForExecutionLocked();
2770 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002771 }
2772 } catch (RemoteException e) {
2773 // can't happen
2774 }
2775 return 0;
2776 }
2777
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002778 // Shell command infrastructure: immediately timeout currently executing jobs
2779 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2780 boolean hasJobId, int jobId) {
2781 if (DEBUG) {
2782 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2783 }
2784
2785 synchronized (mLock) {
2786 boolean foundSome = false;
2787 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002788 final JobServiceContext jc = mActiveServices.get(i);
2789 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002790 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002791 foundSome = true;
2792 pw.print("Timing out: ");
2793 js.printUniqueId(pw);
2794 pw.print(" ");
2795 pw.println(js.getServiceComponent().flattenToShortString());
2796 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002797 }
2798 if (!foundSome) {
2799 pw.println("No matching executing jobs found.");
2800 }
2801 }
2802 return 0;
2803 }
2804
Christopher Tate8c67d122017-09-29 16:54:26 -07002805 // Shell command infrastructure: cancel a scheduled job
2806 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2807 boolean hasJobId, int jobId) {
2808 if (DEBUG) {
2809 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2810 }
2811
2812 int pkgUid = -1;
2813 try {
2814 IPackageManager pm = AppGlobals.getPackageManager();
2815 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2816 } catch (RemoteException e) { /* can't happen */ }
2817
2818 if (pkgUid < 0) {
2819 pw.println("Package " + pkgName + " not found.");
2820 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2821 }
2822
2823 if (!hasJobId) {
2824 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2825 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2826 pw.println("No matching jobs found.");
2827 }
2828 } else {
2829 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002830 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002831 pw.println("No matching job found.");
2832 }
2833 }
2834
2835 return 0;
2836 }
2837
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002838 void setMonitorBattery(boolean enabled) {
2839 synchronized (mLock) {
2840 if (mBatteryController != null) {
2841 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2842 }
2843 }
2844 }
2845
2846 int getBatterySeq() {
2847 synchronized (mLock) {
2848 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2849 }
2850 }
2851
2852 boolean getBatteryCharging() {
2853 synchronized (mLock) {
2854 return mBatteryController != null
2855 ? mBatteryController.getTracker().isOnStablePower() : false;
2856 }
2857 }
2858
2859 boolean getBatteryNotLow() {
2860 synchronized (mLock) {
2861 return mBatteryController != null
2862 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2863 }
2864 }
2865
Dianne Hackborn532ea262017-03-17 17:50:55 -07002866 int getStorageSeq() {
2867 synchronized (mLock) {
2868 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2869 }
2870 }
2871
2872 boolean getStorageNotLow() {
2873 synchronized (mLock) {
2874 return mStorageController != null
2875 ? mStorageController.getTracker().isStorageNotLow() : false;
2876 }
2877 }
2878
Christopher Tatea732f012017-10-26 17:26:53 -07002879 long getCurrentHeartbeat() {
2880 synchronized (mLock) {
2881 return mHeartbeat;
2882 }
2883 }
2884
Christopher Tated1aebb32018-01-31 13:24:14 -08002885 // Shell command infrastructure
Dianne Hackborn6d068262017-05-16 13:14:37 -07002886 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2887 try {
2888 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2889 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2890 if (uid < 0) {
2891 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2892 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2893 }
2894
2895 synchronized (mLock) {
2896 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2897 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2898 if (js == null) {
2899 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2900 pw.print("/jid"); pw.print(jobId); pw.println(")");
2901 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2902 }
2903
2904 boolean printed = false;
2905 if (mPendingJobs.contains(js)) {
2906 pw.print("pending");
2907 printed = true;
2908 }
2909 if (isCurrentlyActiveLocked(js)) {
2910 if (printed) {
2911 pw.print(" ");
2912 }
2913 printed = true;
2914 pw.println("active");
2915 }
2916 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2917 if (printed) {
2918 pw.print(" ");
2919 }
2920 printed = true;
2921 pw.println("user-stopped");
2922 }
2923 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2924 if (printed) {
2925 pw.print(" ");
2926 }
2927 printed = true;
2928 pw.println("backing-up");
2929 }
2930 boolean componentPresent = false;
2931 try {
2932 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2933 js.getServiceComponent(),
2934 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2935 js.getUserId()) != null);
2936 } catch (RemoteException e) {
2937 }
2938 if (!componentPresent) {
2939 if (printed) {
2940 pw.print(" ");
2941 }
2942 printed = true;
2943 pw.println("no-component");
2944 }
2945 if (js.isReady()) {
2946 if (printed) {
2947 pw.print(" ");
2948 }
2949 printed = true;
2950 pw.println("ready");
2951 }
2952 if (!printed) {
2953 pw.print("waiting");
2954 }
2955 pw.println();
2956 }
2957 } catch (RemoteException e) {
2958 // can't happen
2959 }
2960 return 0;
2961 }
2962
Christopher Tated1aebb32018-01-31 13:24:14 -08002963 // Shell command infrastructure
2964 int executeHeartbeatCommand(PrintWriter pw, int numBeats) {
2965 if (numBeats < 1) {
2966 pw.println(getCurrentHeartbeat());
2967 return 0;
2968 }
2969
2970 pw.print("Advancing standby heartbeat by ");
2971 pw.println(numBeats);
2972 synchronized (mLock) {
2973 advanceHeartbeatLocked(numBeats);
2974 }
2975 return 0;
2976 }
2977
lpeter318abc92018-05-04 16:13:14 +08002978 void triggerDockState(boolean idleState) {
2979 final Intent dockIntent;
2980 if (idleState) {
2981 dockIntent = new Intent(Intent.ACTION_DOCK_IDLE);
2982 } else {
2983 dockIntent = new Intent(Intent.ACTION_DOCK_ACTIVE);
2984 }
2985 dockIntent.setPackage("android");
2986 dockIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
2987 getContext().sendBroadcastAsUser(dockIntent, UserHandle.ALL);
2988 }
2989
Shreyas Basarge5db09082016-01-07 13:38:29 +00002990 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2991 StringBuilder s = new StringBuilder(initial + ": ");
2992 for (int i=0; i<map.length; i++) {
2993 s.append("(")
2994 .append(map[i] == null? -1: map[i].getJobId())
2995 .append(map[i] == null? -1: map[i].getUid())
2996 .append(")" );
2997 }
2998 return s.toString();
2999 }
3000
3001 private String printPendingQueue() {
3002 StringBuilder s = new StringBuilder("Pending queue: ");
3003 Iterator<JobStatus> it = mPendingJobs.iterator();
3004 while (it.hasNext()) {
3005 JobStatus js = it.next();
3006 s.append("(")
3007 .append(js.getJob().getId())
3008 .append(", ")
3009 .append(js.getUid())
3010 .append(") ");
3011 }
3012 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07003013 }
Christopher Tate7060b042014-06-09 19:50:00 -07003014
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003015 static void dumpHelp(PrintWriter pw) {
3016 pw.println("Job Scheduler (jobscheduler) dump options:");
3017 pw.println(" [-h] [package] ...");
3018 pw.println(" -h: print this help");
3019 pw.println(" [package] is an optional package name to limit the output to.");
3020 }
3021
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003022 /** Sort jobs by caller UID, then by Job ID. */
3023 private static void sortJobs(List<JobStatus> jobs) {
3024 Collections.sort(jobs, new Comparator<JobStatus>() {
3025 @Override
3026 public int compare(JobStatus o1, JobStatus o2) {
3027 int uid1 = o1.getUid();
3028 int uid2 = o2.getUid();
3029 int id1 = o1.getJobId();
3030 int id2 = o2.getJobId();
3031 if (uid1 != uid2) {
3032 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003033 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003034 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003035 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003036 });
3037 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06003038
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003039 void dumpInternal(final IndentingPrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003040 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07003041 final long nowElapsed = sElapsedRealtimeClock.millis();
3042 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003043 final Predicate<JobStatus> predicate = (js) -> {
3044 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3045 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3046 };
Dianne Hackborn33d31c52016-02-16 10:30:33 -08003047 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003048 mConstants.dump(pw);
3049 pw.println();
Makoto Onukib5d5e972018-02-20 14:44:20 -08003050
3051 pw.println(" Heartbeat:");
3052 pw.print(" Current: "); pw.println(mHeartbeat);
3053 pw.println(" Next");
3054 pw.print(" ACTIVE: "); pw.println(mNextBucketHeartbeat[0]);
3055 pw.print(" WORKING: "); pw.println(mNextBucketHeartbeat[1]);
3056 pw.print(" FREQUENT: "); pw.println(mNextBucketHeartbeat[2]);
3057 pw.print(" RARE: "); pw.println(mNextBucketHeartbeat[3]);
3058 pw.print(" Last heartbeat: ");
3059 TimeUtils.formatDuration(mLastHeartbeatTime, nowElapsed, pw);
3060 pw.println();
3061 pw.print(" Next heartbeat: ");
3062 TimeUtils.formatDuration(mLastHeartbeatTime + mConstants.STANDBY_HEARTBEAT_TIME,
3063 nowElapsed, pw);
3064 pw.println();
Makoto Onuki0525b982018-05-02 14:46:59 -07003065 pw.print(" In parole?: ");
3066 pw.print(mInParole);
3067 pw.println();
Makoto Onukib5d5e972018-02-20 14:44:20 -08003068 pw.println();
3069
Jeff Sharkey822cbd12016-02-25 11:09:55 -07003070 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003071 pw.print("Registered ");
3072 pw.print(mJobs.size());
3073 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07003074 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003075 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003076 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003077 for (JobStatus job : jobs) {
3078 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
3079 pw.println(job.toShortStringExceptUniqueId());
3080
3081 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003082 if (!predicate.test(job)) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003083 continue;
3084 }
3085
Dianne Hackborn6d068262017-05-16 13:14:37 -07003086 job.dump(pw, " ", true, nowElapsed);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003087 pw.print(" Last run heartbeat: ");
3088 pw.print(heartbeatWhenJobsLastRun(job));
3089 pw.println();
3090
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003091 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003092 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003093 pw.print(" (job=");
3094 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003095 pw.print(" user=");
3096 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003097 pw.print(" !pending=");
3098 pw.print(!mPendingJobs.contains(job));
3099 pw.print(" !active=");
3100 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003101 pw.print(" !backingup=");
3102 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003103 pw.print(" comp=");
3104 boolean componentPresent = false;
3105 try {
3106 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3107 job.getServiceComponent(),
3108 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3109 job.getUserId()) != null);
3110 } catch (RemoteException e) {
3111 }
3112 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003113 pw.println(")");
3114 }
Christopher Tate7060b042014-06-09 19:50:00 -07003115 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07003116 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07003117 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003118 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07003119 pw.println();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003120 pw.println(mControllers.get(i).getClass().getSimpleName() + ":");
3121 pw.increaseIndent();
3122 mControllers.get(i).dumpControllerStateLocked(pw, predicate);
3123 pw.decreaseIndent();
Christopher Tate7060b042014-06-09 19:50:00 -07003124 }
3125 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08003126 pw.println("Uid priority overrides:");
3127 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003128 int uid = mUidPriorityOverride.keyAt(i);
3129 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3130 pw.print(" "); pw.print(UserHandle.formatUid(uid));
3131 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
3132 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003133 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003134 if (mBackingUpUids.size() > 0) {
3135 pw.println();
3136 pw.println("Backing up uids:");
3137 boolean first = true;
3138 for (int i = 0; i < mBackingUpUids.size(); i++) {
3139 int uid = mBackingUpUids.keyAt(i);
3140 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3141 if (first) {
3142 pw.print(" ");
3143 first = false;
3144 } else {
3145 pw.print(", ");
3146 }
3147 pw.print(UserHandle.formatUid(uid));
3148 }
3149 }
3150 pw.println();
3151 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003152 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003153 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07003154 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003155 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
3156 pw.println();
3157 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003158 pw.println("Pending queue:");
3159 for (int i=0; i<mPendingJobs.size(); i++) {
3160 JobStatus job = mPendingJobs.get(i);
3161 pw.print(" Pending #"); pw.print(i); pw.print(": ");
3162 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07003163 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003164 int priority = evaluateJobPriorityLocked(job);
3165 if (priority != JobInfo.PRIORITY_DEFAULT) {
3166 pw.print(" Evaluated priority: "); pw.println(priority);
3167 }
3168 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07003169 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003170 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003171 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003172 }
Christopher Tate7060b042014-06-09 19:50:00 -07003173 pw.println();
3174 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003175 for (int i=0; i<mActiveServices.size(); i++) {
3176 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003177 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003178 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07003179 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07003180 if (jsc.mStoppedReason != null) {
3181 pw.print("inactive since ");
3182 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
3183 pw.print(", stopped because: ");
3184 pw.println(jsc.mStoppedReason);
3185 } else {
3186 pw.println("inactive");
3187 }
Christopher Tate7060b042014-06-09 19:50:00 -07003188 continue;
3189 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07003190 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08003191 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003192 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003193 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003194 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003195 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07003196 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003197 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003198 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08003199 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003200 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003201 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003202 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003203 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07003204 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
3205 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07003206 }
3207 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003208 if (filterUid == -1) {
3209 pw.println();
3210 pw.print("mReadyToRock="); pw.println(mReadyToRock);
3211 pw.print("mReportedActive="); pw.println(mReportedActive);
3212 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
3213 }
Makoto Onukie7b02982017-08-24 14:23:36 -07003214 pw.println();
3215 pw.print("PersistStats: ");
3216 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07003217 }
3218 pw.println();
3219 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003220
3221 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
3222 ProtoOutputStream proto = new ProtoOutputStream(fd);
3223 final int filterUidFinal = UserHandle.getAppId(filterUid);
3224 final long nowElapsed = sElapsedRealtimeClock.millis();
3225 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003226 final Predicate<JobStatus> predicate = (js) -> {
3227 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3228 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3229 };
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003230
3231 synchronized (mLock) {
3232 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003233 proto.write(JobSchedulerServiceDumpProto.CURRENT_HEARTBEAT, mHeartbeat);
3234 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[0]);
3235 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[1]);
3236 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[2]);
3237 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[3]);
3238 proto.write(JobSchedulerServiceDumpProto.LAST_HEARTBEAT_TIME_MILLIS,
3239 mLastHeartbeatTime - nowUptime);
3240 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT_TIME_MILLIS,
3241 mLastHeartbeatTime + mConstants.STANDBY_HEARTBEAT_TIME - nowUptime);
Makoto Onuki0525b982018-05-02 14:46:59 -07003242 proto.write(JobSchedulerServiceDumpProto.IN_PAROLE, mInParole);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003243
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003244 for (int u : mStartedUsers) {
3245 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
3246 }
3247 if (mJobs.size() > 0) {
3248 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
3249 sortJobs(jobs);
3250 for (JobStatus job : jobs) {
3251 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
3252 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
3253
3254 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003255 if (!predicate.test(job)) {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003256 continue;
3257 }
3258
3259 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
3260
3261 // isReadyToBeExecuted
3262 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
3263 job.isReady());
3264 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
3265 ArrayUtils.contains(mStartedUsers, job.getUserId()));
3266 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
3267 mPendingJobs.contains(job));
3268 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
3269 isCurrentlyActiveLocked(job));
3270 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
3271 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
3272 boolean componentPresent = false;
3273 try {
3274 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3275 job.getServiceComponent(),
3276 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3277 job.getUserId()) != null);
3278 } catch (RemoteException e) {
3279 }
3280 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
3281 componentPresent);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003282 proto.write(RegisteredJob.LAST_RUN_HEARTBEAT, heartbeatWhenJobsLastRun(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003283
3284 proto.end(rjToken);
3285 }
3286 }
3287 for (StateController controller : mControllers) {
3288 controller.dumpControllerStateLocked(
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003289 proto, JobSchedulerServiceDumpProto.CONTROLLERS, predicate);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003290 }
3291 for (int i=0; i< mUidPriorityOverride.size(); i++) {
3292 int uid = mUidPriorityOverride.keyAt(i);
3293 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3294 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3295 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3296 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3297 mUidPriorityOverride.valueAt(i));
3298 proto.end(pToken);
3299 }
3300 }
3301 for (int i = 0; i < mBackingUpUids.size(); i++) {
3302 int uid = mBackingUpUids.keyAt(i);
3303 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3304 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3305 }
3306 }
3307
3308 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3309 filterUidFinal);
3310 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3311 filterUidFinal);
3312
3313 for (JobStatus job : mPendingJobs) {
3314 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3315
3316 job.writeToShortProto(proto, PendingJob.INFO);
3317 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
3318 int priority = evaluateJobPriorityLocked(job);
3319 if (priority != JobInfo.PRIORITY_DEFAULT) {
3320 proto.write(PendingJob.EVALUATED_PRIORITY, priority);
3321 }
3322 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
3323
3324 proto.end(pjToken);
3325 }
3326 for (JobServiceContext jsc : mActiveServices) {
3327 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
3328 final JobStatus job = jsc.getRunningJobLocked();
3329
3330 if (job == null) {
3331 final long ijToken = proto.start(ActiveJob.INACTIVE);
3332
3333 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
3334 nowElapsed - jsc.mStoppedTime);
3335 if (jsc.mStoppedReason != null) {
3336 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
3337 jsc.mStoppedReason);
3338 }
3339
3340 proto.end(ijToken);
3341 } else {
3342 final long rjToken = proto.start(ActiveJob.RUNNING);
3343
3344 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
3345
3346 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
3347 nowElapsed - jsc.getExecutionStartTimeElapsed());
3348 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
3349 jsc.getTimeoutElapsed() - nowElapsed);
3350
3351 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3352
3353 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
3354 if (priority != JobInfo.PRIORITY_DEFAULT) {
3355 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY, priority);
3356 }
3357
3358 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3359 nowUptime - job.madeActive);
3360 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3361 job.madeActive - job.madePending);
3362
3363 proto.end(rjToken);
3364 }
3365 proto.end(ajToken);
3366 }
3367 if (filterUid == -1) {
3368 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3369 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3370 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
3371 }
3372 }
3373
3374 proto.flush();
3375 }
Christopher Tate7060b042014-06-09 19:50:00 -07003376}