blob: 736aa46352bda11760bedcce751866cacac02cbe [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;
251
252 /**
253 * Bookkeeping about when jobs last run. We keep our own record in heartbeat time,
254 * rather than rely on Usage Stats' timestamps, because heartbeat time can be
255 * manipulated for testing purposes and we need job runnability to track that rather
256 * than real time.
257 *
258 * Outer SparseArray slices by user handle; inner map of package name to heartbeat
259 * is a HashMap<> rather than ArrayMap<> because we expect O(hundreds) of keys
260 * and it will be accessed in a known-hot code path.
261 */
262 final SparseArray<HashMap<String, Long>> mLastJobHeartbeats = new SparseArray<>();
263
Christopher Tated1aebb32018-01-31 13:24:14 -0800264 static final String HEARTBEAT_TAG = "*job.heartbeat*";
265 final HeartbeatAlarmListener mHeartbeatAlarm = new HeartbeatAlarmListener();
Christopher Tatea732f012017-10-26 17:26:53 -0700266
Dianne Hackborn970510b2016-02-24 16:56:42 -0800267 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
268
269 /**
270 * This array essentially stores the state of mActiveServices array.
271 * The ith index stores the job present on the ith JobServiceContext.
272 * We manipulate this array until we arrive at what jobs should be running on
273 * what JobServiceContext.
274 */
275 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
276 /**
277 * Indicates whether we need to act on this jobContext id
278 */
279 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
280 /**
281 * The uid whose jobs we would like to assign to a context.
282 */
283 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800284
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700285 private class ConstantsObserver extends ContentObserver {
286 private ContentResolver mResolver;
287
288 public ConstantsObserver(Handler handler) {
289 super(handler);
290 }
291
292 public void start(ContentResolver resolver) {
293 mResolver = resolver;
294 mResolver.registerContentObserver(Settings.Global.getUriFor(
295 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
296 updateConstants();
297 }
298
299 @Override
300 public void onChange(boolean selfChange, Uri uri) {
301 updateConstants();
302 }
303
304 private void updateConstants() {
305 synchronized (mLock) {
306 try {
307 mConstants.updateConstantsLocked(Settings.Global.getString(mResolver,
308 Settings.Global.JOB_SCHEDULER_CONSTANTS));
309 } catch (IllegalArgumentException e) {
310 // Failed to parse the settings string, log this and move on
311 // with defaults.
312 Slog.e(TAG, "Bad jobscheduler settings", e);
313 }
314 }
315
316 // Reset the heartbeat alarm based on the new heartbeat duration
317 setNextHeartbeatAlarm();
318 }
319 }
320
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800321 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700322 * All times are in milliseconds. These constants are kept synchronized with the system
323 * global Settings. Any access to this class or its fields should be done while
324 * holding the JobSchedulerService.mLock lock.
325 */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700326 public static class Constants {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700327 // Key names stored in the settings value.
328 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
329 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800330 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700331 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700332 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
333 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
334 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
335 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
336 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
337 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
338 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
339 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
340 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
341 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700342 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
343 = "max_standard_reschedule_count";
344 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
345 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
346 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700347 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
348 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
349 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
350 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700351 private static final String KEY_CONN_CONGESTION_DELAY_FRAC = "conn_congestion_delay_frac";
352 private static final String KEY_CONN_PREFETCH_RELAX_FRAC = "conn_prefetch_relax_frac";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700353
354 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
355 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800356 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700357 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700358 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
359 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
360 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
361 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
362 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
363 private static final int DEFAULT_FG_JOB_COUNT = 4;
364 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
365 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700366 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700367 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700368 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
369 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
370 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
371 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700372 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000373 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
374 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700375 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700376 private static final float DEFAULT_CONN_CONGESTION_DELAY_FRAC = 0.5f;
377 private static final float DEFAULT_CONN_PREFETCH_RELAX_FRAC = 0.5f;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700378
379 /**
380 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
381 * early.
382 */
383 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
384 /**
385 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
386 * things early.
387 */
388 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
389 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800390 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
391 * schedule things early.
392 */
393 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
394 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700395 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
396 * schedule things early.
397 */
398 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
399 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700400 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
401 * things early. 1 == Run connectivity jobs as soon as ready.
402 */
403 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
404 /**
405 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
406 * schedule things early.
407 */
408 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
409 /**
410 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
411 * running some work early. This (and thus the other min counts) is now set to 1, to
412 * prevent any batching at this level. Since we now do batching through doze, that is
413 * a much better mechanism.
414 */
415 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
416 /**
417 * This is the job execution factor that is considered to be heavy use of the system.
418 */
419 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
420 /**
421 * This is the job execution factor that is considered to be moderate use of the system.
422 */
423 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
424 /**
425 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
426 */
427 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
428 /**
429 * The maximum number of background jobs we allow when the system is in a normal
430 * memory state.
431 */
432 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
433 /**
434 * The maximum number of background jobs we allow when the system is in a moderate
435 * memory state.
436 */
437 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
438 /**
439 * The maximum number of background jobs we allow when the system is in a low
440 * memory state.
441 */
442 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
443 /**
444 * The maximum number of background jobs we allow when the system is in a critical
445 * memory state.
446 */
447 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700448 /**
449 * The maximum number of times we allow a job to have itself rescheduled before
450 * giving up on it, for standard jobs.
451 */
452 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
453 /**
454 * The maximum number of times we allow a job to have itself rescheduled before
455 * giving up on it, for jobs that are executing work.
456 */
457 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
458 /**
459 * The minimum backoff time to allow for linear backoff.
460 */
461 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
462 /**
463 * The minimum backoff time to allow for exponential backoff.
464 */
465 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700466 /**
467 * How often we recalculate runnability based on apps' standby bucket assignment.
468 * This should be prime relative to common time interval lengths such as a quarter-
469 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
470 */
471 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700472 /**
473 * Mapping: standby bucket -> number of heartbeats between each sweep of that
474 * bucket's jobs.
475 *
476 * Bucket assignments as recorded in the JobStatus objects are normalized to be
477 * indices into this array, rather than the raw constants used
478 * by AppIdleHistory.
479 */
480 final int[] STANDBY_BEATS = {
481 0,
482 DEFAULT_STANDBY_WORKING_BEATS,
483 DEFAULT_STANDBY_FREQUENT_BEATS,
484 DEFAULT_STANDBY_RARE_BEATS
485 };
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700486 /**
487 * The fraction of a job's running window that must pass before we
488 * consider running it when the network is congested.
489 */
490 public float CONN_CONGESTION_DELAY_FRAC = DEFAULT_CONN_CONGESTION_DELAY_FRAC;
491 /**
492 * The fraction of a prefetch job's running window that must pass before
493 * we consider matching it against a metered network.
494 */
495 public float CONN_PREFETCH_RELAX_FRAC = DEFAULT_CONN_PREFETCH_RELAX_FRAC;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700496
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700497 private final KeyValueListParser mParser = new KeyValueListParser(',');
498
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700499 void updateConstantsLocked(String value) {
500 try {
501 mParser.setString(value);
502 } catch (Exception e) {
503 // Failed to parse the settings string, log this and move on
504 // with defaults.
505 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700506 }
Christopher Tated1aebb32018-01-31 13:24:14 -0800507
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700508 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
509 DEFAULT_MIN_IDLE_COUNT);
510 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
511 DEFAULT_MIN_CHARGING_COUNT);
512 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
513 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
514 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
515 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
516 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
517 DEFAULT_MIN_CONNECTIVITY_COUNT);
518 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
519 DEFAULT_MIN_CONTENT_COUNT);
520 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
521 DEFAULT_MIN_READY_JOBS_COUNT);
522 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
523 DEFAULT_HEAVY_USE_FACTOR);
524 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
525 DEFAULT_MODERATE_USE_FACTOR);
526 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
527 DEFAULT_FG_JOB_COUNT);
528 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
529 DEFAULT_BG_NORMAL_JOB_COUNT);
530 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
531 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
532 }
533 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
534 DEFAULT_BG_MODERATE_JOB_COUNT);
535 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
536 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
537 }
538 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
539 DEFAULT_BG_LOW_JOB_COUNT);
540 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
541 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
542 }
543 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
544 DEFAULT_BG_CRITICAL_JOB_COUNT);
545 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
546 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
547 }
548 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
549 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
550 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
551 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
552 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
553 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
554 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
555 DEFAULT_MIN_EXP_BACKOFF_TIME);
556 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
557 DEFAULT_STANDBY_HEARTBEAT_TIME);
Christopher Tate325768c2018-03-07 16:07:56 -0800558 STANDBY_BEATS[WORKING_INDEX] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700559 DEFAULT_STANDBY_WORKING_BEATS);
Christopher Tate325768c2018-03-07 16:07:56 -0800560 STANDBY_BEATS[FREQUENT_INDEX] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700561 DEFAULT_STANDBY_FREQUENT_BEATS);
Christopher Tate325768c2018-03-07 16:07:56 -0800562 STANDBY_BEATS[RARE_INDEX] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700563 DEFAULT_STANDBY_RARE_BEATS);
564 CONN_CONGESTION_DELAY_FRAC = mParser.getFloat(KEY_CONN_CONGESTION_DELAY_FRAC,
565 DEFAULT_CONN_CONGESTION_DELAY_FRAC);
566 CONN_PREFETCH_RELAX_FRAC = mParser.getFloat(KEY_CONN_PREFETCH_RELAX_FRAC,
567 DEFAULT_CONN_PREFETCH_RELAX_FRAC);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700568 }
569
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700570 void dump(IndentingPrintWriter pw) {
571 pw.println("Settings:");
572 pw.increaseIndent();
573 pw.printPair(KEY_MIN_IDLE_COUNT, MIN_IDLE_COUNT).println();
574 pw.printPair(KEY_MIN_CHARGING_COUNT, MIN_CHARGING_COUNT).println();
575 pw.printPair(KEY_MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT).println();
576 pw.printPair(KEY_MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT).println();
577 pw.printPair(KEY_MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT).println();
578 pw.printPair(KEY_MIN_CONTENT_COUNT, MIN_CONTENT_COUNT).println();
579 pw.printPair(KEY_MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT).println();
580 pw.printPair(KEY_HEAVY_USE_FACTOR, HEAVY_USE_FACTOR).println();
581 pw.printPair(KEY_MODERATE_USE_FACTOR, MODERATE_USE_FACTOR).println();
582 pw.printPair(KEY_FG_JOB_COUNT, FG_JOB_COUNT).println();
583 pw.printPair(KEY_BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT).println();
584 pw.printPair(KEY_BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT).println();
585 pw.printPair(KEY_BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT).println();
586 pw.printPair(KEY_BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT).println();
587 pw.printPair(KEY_MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT).println();
588 pw.printPair(KEY_MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT).println();
589 pw.printPair(KEY_MIN_LINEAR_BACKOFF_TIME, MIN_LINEAR_BACKOFF_TIME).println();
590 pw.printPair(KEY_MIN_EXP_BACKOFF_TIME, MIN_EXP_BACKOFF_TIME).println();
591 pw.printPair(KEY_STANDBY_HEARTBEAT_TIME, STANDBY_HEARTBEAT_TIME).println();
592 pw.print("standby_beats={");
Christopher Tatea732f012017-10-26 17:26:53 -0700593 pw.print(STANDBY_BEATS[0]);
594 for (int i = 1; i < STANDBY_BEATS.length; i++) {
595 pw.print(", ");
596 pw.print(STANDBY_BEATS[i]);
597 }
598 pw.println('}');
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700599 pw.printPair(KEY_CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC).println();
600 pw.printPair(KEY_CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC).println();
601 pw.decreaseIndent();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700602 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800603
604 void dump(ProtoOutputStream proto, long fieldId) {
605 final long token = proto.start(fieldId);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800606 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
607 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
608 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
609 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
610 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
611 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
612 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
613 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
614 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
615 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
616 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
617 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
618 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
619 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
620 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
621 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
622 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
623 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
624 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800625 for (int period : STANDBY_BEATS) {
626 proto.write(ConstantsProto.STANDBY_BEATS, period);
627 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700628 proto.write(ConstantsProto.CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC);
629 proto.write(ConstantsProto.CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800630 proto.end(token);
631 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700632 }
633
634 final Constants mConstants;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700635 final ConstantsObserver mConstantsObserver;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700636
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700637 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
638 if (o1.enqueueTime < o2.enqueueTime) {
639 return -1;
640 }
641 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
642 };
643
644 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
645 int where = Collections.binarySearch(array, newItem, comparator);
646 if (where < 0) {
647 where = ~where;
648 }
649 array.add(where, newItem);
650 }
651
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700652 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700653 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
654 * still clean up. On reinstall the package will have a new uid.
655 */
656 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
657 @Override
658 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700659 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700660 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700661 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700662 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700663 final String pkgName = getPackageName(intent);
664 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
665
Christopher Tateee7805b2016-07-15 16:56:56 -0700666 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700667 // Purge the app's jobs if the whole package was just disabled. When this is
668 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700669 if (pkgName != null && pkgUid != -1) {
670 final String[] changedComponents = intent.getStringArrayExtra(
671 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
672 if (changedComponents != null) {
673 for (String component : changedComponents) {
674 if (component.equals(pkgName)) {
675 if (DEBUG) {
676 Slog.d(TAG, "Package state change: " + pkgName);
677 }
678 try {
679 final int userId = UserHandle.getUserId(pkgUid);
680 IPackageManager pm = AppGlobals.getPackageManager();
681 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
682 if (state == COMPONENT_ENABLED_STATE_DISABLED
683 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
684 if (DEBUG) {
685 Slog.d(TAG, "Removing jobs for package " + pkgName
686 + " in user " + userId);
687 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700688 cancelJobsForPackageAndUid(pkgName, pkgUid,
689 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700690 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700691 } catch (RemoteException|IllegalArgumentException e) {
692 /*
693 * IllegalArgumentException means that the package doesn't exist.
694 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
695 * behind outright uninstall, so by the time we try to act it's gone.
696 * We don't need to act on this PACKAGE_CHANGED when this happens;
697 * we'll get a PACKAGE_REMOVED later and clean up then.
698 *
699 * RemoteException can't actually happen; the package manager is
700 * running in this same process.
701 */
702 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700703 break;
704 }
705 }
706 }
707 } else {
708 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
709 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700710 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700711 // If this is an outright uninstall rather than the first half of an
712 // app update sequence, cancel the jobs associated with the app.
713 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
714 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
715 if (DEBUG) {
716 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
717 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700718 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700719 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700720 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700721 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
722 if (DEBUG) {
723 Slog.d(TAG, "Removing jobs for user: " + userId);
724 }
725 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700726 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
727 // Has this package scheduled any jobs, such that we will take action
728 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700729 if (pkgUid != -1) {
730 List<JobStatus> jobsForUid;
731 synchronized (mLock) {
732 jobsForUid = mJobs.getJobsByUid(pkgUid);
733 }
734 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
735 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
736 if (DEBUG) {
737 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
738 + pkgUid + " has jobs");
739 }
740 setResultCode(Activity.RESULT_OK);
741 break;
742 }
743 }
744 }
745 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
746 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700747 if (pkgUid != -1) {
748 if (DEBUG) {
749 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
750 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700751 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700752 }
Christopher Tate7060b042014-06-09 19:50:00 -0700753 }
754 }
755 };
756
Christopher Tateb5c07882016-05-26 17:11:09 -0700757 private String getPackageName(Intent intent) {
758 Uri uri = intent.getData();
759 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
760 return pkg;
761 }
762
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700763 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700764 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800765 mHandler.obtainMessage(MSG_UID_STATE_CHANGED, uid, procState).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700766 }
767
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700768 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800769 mHandler.obtainMessage(MSG_UID_GONE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700770 }
771
772 @Override public void onUidActive(int uid) throws RemoteException {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800773 mHandler.obtainMessage(MSG_UID_ACTIVE, uid, 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700774 }
775
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700776 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800777 mHandler.obtainMessage(MSG_UID_IDLE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700778 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700779
780 @Override public void onUidCachedChanged(int uid, boolean cached) {
781 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700782 };
783
Jeff Sharkey4d89e422018-03-29 18:22:41 -0600784 public Context getTestableContext() {
785 return getContext();
786 }
787
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800788 public Object getLock() {
789 return mLock;
790 }
791
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700792 public JobStore getJobStore() {
793 return mJobs;
794 }
795
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700796 public Constants getConstants() {
797 return mConstants;
798 }
799
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700800 @Override
801 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700802 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
803 // Let's kick any outstanding jobs for this user.
804 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
805 }
806
807 @Override
808 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700809 // Let's kick any outstanding jobs for this user.
810 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
811 }
812
813 @Override
814 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700815 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700816 }
817
Makoto Onuki15407842018-01-19 14:23:11 -0800818 /**
Makoto Onukie4918212018-02-06 11:30:15 -0800819 * Return whether an UID is active or idle.
Makoto Onuki15407842018-01-19 14:23:11 -0800820 */
Makoto Onukie4918212018-02-06 11:30:15 -0800821 private boolean isUidActive(int uid) {
822 return mAppStateTracker.isUidActiveSynced(uid);
Makoto Onuki15407842018-01-19 14:23:11 -0800823 }
824
Makoto Onukie4918212018-02-06 11:30:15 -0800825 private final Predicate<Integer> mIsUidActivePredicate = this::isUidActive;
Makoto Onuki15407842018-01-19 14:23:11 -0800826
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700827 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
828 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700829 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800830 if (ActivityManager.getService().isAppStartModeDisabled(uId,
831 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700832 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
833 + " -- package not allowed to start");
834 return JobScheduler.RESULT_FAILURE;
835 }
836 } catch (RemoteException e) {
837 }
Christopher Tatea732f012017-10-26 17:26:53 -0700838
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800839 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700840 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
841
842 if (work != null && toCancel != null) {
843 // Fast path: we are adding work to an existing job, and the JobInfo is not
844 // changing. We can just directly enqueue this work in to the job.
845 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -0800846
Dianne Hackborn342e6032017-04-13 18:04:31 -0700847 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Makoto Onuki15407842018-01-19 14:23:11 -0800848
849 // If any of work item is enqueued when the source is in the foreground,
850 // exempt the entire job.
Makoto Onukie4918212018-02-06 11:30:15 -0800851 toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800852
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700853 return JobScheduler.RESULT_SUCCESS;
854 }
855 }
856
857 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -0800858
859 // Give exemption if the source is in the foreground just now.
860 // Note if it's a sync job, this method is called on the handler so it's not exactly
861 // the state when requestSync() was called, but that should be fine because of the
862 // 1 minute foreground grace period.
Makoto Onukie4918212018-02-06 11:30:15 -0800863 jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800864
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700865 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800866 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800867 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800868 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
869 Slog.w(TAG, "Too many jobs for uid " + uId);
870 throw new IllegalStateException("Apps may not schedule more than "
871 + MAX_JOBS_PER_APP + " distinct jobs");
872 }
873 }
874
Dianne Hackborna47223f2017-03-30 13:49:13 -0700875 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700876 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700877
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700878 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700879 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700880 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700881 if (work != null) {
882 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700883 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700884 }
885 startTrackingJobLocked(jobStatus, toCancel);
Tej Singhd5747a62018-01-08 20:57:35 -0800886 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -0800887 uId, null, jobStatus.getBatteryName(),
Tej Singh33a412b2018-03-16 18:43:59 -0700888 StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
889 JobProtoEnums.STOP_REASON_CANCELLED);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700890
891 // If the job is immediately ready to run, then we can just immediately
892 // put it in the pending list and try to schedule it. This is especially
893 // important for jobs with a 0 deadline constraint, since they will happen a fair
894 // amount, we want to handle them as quickly as possible, and semantically we want to
895 // make sure we have started holding the wake lock for the job before returning to
896 // the caller.
897 // If the job is not yet ready to run, there is nothing more to do -- we are
898 // now just waiting for one of its controllers to change state and schedule
899 // the job appropriately.
900 if (isReadyToBeExecutedLocked(jobStatus)) {
901 // This is a new job, we can just immediately put it on the pending
902 // list and try to run it.
903 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700904 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700905 maybeRunPendingJobsLocked();
906 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800907 }
Christopher Tate7060b042014-06-09 19:50:00 -0700908 return JobScheduler.RESULT_SUCCESS;
909 }
910
911 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800912 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800913 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
914 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
915 for (int i = jobs.size() - 1; i >= 0; i--) {
916 JobStatus job = jobs.get(i);
917 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700918 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800919 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700920 }
Christopher Tate7060b042014-06-09 19:50:00 -0700921 }
922
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600923 public JobInfo getPendingJob(int uid, int jobId) {
924 synchronized (mLock) {
925 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
926 for (int i = jobs.size() - 1; i >= 0; i--) {
927 JobStatus job = jobs.get(i);
928 if (job.getJobId() == jobId) {
929 return job.getJob();
930 }
931 }
932 return null;
933 }
934 }
935
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700936 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800937 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700938 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
939 for (int i=0; i<jobsForUser.size(); i++) {
940 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700941 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700942 }
Christopher Tate7060b042014-06-09 19:50:00 -0700943 }
944 }
945
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700946 private void cancelJobsForNonExistentUsers() {
947 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
948 synchronized (mLock) {
949 mJobs.removeJobsOfNonUsers(umi.getUserIds());
950 }
951 }
952
Makoto Onukie7b96182017-08-30 14:53:16 -0700953 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
954 if ("android".equals(pkgName)) {
955 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
956 return;
957 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700958 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700959 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
960 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
961 final JobStatus job = jobsForUid.get(i);
962 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700963 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700964 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700965 }
966 }
967 }
968
Christopher Tate7060b042014-06-09 19:50:00 -0700969 /**
970 * Entry point from client to cancel all jobs originating from their uid.
971 * This will remove the job from the master list, and cancel the job if it was staged for
972 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700973 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800974 *
Christopher Tate7060b042014-06-09 19:50:00 -0700975 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700976 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700977 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700978 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700979 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700980 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700981
982 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800983 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700984 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
985 for (int i=0; i<jobsForUid.size(); i++) {
986 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700987 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700988 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700989 }
Christopher Tate7060b042014-06-09 19:50:00 -0700990 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700991 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700992 }
993
994 /**
995 * Entry point from client to cancel the job corresponding to the jobId provided.
996 * This will remove the job from the master list, and cancel the job if it was staged for
997 * execution or being executed.
998 * @param uid Uid of the calling client.
999 * @param jobId Id of the job, provided at schedule-time.
1000 */
Makoto Onukid2bfec62018-01-12 13:58:01 -08001001 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -07001002 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001003 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -07001004 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001005 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -08001006 cancelJobImplLocked(toCancel, null,
1007 "cancel() called by app, callingUid=" + callingUid
1008 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001009 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001010 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -07001011 }
1012 }
1013
Dianne Hackborn729a3282017-06-09 16:06:01 -07001014 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001015 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
1016 cancelled.unprepareLocked(ActivityManager.getService());
1017 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
1018 // Remove from pending queue.
1019 if (mPendingJobs.remove(cancelled)) {
1020 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -07001021 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001022 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -07001023 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001024 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001025 }
1026
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001027 void updateUidState(int uid, int procState) {
1028 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001029 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1030 // Only use this if we are exactly the top app. All others can live
1031 // with just the foreground priority. This means that persistent processes
1032 // can never be the top app priority... that is fine.
1033 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001034 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001035 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001036 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001037 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001038 }
1039 }
1040 }
1041
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001042 @Override
1043 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001044 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001045 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001046 // When becoming idle, make sure no jobs are actively running,
1047 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001048 for (int i=0; i<mActiveServices.size(); i++) {
1049 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001050 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001051 if (executing != null
1052 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001053 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1054 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001055 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001056 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001057 } else {
1058 // When coming out of idle, allow thing to start back up.
1059 if (mReadyToRock) {
1060 if (mLocalDeviceIdleController != null) {
1061 if (!mReportedActive) {
1062 mReportedActive = true;
1063 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001064 }
1065 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001066 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001067 }
1068 }
1069 }
1070 }
1071
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001072 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001073 // active is true if pending queue contains jobs OR some job is running.
1074 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001075 if (mPendingJobs.size() <= 0) {
1076 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001077 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001078 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001079 if (job != null
1080 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
Christopher Tate20afddd2018-02-28 15:19:19 -08001081 && !job.dozeWhitelisted
1082 && !job.uidActive) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001083 // We will report active if we have a job running and it is not an exception
1084 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001085 active = true;
1086 break;
1087 }
1088 }
1089 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001090
1091 if (mReportedActive != active) {
1092 mReportedActive = active;
1093 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001094 mLocalDeviceIdleController.setJobsActive(active);
1095 }
1096 }
1097 }
1098
Christopher Tated117b292018-01-05 17:32:36 -08001099 void reportAppUsage(String packageName, int userId) {
1100 // This app just transitioned into interactive use or near equivalent, so we should
1101 // take a look at its job state for feedback purposes.
1102 }
1103
Christopher Tate7060b042014-06-09 19:50:00 -07001104 /**
1105 * Initializes the system service.
1106 * <p>
1107 * Subclasses must define a single argument constructor that accepts the context
1108 * and passes it to super.
1109 * </p>
1110 *
1111 * @param context The system server context.
1112 */
1113 public JobSchedulerService(Context context) {
1114 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001115
1116 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Makoto Onuki15407842018-01-19 14:23:11 -08001117 mActivityManagerInternal = Preconditions.checkNotNull(
1118 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001119
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001120 mHandler = new JobHandler(context.getMainLooper());
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001121 mConstants = new Constants();
1122 mConstantsObserver = new ConstantsObserver(mHandler);
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001123 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001124
1125 // Set up the app standby bucketing tracker
Christopher Tated1aebb32018-01-31 13:24:14 -08001126 mStandbyTracker = new StandbyTracker();
1127 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1128 mUsageStats.addAppIdleStateChangeListener(mStandbyTracker);
Christopher Tatea732f012017-10-26 17:26:53 -07001129
1130 // The job store needs to call back
1131 publishLocalService(JobSchedulerInternal.class, new LocalService());
1132
1133 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001134 mJobs = JobStore.initAndGet(this);
1135
Christopher Tate7060b042014-06-09 19:50:00 -07001136 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001137 mControllers = new ArrayList<StateController>();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001138 mControllers.add(new ConnectivityController(this));
1139 mControllers.add(new TimeController(this));
1140 mControllers.add(new IdleController(this));
1141 mBatteryController = new BatteryController(this);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001142 mControllers.add(mBatteryController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001143 mStorageController = new StorageController(this);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001144 mControllers.add(mStorageController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001145 mControllers.add(new BackgroundJobsController(this));
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001146 mControllers.add(new ContentObserverController(this));
1147 mDeviceIdleJobsController = new DeviceIdleJobsController(this);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001148 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001149
1150 // If the job store determined that it can't yet reschedule persisted jobs,
1151 // we need to start watching the clock.
1152 if (!mJobs.jobTimesInflatedValid()) {
1153 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1154 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1155 }
Christopher Tate7060b042014-06-09 19:50:00 -07001156 }
1157
Christopher Tate616541d2017-07-26 14:27:38 -07001158 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1159 @Override
1160 public void onReceive(Context context, Intent intent) {
1161 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1162 // When we reach clock sanity, recalculate the temporal windows
1163 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001164 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001165 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1166
1167 // We've done our job now, so stop watching the time.
1168 context.unregisterReceiver(this);
1169
1170 // And kick off the work to update the affected jobs, using a secondary
1171 // thread instead of chugging away here on the main looper thread.
1172 FgThread.getHandler().post(mJobTimeUpdater);
1173 }
1174 }
1175 }
1176 };
1177
1178 private final Runnable mJobTimeUpdater = () -> {
1179 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1180 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1181 synchronized (mLock) {
1182 // Note: we intentionally both look up the existing affected jobs and replace them
1183 // with recalculated ones inside the same lock lifetime.
1184 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1185
1186 // Now, at each position [i], we have both the existing JobStatus
1187 // and the one that replaces it.
1188 final int N = toAdd.size();
1189 for (int i = 0; i < N; i++) {
1190 final JobStatus oldJob = toRemove.get(i);
1191 final JobStatus newJob = toAdd.get(i);
1192 if (DEBUG) {
1193 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1194 }
1195 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1196 }
1197 }
1198 };
1199
Christopher Tate7060b042014-06-09 19:50:00 -07001200 @Override
1201 public void onStart() {
1202 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1203 }
1204
1205 @Override
1206 public void onBootPhase(int phase) {
1207 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001208 mConstantsObserver.start(getContext().getContentResolver());
Makoto Onuki15407842018-01-19 14:23:11 -08001209
Makoto Onukie4918212018-02-06 11:30:15 -08001210 mAppStateTracker = Preconditions.checkNotNull(
1211 LocalServices.getService(AppStateTracker.class));
Christopher Tated1aebb32018-01-31 13:24:14 -08001212 setNextHeartbeatAlarm();
Makoto Onuki15407842018-01-19 14:23:11 -08001213
Shreyas Basarge5db09082016-01-07 13:38:29 +00001214 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001215 final IntentFilter filter = new IntentFilter();
1216 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1217 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001218 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1219 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001220 filter.addDataScheme("package");
1221 getContext().registerReceiverAsUser(
1222 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1223 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1224 getContext().registerReceiverAsUser(
1225 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001226 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001227 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001228 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001229 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1230 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001231 } catch (RemoteException e) {
1232 // ignored; both services live in system_server
1233 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001234 // Remove any jobs that are not associated with any of the current users.
1235 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001236 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001237 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001238 // Let's go!
1239 mReadyToRock = true;
1240 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1241 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001242 mLocalDeviceIdleController
1243 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001244 // Create the "runners".
1245 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1246 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001247 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001248 getContext().getMainLooper()));
1249 }
1250 // Attach jobs to their controllers.
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001251 mJobs.forEachJob((job) -> {
1252 for (int controller = 0; controller < mControllers.size(); controller++) {
1253 final StateController sc = mControllers.get(controller);
1254 sc.maybeStartTrackingJobLocked(job, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001255 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001256 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001257 // GO GO GO!
1258 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1259 }
Christopher Tate7060b042014-06-09 19:50:00 -07001260 }
1261 }
1262
1263 /**
1264 * Called when we have a job status object that we need to insert in our
1265 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1266 * about.
1267 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001268 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1269 if (!jobStatus.isPreparedLocked()) {
1270 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1271 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001272 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001273 final boolean update = mJobs.add(jobStatus);
1274 if (mReadyToRock) {
1275 for (int i = 0; i < mControllers.size(); i++) {
1276 StateController controller = mControllers.get(i);
1277 if (update) {
1278 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001279 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001280 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001281 }
Christopher Tate7060b042014-06-09 19:50:00 -07001282 }
1283 }
1284
1285 /**
1286 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1287 * object removed.
1288 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001289 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001290 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001291 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001292 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001293
1294 // Remove from store as well as controllers.
1295 final boolean removed = mJobs.remove(jobStatus, writeBack);
1296 if (removed && mReadyToRock) {
1297 for (int i=0; i<mControllers.size(); i++) {
1298 StateController controller = mControllers.get(i);
1299 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001300 }
1301 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001302 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001303 }
1304
Dianne Hackborn729a3282017-06-09 16:06:01 -07001305 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001306 for (int i=0; i<mActiveServices.size(); i++) {
1307 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001308 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001309 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001310 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001311 return true;
1312 }
1313 }
1314 return false;
1315 }
1316
1317 /**
1318 * @param job JobStatus we are querying against.
1319 * @return Whether or not the job represented by the status object is currently being run or
1320 * is pending.
1321 */
1322 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001323 for (int i=0; i<mActiveServices.size(); i++) {
1324 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001325 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001326 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1327 return true;
1328 }
1329 }
1330 return false;
1331 }
1332
Dianne Hackborn807de782016-04-07 17:54:41 -07001333 void noteJobsPending(List<JobStatus> jobs) {
1334 for (int i = jobs.size() - 1; i >= 0; i--) {
1335 JobStatus job = jobs.get(i);
1336 mJobPackageTracker.notePending(job);
1337 }
1338 }
1339
1340 void noteJobsNonpending(List<JobStatus> jobs) {
1341 for (int i = jobs.size() - 1; i >= 0; i--) {
1342 JobStatus job = jobs.get(i);
1343 mJobPackageTracker.noteNonpending(job);
1344 }
1345 }
1346
Christopher Tate7060b042014-06-09 19:50:00 -07001347 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001348 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1349 * specify an override deadline on a failed job (the failed job will run even though it's not
1350 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1351 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1352 *
Christopher Tate7060b042014-06-09 19:50:00 -07001353 * @param failureToReschedule Provided job status that we will reschedule.
1354 * @return A newly instantiated JobStatus with the same constraints as the last job except
1355 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001356 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001357 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001358 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001359 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001360 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001361 final JobInfo job = failureToReschedule.getJob();
1362
1363 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001364 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1365 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001366
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001367 if (failureToReschedule.hasWorkLocked()) {
1368 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1369 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1370 + backoffAttempts + " > work limit "
1371 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1372 return null;
1373 }
1374 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1375 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1376 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1377 return null;
1378 }
1379
Christopher Tate7060b042014-06-09 19:50:00 -07001380 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001381 case JobInfo.BACKOFF_POLICY_LINEAR: {
1382 long backoff = initialBackoffMillis;
1383 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1384 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1385 }
1386 delayMillis = backoff * backoffAttempts;
1387 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001388 default:
1389 if (DEBUG) {
1390 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1391 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001392 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1393 long backoff = initialBackoffMillis;
1394 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1395 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1396 }
1397 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1398 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001399 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001400 delayMillis =
1401 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001402 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1403 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001404 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001405 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001406 for (int ic=0; ic<mControllers.size(); ic++) {
1407 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001408 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001409 }
1410 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001411 }
1412
1413 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001414 * Called after a periodic has executed so we can reschedule it. We take the last execution
1415 * time of the job to be the time of completion (i.e. the time at which this function is
1416 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001417 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001418 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1419 * to underscheduling at least, rather than if we had taken the last execution time to be the
1420 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001421 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1422 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001423 * @return A new job representing the execution criteria for this instantiation of the
1424 * recurring job.
1425 */
1426 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001427 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001428 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001429 long runEarly = 0L;
1430
1431 // If this periodic was rescheduled it won't have a deadline.
1432 if (periodicToReschedule.hasDeadlineConstraint()) {
1433 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1434 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001435 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001436 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001437 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1438 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001439
1440 if (DEBUG) {
1441 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1442 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1443 }
Christopher Tatea732f012017-10-26 17:26:53 -07001444 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1445 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1446 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001447 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001448 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001449 }
1450
Christopher Tate325768c2018-03-07 16:07:56 -08001451 /*
1452 * We default to "long enough ago that every bucket's jobs are immediately runnable" to
1453 * avoid starvation of apps in uncommon-use buckets that might arise from repeated
1454 * reboot behavior.
1455 */
Christopher Tated1aebb32018-01-31 13:24:14 -08001456 long heartbeatWhenJobsLastRun(String packageName, final @UserIdInt int userId) {
Christopher Tate325768c2018-03-07 16:07:56 -08001457 // The furthest back in pre-boot time that we need to bother with
1458 long heartbeat = -mConstants.STANDBY_BEATS[RARE_INDEX];
1459 boolean cacheHit = false;
Christopher Tated1aebb32018-01-31 13:24:14 -08001460 synchronized (mLock) {
Christopher Tate325768c2018-03-07 16:07:56 -08001461 HashMap<String, Long> jobPackages = mLastJobHeartbeats.get(userId);
1462 if (jobPackages != null) {
1463 long cachedValue = jobPackages.getOrDefault(packageName, Long.MAX_VALUE);
1464 if (cachedValue < Long.MAX_VALUE) {
1465 cacheHit = true;
1466 heartbeat = cachedValue;
1467 }
1468 }
1469 if (!cacheHit) {
1470 // We haven't seen it yet; ask usage stats about it
1471 final long timeSinceJob = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
1472 if (timeSinceJob < Long.MAX_VALUE) {
1473 // Usage stats knows about it from before, so calculate back from that
1474 // and go from there.
1475 heartbeat = mHeartbeat - (timeSinceJob / mConstants.STANDBY_HEARTBEAT_TIME);
1476 }
1477 // If usage stats returned its "not found" MAX_VALUE, we still have the
1478 // negative default 'heartbeat' value we established above
1479 setLastJobHeartbeatLocked(packageName, userId, heartbeat);
1480 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001481 }
1482 if (DEBUG_STANDBY) {
Christopher Tate325768c2018-03-07 16:07:56 -08001483 Slog.v(TAG, "Last job heartbeat " + heartbeat + " for "
1484 + packageName + "/" + userId);
Christopher Tated1aebb32018-01-31 13:24:14 -08001485 }
1486 return heartbeat;
1487 }
1488
1489 long heartbeatWhenJobsLastRun(JobStatus job) {
1490 return heartbeatWhenJobsLastRun(job.getSourcePackageName(), job.getSourceUserId());
1491 }
1492
Christopher Tate325768c2018-03-07 16:07:56 -08001493 void setLastJobHeartbeatLocked(String packageName, int userId, long heartbeat) {
1494 HashMap<String, Long> jobPackages = mLastJobHeartbeats.get(userId);
1495 if (jobPackages == null) {
1496 jobPackages = new HashMap<>();
1497 mLastJobHeartbeats.put(userId, jobPackages);
1498 }
1499 jobPackages.put(packageName, heartbeat);
1500 }
1501
Christopher Tate7060b042014-06-09 19:50:00 -07001502 // JobCompletedListener implementations.
1503
1504 /**
1505 * A job just finished executing. We fetch the
1506 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
Christopher Tate325768c2018-03-07 16:07:56 -08001507 * whether we want to reschedule we re-add it to the controllers.
Christopher Tate7060b042014-06-09 19:50:00 -07001508 * @param jobStatus Completed job.
1509 * @param needsReschedule Whether the implementing class should reschedule this job.
1510 */
1511 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001512 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001513 if (DEBUG) {
1514 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1515 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001516
1517 // If the job wants to be rescheduled, we first need to make the next upcoming
1518 // job so we can transfer any appropriate state over from the previous job when
1519 // we stop it.
1520 final JobStatus rescheduledJob = needsReschedule
1521 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1522
Shreyas Basarge73f10252016-02-11 17:06:13 +00001523 // Do not write back immediately if this is a periodic job. The job may get lost if system
1524 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001525 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001526 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001527 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001528 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001529 // We still want to check for jobs to execute, because this job may have
1530 // scheduled a new job under the same job id, and now we can run it.
1531 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001532 return;
1533 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001534
1535 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001536 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001537 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001538 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001539 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001540 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001541 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001542 } else if (jobStatus.getJob().isPeriodic()) {
1543 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001544 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001545 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001546 } catch (SecurityException e) {
1547 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1548 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001549 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001550 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001551 jobStatus.unprepareLocked(ActivityManager.getService());
1552 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001553 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001554 }
1555
1556 // StateChangedListener implementations.
1557
1558 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001559 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1560 * some controller's state has changed, so as to run through the list of jobs and start/stop
1561 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001562 */
1563 @Override
1564 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001565 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001566 }
1567
1568 @Override
1569 public void onRunJobNow(JobStatus jobStatus) {
1570 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1571 }
1572
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001573 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001574
1575 public JobHandler(Looper looper) {
1576 super(looper);
1577 }
1578
1579 @Override
1580 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001581 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001582 if (!mReadyToRock) {
1583 return;
1584 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001585 switch (message.what) {
1586 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001587 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001588 // runNow can be null, which is a controller's way of indicating that its
1589 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001590 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001591 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001592 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001593 } else {
1594 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001595 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001596 } break;
1597 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001598 if (mReportedActive) {
1599 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001600 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001601 } else {
1602 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001603 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001604 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001605 break;
1606 case MSG_CHECK_JOB_GREEDY:
1607 queueReadyJobsForExecutionLocked();
1608 break;
1609 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001610 cancelJobImplLocked((JobStatus) message.obj, null,
1611 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001612 break;
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001613
1614 case MSG_UID_STATE_CHANGED: {
1615 final int uid = message.arg1;
1616 final int procState = message.arg2;
1617 updateUidState(uid, procState);
1618 break;
1619 }
1620 case MSG_UID_GONE: {
1621 final int uid = message.arg1;
1622 final boolean disabled = message.arg2 != 0;
1623 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1624 if (disabled) {
1625 cancelJobsForUid(uid, "uid gone");
1626 }
1627 synchronized (mLock) {
1628 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1629 }
1630 break;
1631 }
1632 case MSG_UID_ACTIVE: {
1633 final int uid = message.arg1;
1634 synchronized (mLock) {
1635 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
1636 }
1637 break;
1638 }
1639 case MSG_UID_IDLE: {
1640 final int uid = message.arg1;
1641 final boolean disabled = message.arg2 != 0;
1642 if (disabled) {
1643 cancelJobsForUid(uid, "app uid idle");
1644 }
1645 synchronized (mLock) {
1646 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1647 }
1648 break;
1649 }
1650
Matthew Williams75fc5252014-09-02 16:17:53 -07001651 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001652 maybeRunPendingJobsLocked();
1653 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1654 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001655 }
1656 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001657 }
Christopher Tate7060b042014-06-09 19:50:00 -07001658
Dianne Hackborn6d068262017-05-16 13:14:37 -07001659 private void stopNonReadyActiveJobsLocked() {
1660 for (int i=0; i<mActiveServices.size(); i++) {
1661 JobServiceContext serviceContext = mActiveServices.get(i);
1662 final JobStatus running = serviceContext.getRunningJobLocked();
1663 if (running != null && !running.isReady()) {
1664 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001665 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1666 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001667 }
1668 }
1669 }
1670
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001671 /**
1672 * Run through list of jobs and execute all possible - at least one is expired so we do
1673 * as many as we can.
1674 */
1675 private void queueReadyJobsForExecutionLocked() {
1676 if (DEBUG) {
1677 Slog.d(TAG, "queuing all ready jobs for execution:");
1678 }
1679 noteJobsNonpending(mPendingJobs);
1680 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001681 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001682 mJobs.forEachJob(mReadyQueueFunctor);
1683 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001684
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001685 if (DEBUG) {
1686 final int queuedJobs = mPendingJobs.size();
1687 if (queuedJobs == 0) {
1688 Slog.d(TAG, "No jobs pending.");
1689 } else {
1690 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001691 }
1692 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001693 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001694
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001695 final class ReadyJobQueueFunctor implements Consumer<JobStatus> {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001696 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001697
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001698 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001699 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001700 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001701 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001702 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001703 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001704 if (newReadyJobs == null) {
1705 newReadyJobs = new ArrayList<JobStatus>();
1706 }
1707 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001708 }
1709 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001710
1711 public void postProcess() {
1712 if (newReadyJobs != null) {
1713 noteJobsPending(newReadyJobs);
1714 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001715 if (mPendingJobs.size() > 1) {
1716 mPendingJobs.sort(mEnqueueTimeComparator);
1717 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001718 }
1719 newReadyJobs = null;
1720 }
1721 }
1722 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1723
1724 /**
1725 * The state of at least one job has changed. Here is where we could enforce various
1726 * policies on when we want to execute jobs.
1727 * Right now the policy is such:
1728 * If >1 of the ready jobs is idle mode we send all of them off
1729 * if more than 2 network connectivity jobs are ready we send them all off.
1730 * If more than 4 jobs total are ready we send them all off.
1731 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1732 */
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001733 final class MaybeReadyJobQueueFunctor implements Consumer<JobStatus> {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001734 int chargingCount;
1735 int batteryNotLowCount;
1736 int storageNotLowCount;
1737 int idleCount;
1738 int backoffCount;
1739 int connectivityCount;
1740 int contentCount;
1741 List<JobStatus> runnableJobs;
1742
1743 public MaybeReadyJobQueueFunctor() {
1744 reset();
1745 }
1746
1747 // Functor method invoked for each job via JobStore.forEachJob()
1748 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001749 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001750 if (isReadyToBeExecutedLocked(job)) {
1751 try {
1752 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1753 job.getJob().getService().getPackageName())) {
1754 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1755 + job.getJob().toString() + " -- package not allowed to start");
1756 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1757 return;
1758 }
1759 } catch (RemoteException e) {
1760 }
1761 if (job.getNumFailures() > 0) {
1762 backoffCount++;
1763 }
1764 if (job.hasIdleConstraint()) {
1765 idleCount++;
1766 }
1767 if (job.hasConnectivityConstraint()) {
1768 connectivityCount++;
1769 }
1770 if (job.hasChargingConstraint()) {
1771 chargingCount++;
1772 }
1773 if (job.hasBatteryNotLowConstraint()) {
1774 batteryNotLowCount++;
1775 }
1776 if (job.hasStorageNotLowConstraint()) {
1777 storageNotLowCount++;
1778 }
1779 if (job.hasContentTriggerConstraint()) {
1780 contentCount++;
1781 }
1782 if (runnableJobs == null) {
1783 runnableJobs = new ArrayList<>();
1784 }
1785 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001786 }
1787 }
1788
1789 public void postProcess() {
1790 if (backoffCount > 0 ||
1791 idleCount >= mConstants.MIN_IDLE_COUNT ||
1792 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1793 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1794 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1795 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1796 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1797 (runnableJobs != null
1798 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1799 if (DEBUG) {
1800 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1801 }
1802 noteJobsPending(runnableJobs);
1803 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001804 if (mPendingJobs.size() > 1) {
1805 mPendingJobs.sort(mEnqueueTimeComparator);
1806 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001807 } else {
1808 if (DEBUG) {
1809 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1810 }
1811 }
1812
1813 // Be ready for next time
1814 reset();
1815 }
1816
1817 private void reset() {
1818 chargingCount = 0;
1819 idleCount = 0;
1820 backoffCount = 0;
1821 connectivityCount = 0;
1822 batteryNotLowCount = 0;
1823 storageNotLowCount = 0;
1824 contentCount = 0;
1825 runnableJobs = null;
1826 }
1827 }
1828 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1829
1830 private void maybeQueueReadyJobsForExecutionLocked() {
1831 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1832
1833 noteJobsNonpending(mPendingJobs);
1834 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001835 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001836 mJobs.forEachJob(mMaybeQueueFunctor);
1837 mMaybeQueueFunctor.postProcess();
1838 }
1839
Christopher Tated1aebb32018-01-31 13:24:14 -08001840 /**
1841 * Heartbeat tracking. The heartbeat alarm is intentionally non-wakeup.
1842 */
1843 class HeartbeatAlarmListener implements AlarmManager.OnAlarmListener {
1844
1845 @Override
1846 public void onAlarm() {
1847 synchronized (mLock) {
1848 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1849 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1850 if (beatsElapsed > 0) {
1851 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1852 advanceHeartbeatLocked(beatsElapsed);
1853 }
Christopher Tatea732f012017-10-26 17:26:53 -07001854 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001855 setNextHeartbeatAlarm();
Christopher Tatea732f012017-10-26 17:26:53 -07001856 }
Christopher Tatea732f012017-10-26 17:26:53 -07001857 }
1858
Christopher Tated1aebb32018-01-31 13:24:14 -08001859 // Intentionally does not touch the alarm timing
1860 void advanceHeartbeatLocked(long beatsElapsed) {
1861 mHeartbeat += beatsElapsed;
1862 if (DEBUG_STANDBY) {
1863 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed
1864 + " to " + mHeartbeat);
1865 }
1866 // Don't update ACTIVE or NEVER bucket milestones. Note that mHeartbeat
1867 // will be equal to mNextBucketHeartbeat[bucket] for one beat, during which
1868 // new jobs scheduled by apps in that bucket will be permitted to run
1869 // immediately.
1870 boolean didAdvanceBucket = false;
Christopher Tatea732f012017-10-26 17:26:53 -07001871 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
Christopher Tated1aebb32018-01-31 13:24:14 -08001872 // Did we reach or cross a bucket boundary?
1873 if (mHeartbeat >= mNextBucketHeartbeat[i]) {
1874 didAdvanceBucket = true;
1875 }
1876 while (mHeartbeat > mNextBucketHeartbeat[i]) {
Christopher Tatea732f012017-10-26 17:26:53 -07001877 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1878 }
1879 if (DEBUG_STANDBY) {
Christopher Tated1aebb32018-01-31 13:24:14 -08001880 Slog.v(TAG, " Bucket " + i + " next heartbeat "
1881 + mNextBucketHeartbeat[i]);
Christopher Tatea732f012017-10-26 17:26:53 -07001882 }
1883 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001884
1885 if (didAdvanceBucket) {
1886 if (DEBUG_STANDBY) {
1887 Slog.v(TAG, "Hit bucket boundary; reevaluating job runnability");
1888 }
1889 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1890 }
1891 }
1892
1893 void setNextHeartbeatAlarm() {
1894 final long heartbeatLength;
1895 synchronized (mLock) {
1896 heartbeatLength = mConstants.STANDBY_HEARTBEAT_TIME;
1897 }
1898 final long now = sElapsedRealtimeClock.millis();
1899 final long nextBeatOrdinal = (now + heartbeatLength) / heartbeatLength;
1900 final long nextHeartbeat = nextBeatOrdinal * heartbeatLength;
1901 if (DEBUG_STANDBY) {
1902 Slog.i(TAG, "Setting heartbeat alarm for " + nextHeartbeat
1903 + " = " + TimeUtils.formatDuration(nextHeartbeat - now));
1904 }
1905 AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1906 am.setExact(AlarmManager.ELAPSED_REALTIME, nextHeartbeat,
1907 HEARTBEAT_TAG, mHeartbeatAlarm, mHandler);
Christopher Tatea732f012017-10-26 17:26:53 -07001908 }
1909
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001910 /**
1911 * Criteria for moving a job into the pending queue:
1912 * - It's ready.
1913 * - It's not pending.
1914 * - It's not already running on a JSC.
1915 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001916 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001917 * - The component is enabled and runnable.
1918 */
1919 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001920 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001921
1922 if (DEBUG) {
1923 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1924 + " ready=" + jobReady);
1925 }
1926
1927 // This is a condition that is very likely to be false (most jobs that are
1928 // scheduled are sitting there, not ready yet) and very cheap to check (just
1929 // a few conditions on data in JobStatus).
1930 if (!jobReady) {
Christopher Tate20afddd2018-02-28 15:19:19 -08001931 if (job.getSourcePackageName().equals("android.jobscheduler.cts.jobtestapp")) {
1932 Slog.v(TAG, " NOT READY: " + job);
1933 }
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001934 return false;
1935 }
1936
1937 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001938
1939 final int userId = job.getUserId();
1940 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1941
1942 if (DEBUG) {
1943 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001944 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001945 }
1946
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001947 // These are also fairly cheap to check, though they typically will not
1948 // be conditions we fail.
1949 if (!jobExists || !userStarted) {
1950 return false;
1951 }
1952
1953 final boolean jobPending = mPendingJobs.contains(job);
1954 final boolean jobActive = isCurrentlyActiveLocked(job);
1955
1956 if (DEBUG) {
1957 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1958 + " pending=" + jobPending + " active=" + jobActive);
1959 }
1960
1961 // These can be a little more expensive (especially jobActive, since we need to
1962 // go through the array of all potentially active jobs), so we are doing them
1963 // later... but still before checking with the package manager!
1964 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001965 return false;
1966 }
1967
Christopher Tatea732f012017-10-26 17:26:53 -07001968 // If the app is in a non-active standby bucket, make sure we've waited
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001969 // an appropriate amount of time since the last invocation. During device-
1970 // wide parole, standby bucketing is ignored.
Makoto Onuki959acb52018-01-26 14:10:03 -08001971 //
Christopher Tate20afddd2018-02-28 15:19:19 -08001972 // Jobs in 'active' apps are not subject to standby, nor are jobs that are
1973 // specifically marked as exempt.
1974 if (DEBUG_STANDBY) {
1975 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1976 + " parole=" + mInParole + " active=" + job.uidActive
1977 + " exempt=" + job.getJob().isExemptedFromAppStandby());
1978 }
1979 if (!mInParole
1980 && !job.uidActive
1981 && !job.getJob().isExemptedFromAppStandby()) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001982 final int bucket = job.getStandbyBucket();
Christopher Tate20afddd2018-02-28 15:19:19 -08001983 if (DEBUG_STANDBY) {
1984 Slog.v(TAG, " bucket=" + bucket + " heartbeat=" + mHeartbeat
1985 + " next=" + mNextBucketHeartbeat[bucket]);
1986 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001987 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
Christopher Tated1aebb32018-01-31 13:24:14 -08001988 // Only skip this job if the app is still waiting for the end of its nominal
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001989 // bucket interval. Once it's waited that long, we let it go ahead and clear.
1990 // The final (NEVER) bucket is special; we never age those apps' jobs into
1991 // runnability.
Christopher Tated1aebb32018-01-31 13:24:14 -08001992 final long appLastRan = heartbeatWhenJobsLastRun(job);
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001993 if (bucket >= mConstants.STANDBY_BEATS.length
Christopher Tated1aebb32018-01-31 13:24:14 -08001994 || (mHeartbeat > appLastRan
1995 && mHeartbeat < appLastRan + mConstants.STANDBY_BEATS[bucket])) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001996 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
1997 if (job.getWhenStandbyDeferred() == 0) {
1998 if (DEBUG_STANDBY) {
1999 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
Christopher Tated1aebb32018-01-31 13:24:14 -08002000 + (appLastRan + mConstants.STANDBY_BEATS[bucket])
2001 + " for " + job);
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002002 }
2003 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tate0c4d7682017-12-06 15:10:22 -08002004 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002005 return false;
2006 } else {
2007 if (DEBUG_STANDBY) {
2008 Slog.v(TAG, "Bucket deferred job aged into runnability at "
2009 + mHeartbeat + " : " + job);
2010 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08002011 }
Christopher Tatea732f012017-10-26 17:26:53 -07002012 }
Christopher Tatea732f012017-10-26 17:26:53 -07002013 }
2014
2015 // The expensive check last: validate that the defined package+service is
2016 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002017 final boolean componentPresent;
2018 try {
2019 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2020 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2021 userId) != null);
2022 } catch (RemoteException e) {
2023 throw e.rethrowAsRuntimeException();
2024 }
2025
2026 if (DEBUG) {
2027 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2028 + " componentPresent=" + componentPresent);
2029 }
2030
2031 // Everything else checked out so far, so this is the final yes/no check
2032 return componentPresent;
2033 }
2034
2035 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002036 * Reconcile jobs in the pending queue against available execution contexts.
2037 * A controller can force a job into the pending queue even if it's already running, but
2038 * here is where we decide whether to actually execute it.
2039 */
2040 private void maybeRunPendingJobsLocked() {
2041 if (DEBUG) {
2042 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
2043 }
2044 assignJobsToContextsLocked();
2045 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07002046 }
2047
Dianne Hackborn807de782016-04-07 17:54:41 -07002048 private int adjustJobPriority(int curPriority, JobStatus job) {
2049 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
2050 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002051 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002052 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002053 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002054 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
2055 }
2056 }
2057 return curPriority;
2058 }
2059
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002060 private int evaluateJobPriorityLocked(JobStatus job) {
2061 int priority = job.getPriority();
2062 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002063 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002064 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002065 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
2066 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002067 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002068 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002069 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002070 }
2071
Christopher Tate7060b042014-06-09 19:50:00 -07002072 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00002073 * Takes jobs from pending queue and runs them on available contexts.
2074 * If no contexts are available, preempts lower priority jobs to
2075 * run higher priority ones.
2076 * Lock on mJobs before calling this function.
2077 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08002078 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002079 if (DEBUG) {
2080 Slog.d(TAG, printPendingQueue());
2081 }
2082
Dianne Hackborn970510b2016-02-24 16:56:42 -08002083 int memLevel;
2084 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002085 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002086 } catch (RemoteException e) {
2087 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
2088 }
2089 switch (memLevel) {
2090 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002091 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002092 break;
2093 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002094 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002095 break;
2096 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002097 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002098 break;
2099 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002100 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002101 break;
2102 }
2103
2104 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
2105 boolean[] act = mTmpAssignAct;
2106 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
2107 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002108 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002109 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
2110 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002111 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002112 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002113 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002114 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
2115 numForeground++;
2116 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002117 }
2118 act[i] = false;
2119 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002120 }
2121 if (DEBUG) {
2122 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
2123 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002124 for (int i=0; i<mPendingJobs.size(); i++) {
2125 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002126
2127 // If job is already running, go to next job.
2128 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
2129 if (jobRunningContext != -1) {
2130 continue;
2131 }
2132
Dianne Hackborn970510b2016-02-24 16:56:42 -08002133 final int priority = evaluateJobPriorityLocked(nextPending);
2134 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002135
Shreyas Basarge5db09082016-01-07 13:38:29 +00002136 // Find a context for nextPending. The context should be available OR
2137 // it should have lowest priority among all running jobs
2138 // (sharing the same Uid as nextPending)
2139 int minPriority = Integer.MAX_VALUE;
2140 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002141 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
2142 JobStatus job = contextIdToJobMap[j];
2143 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00002144 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002145 if ((numActive < mMaxActiveJobs ||
2146 (priority >= JobInfo.PRIORITY_TOP_APP &&
2147 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08002148 (preferredUid == nextPending.getUid() ||
2149 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
2150 // This slot is free, and we haven't yet hit the limit on
2151 // concurrent jobs... we can just throw the job in to here.
2152 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002153 break;
2154 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00002155 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08002156 // the context has a preferred Uid or we have reached the limit on
2157 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00002158 continue;
2159 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002160 if (job.getUid() != nextPending.getUid()) {
2161 continue;
2162 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002163 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002164 continue;
2165 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002166 if (minPriority > nextPending.lastEvaluatedPriority) {
2167 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002168 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00002169 }
2170 }
2171 if (minPriorityContextId != -1) {
2172 contextIdToJobMap[minPriorityContextId] = nextPending;
2173 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002174 numActive++;
2175 if (priority >= JobInfo.PRIORITY_TOP_APP) {
2176 numForeground++;
2177 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002178 }
2179 }
2180 if (DEBUG) {
2181 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
2182 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002183 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002184 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002185 boolean preservePreferredUid = false;
2186 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002187 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002188 if (js != null) {
2189 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002190 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00002191 }
2192 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07002193 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002194 preservePreferredUid = true;
2195 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002196 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00002197 if (DEBUG) {
2198 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002199 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002200 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002201 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002202 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002203 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002204 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
2205 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002206 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002207 if (mPendingJobs.remove(pendingJob)) {
2208 mJobPackageTracker.noteNonpending(pendingJob);
2209 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002210 }
2211 }
2212 if (!preservePreferredUid) {
2213 mActiveServices.get(i).clearPreferredUid();
2214 }
2215 }
2216 }
2217
2218 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
2219 for (int i=0; i<map.length; i++) {
2220 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
2221 return i;
2222 }
2223 }
2224 return -1;
2225 }
2226
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002227 final class LocalService implements JobSchedulerInternal {
2228
2229 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002230 * The current bucket heartbeat ordinal
2231 */
2232 public long currentHeartbeat() {
2233 return getCurrentHeartbeat();
2234 }
2235
2236 /**
2237 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2238 */
2239 public long nextHeartbeatForBucket(int bucket) {
2240 synchronized (mLock) {
2241 return mNextBucketHeartbeat[bucket];
2242 }
2243 }
2244
2245 /**
Christopher Tate435c2f42018-01-18 12:59:15 -08002246 * Heartbeat ordinal for the given app. This is typically the heartbeat at which
2247 * the app last ran jobs, so that a newly-scheduled job in an app that hasn't run
2248 * jobs in a long time is immediately runnable even if the app is bucketed into
2249 * an infrequent time allocation.
2250 */
2251 public long baseHeartbeatForApp(String packageName, @UserIdInt int userId,
2252 final int appStandbyBucket) {
2253 if (appStandbyBucket == 0 ||
2254 appStandbyBucket >= mConstants.STANDBY_BEATS.length) {
2255 // ACTIVE => everything can be run right away
2256 // NEVER => we won't run them anyway, so let them go in the future
2257 // as soon as the app enters normal use
Christopher Tated1aebb32018-01-31 13:24:14 -08002258 if (DEBUG_STANDBY) {
2259 Slog.v(TAG, "Base heartbeat forced ZERO for new job in "
2260 + packageName + "/" + userId);
2261 }
Christopher Tate435c2f42018-01-18 12:59:15 -08002262 return 0;
2263 }
2264
Christopher Tated1aebb32018-01-31 13:24:14 -08002265 final long baseHeartbeat = heartbeatWhenJobsLastRun(packageName, userId);
2266 if (DEBUG_STANDBY) {
2267 Slog.v(TAG, "Base heartbeat " + baseHeartbeat + " for new job in "
2268 + packageName + "/" + userId);
2269 }
2270 return baseHeartbeat;
Christopher Tate435c2f42018-01-18 12:59:15 -08002271 }
2272
Christopher Tate325768c2018-03-07 16:07:56 -08002273 public void noteJobStart(String packageName, int userId) {
2274 synchronized (mLock) {
2275 setLastJobHeartbeatLocked(packageName, userId, mHeartbeat);
2276 }
2277 }
2278
Christopher Tate435c2f42018-01-18 12:59:15 -08002279 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002280 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2281 * jobs are always considered pending.
2282 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002283 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002284 public List<JobInfo> getSystemScheduledPendingJobs() {
2285 synchronized (mLock) {
2286 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002287 mJobs.forEachJob(Process.SYSTEM_UID, (job) -> {
2288 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2289 pendingJobs.add(job.getJob());
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002290 }
2291 });
2292 return pendingJobs;
2293 }
2294 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002295
2296 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002297 public void cancelJobsForUid(int uid, String reason) {
2298 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2299 }
2300
2301 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002302 public void addBackingUpUid(int uid) {
2303 synchronized (mLock) {
2304 // No need to actually do anything here, since for a full backup the
2305 // activity manager will kill the process which will kill the job (and
2306 // cause it to restart, but now it can't run).
2307 mBackingUpUids.put(uid, uid);
2308 }
2309 }
2310
2311 @Override
2312 public void removeBackingUpUid(int uid) {
2313 synchronized (mLock) {
2314 mBackingUpUids.delete(uid);
2315 // If there are any jobs for this uid, we need to rebuild the pending list
2316 // in case they are now ready to run.
2317 if (mJobs.countJobsForUid(uid) > 0) {
2318 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2319 }
2320 }
2321 }
2322
2323 @Override
2324 public void clearAllBackingUpUids() {
2325 synchronized (mLock) {
2326 if (mBackingUpUids.size() > 0) {
2327 mBackingUpUids.clear();
2328 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2329 }
2330 }
2331 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002332
2333 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002334 public void reportAppUsage(String packageName, int userId) {
2335 JobSchedulerService.this.reportAppUsage(packageName, userId);
2336 }
2337
2338 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002339 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002340 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002341 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002342 }
2343 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002344 }
2345
Shreyas Basarge5db09082016-01-07 13:38:29 +00002346 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002347 * Tracking of app assignments to standby buckets
2348 */
2349 final class StandbyTracker extends AppIdleStateChangeListener {
Christopher Tate435c2f42018-01-18 12:59:15 -08002350
Christopher Tatea732f012017-10-26 17:26:53 -07002351 // AppIdleStateChangeListener interface for live updates
2352
2353 @Override
Christopher Tate435c2f42018-01-18 12:59:15 -08002354 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08002355 boolean idle, int bucket, int reason) {
Christopher Tatea732f012017-10-26 17:26:53 -07002356 final int uid = mLocalPM.getPackageUid(packageName,
2357 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2358 if (uid < 0) {
2359 if (DEBUG_STANDBY) {
2360 Slog.i(TAG, "App idle state change for unknown app "
2361 + packageName + "/" + userId);
2362 }
2363 return;
2364 }
2365
2366 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2367 // update job bookkeeping out of band
2368 BackgroundThread.getHandler().post(() -> {
2369 if (DEBUG_STANDBY) {
2370 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2371 }
2372 synchronized (mLock) {
Christopher Tate93defea2018-02-20 15:57:17 -08002373 mJobs.forEachJobForSourceUid(uid, job -> {
2374 // double-check uid vs package name to disambiguate shared uids
2375 if (packageName.equals(job.getSourcePackageName())) {
2376 job.setStandbyBucket(bucketIndex);
2377 }
2378 });
Christopher Tatea732f012017-10-26 17:26:53 -07002379 onControllerStateChanged();
2380 }
2381 });
2382 }
2383
2384 @Override
2385 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002386 if (DEBUG_STANDBY) {
2387 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2388 }
2389 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002390 }
Christopher Tated117b292018-01-05 17:32:36 -08002391
2392 @Override
2393 public void onUserInteractionStarted(String packageName, int userId) {
2394 final int uid = mLocalPM.getPackageUid(packageName,
2395 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2396 if (uid < 0) {
2397 // Quietly ignore; the case is already logged elsewhere
2398 return;
2399 }
2400
Amith Yamasani977e11f2018-02-16 11:29:54 -08002401 long sinceLast = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2402 if (sinceLast > 2 * DateUtils.DAY_IN_MILLIS) {
2403 // Too long ago, not worth logging
2404 sinceLast = 0L;
2405 }
Christopher Tated117b292018-01-05 17:32:36 -08002406 final DeferredJobCounter counter = new DeferredJobCounter();
2407 synchronized (mLock) {
2408 mJobs.forEachJobForSourceUid(uid, counter);
2409 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08002410 if (counter.numDeferred() > 0 || sinceLast > 0) {
2411 BatteryStatsInternal mBatteryStatsInternal = LocalServices.getService
2412 (BatteryStatsInternal.class);
2413 mBatteryStatsInternal.noteJobsDeferred(uid, counter.numDeferred(), sinceLast);
2414 }
Christopher Tated117b292018-01-05 17:32:36 -08002415 }
2416 }
2417
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002418 static class DeferredJobCounter implements Consumer<JobStatus> {
Christopher Tated117b292018-01-05 17:32:36 -08002419 private int mDeferred = 0;
2420
2421 public int numDeferred() {
2422 return mDeferred;
2423 }
2424
2425 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002426 public void accept(JobStatus job) {
Christopher Tated117b292018-01-05 17:32:36 -08002427 if (job.getWhenStandbyDeferred() > 0) {
2428 mDeferred++;
2429 }
2430 }
Christopher Tatea732f012017-10-26 17:26:53 -07002431 }
2432
2433 public static int standbyBucketToBucketIndex(int bucket) {
2434 // Normalize AppStandby constants to indices into our bookkeeping
Amith Yamasaniafbccb72017-11-27 10:44:24 -08002435 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return 4;
2436 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) return 3;
2437 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) return 2;
2438 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return 1;
Christopher Tatea732f012017-10-26 17:26:53 -07002439 else return 0;
2440 }
2441
Christopher Tated1aebb32018-01-31 13:24:14 -08002442 // Static to support external callers
Christopher Tatea732f012017-10-26 17:26:53 -07002443 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2444 UsageStatsManagerInternal usageStats = LocalServices.getService(
2445 UsageStatsManagerInternal.class);
2446 int bucket = usageStats != null
2447 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2448 : 0;
2449
2450 bucket = standbyBucketToBucketIndex(bucket);
2451
2452 if (DEBUG_STANDBY) {
2453 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2454 }
2455 return bucket;
2456 }
2457
2458 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002459 * Binder stub trampoline implementation
2460 */
2461 final class JobSchedulerStub extends IJobScheduler.Stub {
2462 /** Cache determination of whether a given app can persist jobs
2463 * key is uid of the calling app; value is undetermined/true/false
2464 */
2465 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2466
2467 // Enforce that only the app itself (or shared uid participant) can schedule a
2468 // job that runs one of the app's services, as well as verifying that the
2469 // named service properly requires the BIND_JOB_SERVICE permission
2470 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002471 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002472 final ComponentName service = job.getService();
2473 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002474 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002475 PackageManager.MATCH_DIRECT_BOOT_AWARE
2476 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002477 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002478 if (si == null) {
2479 throw new IllegalArgumentException("No such service " + service);
2480 }
Christopher Tate7060b042014-06-09 19:50:00 -07002481 if (si.applicationInfo.uid != uid) {
2482 throw new IllegalArgumentException("uid " + uid +
2483 " cannot schedule job in " + service.getPackageName());
2484 }
2485 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2486 throw new IllegalArgumentException("Scheduled service " + service
2487 + " does not require android.permission.BIND_JOB_SERVICE permission");
2488 }
Christopher Tate5568f542014-06-18 13:53:31 -07002489 } catch (RemoteException e) {
2490 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002491 }
2492 }
2493
2494 private boolean canPersistJobs(int pid, int uid) {
2495 // If we get this far we're good to go; all we need to do now is check
2496 // whether the app is allowed to persist its scheduled work.
2497 final boolean canPersist;
2498 synchronized (mPersistCache) {
2499 Boolean cached = mPersistCache.get(uid);
2500 if (cached != null) {
2501 canPersist = cached.booleanValue();
2502 } else {
2503 // Persisting jobs is tantamount to running at boot, so we permit
2504 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2505 // permission
2506 int result = getContext().checkPermission(
2507 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2508 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2509 mPersistCache.put(uid, canPersist);
2510 }
2511 }
2512 return canPersist;
2513 }
2514
Makoto Onuki959acb52018-01-26 14:10:03 -08002515 private void validateJobFlags(JobInfo job, int callingUid) {
2516 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2517 getContext().enforceCallingOrSelfPermission(
2518 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2519 }
2520 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
2521 if (callingUid != Process.SYSTEM_UID) {
2522 throw new SecurityException("Job has invalid flags");
2523 }
Makoto Onuki2b5811a2018-02-08 11:09:42 -08002524 if (job.isPeriodic()) {
2525 Slog.wtf(TAG, "Periodic jobs mustn't have"
2526 + " FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
Makoto Onuki959acb52018-01-26 14:10:03 -08002527 }
2528 }
2529 }
2530
Christopher Tate7060b042014-06-09 19:50:00 -07002531 // IJobScheduler implementation
2532 @Override
2533 public int schedule(JobInfo job) throws RemoteException {
2534 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002535 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002536 }
2537 final int pid = Binder.getCallingPid();
2538 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002539 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002540
2541 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002542 if (job.isPersisted()) {
2543 if (!canPersistJobs(pid, uid)) {
2544 throw new IllegalArgumentException("Error: requested job be persisted without"
2545 + " holding RECEIVE_BOOT_COMPLETED permission.");
2546 }
2547 }
Christopher Tate7060b042014-06-09 19:50:00 -07002548
Makoto Onuki959acb52018-01-26 14:10:03 -08002549 validateJobFlags(job, uid);
Jeff Sharkey785f4942016-07-14 10:31:15 -06002550
Christopher Tate7060b042014-06-09 19:50:00 -07002551 long ident = Binder.clearCallingIdentity();
2552 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002553 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2554 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002555 } finally {
2556 Binder.restoreCallingIdentity(ident);
2557 }
2558 }
2559
2560 // IJobScheduler implementation
2561 @Override
2562 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2563 if (DEBUG) {
2564 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2565 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002566 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002567 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002568
2569 enforceValidJobRequest(uid, job);
2570 if (job.isPersisted()) {
2571 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2572 }
2573 if (work == null) {
2574 throw new NullPointerException("work is null");
2575 }
2576
Makoto Onuki959acb52018-01-26 14:10:03 -08002577 validateJobFlags(job, uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002578
2579 long ident = Binder.clearCallingIdentity();
2580 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002581 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2582 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002583 } finally {
2584 Binder.restoreCallingIdentity(ident);
2585 }
2586 }
2587
2588 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002589 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002590 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002591 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002592 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002593 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002594 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002595 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002596
2597 if (packageName == null) {
2598 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002599 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002600
2601 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2602 android.Manifest.permission.UPDATE_DEVICE_STATS);
2603 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2604 throw new SecurityException("Caller uid " + callerUid
2605 + " not permitted to schedule jobs for other apps");
2606 }
2607
Makoto Onuki959acb52018-01-26 14:10:03 -08002608 validateJobFlags(job, callerUid);
Jeff Sharkey4f100402016-05-03 17:44:23 -06002609
Shreyas Basarge968ac752016-01-11 23:09:26 +00002610 long ident = Binder.clearCallingIdentity();
2611 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002612 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002613 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002614 } finally {
2615 Binder.restoreCallingIdentity(ident);
2616 }
2617 }
2618
2619 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002620 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2621 final int uid = Binder.getCallingUid();
2622
2623 long ident = Binder.clearCallingIdentity();
2624 try {
2625 return JobSchedulerService.this.getPendingJobs(uid);
2626 } finally {
2627 Binder.restoreCallingIdentity(ident);
2628 }
2629 }
2630
2631 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002632 public JobInfo getPendingJob(int jobId) throws RemoteException {
2633 final int uid = Binder.getCallingUid();
2634
2635 long ident = Binder.clearCallingIdentity();
2636 try {
2637 return JobSchedulerService.this.getPendingJob(uid, jobId);
2638 } finally {
2639 Binder.restoreCallingIdentity(ident);
2640 }
2641 }
2642
2643 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002644 public void cancelAll() throws RemoteException {
2645 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002646 long ident = Binder.clearCallingIdentity();
2647 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002648 JobSchedulerService.this.cancelJobsForUid(uid,
2649 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002650 } finally {
2651 Binder.restoreCallingIdentity(ident);
2652 }
2653 }
2654
2655 @Override
2656 public void cancel(int jobId) throws RemoteException {
2657 final int uid = Binder.getCallingUid();
2658
2659 long ident = Binder.clearCallingIdentity();
2660 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002661 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002662 } finally {
2663 Binder.restoreCallingIdentity(ident);
2664 }
2665 }
2666
2667 /**
2668 * "dumpsys" infrastructure
2669 */
2670 @Override
2671 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002672 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002673
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002674 int filterUid = -1;
2675 boolean proto = false;
2676 if (!ArrayUtils.isEmpty(args)) {
2677 int opti = 0;
2678 while (opti < args.length) {
2679 String arg = args[opti];
2680 if ("-h".equals(arg)) {
2681 dumpHelp(pw);
2682 return;
2683 } else if ("-a".equals(arg)) {
2684 // Ignore, we always dump all.
2685 } else if ("--proto".equals(arg)) {
2686 proto = true;
2687 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2688 pw.println("Unknown option: " + arg);
2689 return;
2690 } else {
2691 break;
2692 }
2693 opti++;
2694 }
2695 if (opti < args.length) {
2696 String pkg = args[opti];
2697 try {
2698 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2699 PackageManager.MATCH_ANY_USER);
2700 } catch (NameNotFoundException ignored) {
2701 pw.println("Invalid package: " + pkg);
2702 return;
2703 }
2704 }
2705 }
2706
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002707 final long identityToken = Binder.clearCallingIdentity();
Christopher Tate7060b042014-06-09 19:50:00 -07002708 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002709 if (proto) {
2710 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2711 } else {
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002712 JobSchedulerService.this.dumpInternal(new IndentingPrintWriter(pw, " "),
2713 filterUid);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002714 }
Christopher Tate7060b042014-06-09 19:50:00 -07002715 } finally {
2716 Binder.restoreCallingIdentity(identityToken);
2717 }
2718 }
Christopher Tate5d346052016-03-08 12:56:08 -08002719
2720 @Override
2721 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002722 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002723 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002724 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002725 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002726 };
2727
Christopher Tate5d346052016-03-08 12:56:08 -08002728 // Shell command infrastructure: run the given job immediately
2729 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2730 if (DEBUG) {
2731 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2732 + " " + jobId + " f=" + force);
2733 }
2734
2735 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002736 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2737 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002738 if (uid < 0) {
2739 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2740 }
2741
2742 synchronized (mLock) {
2743 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2744 if (js == null) {
2745 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2746 }
2747
2748 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2749 if (!js.isConstraintsSatisfied()) {
2750 js.overrideState = 0;
2751 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2752 }
2753
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002754 queueReadyJobsForExecutionLocked();
2755 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002756 }
2757 } catch (RemoteException e) {
2758 // can't happen
2759 }
2760 return 0;
2761 }
2762
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002763 // Shell command infrastructure: immediately timeout currently executing jobs
2764 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2765 boolean hasJobId, int jobId) {
2766 if (DEBUG) {
2767 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2768 }
2769
2770 synchronized (mLock) {
2771 boolean foundSome = false;
2772 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002773 final JobServiceContext jc = mActiveServices.get(i);
2774 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002775 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002776 foundSome = true;
2777 pw.print("Timing out: ");
2778 js.printUniqueId(pw);
2779 pw.print(" ");
2780 pw.println(js.getServiceComponent().flattenToShortString());
2781 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002782 }
2783 if (!foundSome) {
2784 pw.println("No matching executing jobs found.");
2785 }
2786 }
2787 return 0;
2788 }
2789
Christopher Tate8c67d122017-09-29 16:54:26 -07002790 // Shell command infrastructure: cancel a scheduled job
2791 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2792 boolean hasJobId, int jobId) {
2793 if (DEBUG) {
2794 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2795 }
2796
2797 int pkgUid = -1;
2798 try {
2799 IPackageManager pm = AppGlobals.getPackageManager();
2800 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2801 } catch (RemoteException e) { /* can't happen */ }
2802
2803 if (pkgUid < 0) {
2804 pw.println("Package " + pkgName + " not found.");
2805 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2806 }
2807
2808 if (!hasJobId) {
2809 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2810 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2811 pw.println("No matching jobs found.");
2812 }
2813 } else {
2814 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002815 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002816 pw.println("No matching job found.");
2817 }
2818 }
2819
2820 return 0;
2821 }
2822
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002823 void setMonitorBattery(boolean enabled) {
2824 synchronized (mLock) {
2825 if (mBatteryController != null) {
2826 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2827 }
2828 }
2829 }
2830
2831 int getBatterySeq() {
2832 synchronized (mLock) {
2833 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2834 }
2835 }
2836
2837 boolean getBatteryCharging() {
2838 synchronized (mLock) {
2839 return mBatteryController != null
2840 ? mBatteryController.getTracker().isOnStablePower() : false;
2841 }
2842 }
2843
2844 boolean getBatteryNotLow() {
2845 synchronized (mLock) {
2846 return mBatteryController != null
2847 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2848 }
2849 }
2850
Dianne Hackborn532ea262017-03-17 17:50:55 -07002851 int getStorageSeq() {
2852 synchronized (mLock) {
2853 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2854 }
2855 }
2856
2857 boolean getStorageNotLow() {
2858 synchronized (mLock) {
2859 return mStorageController != null
2860 ? mStorageController.getTracker().isStorageNotLow() : false;
2861 }
2862 }
2863
Christopher Tatea732f012017-10-26 17:26:53 -07002864 long getCurrentHeartbeat() {
2865 synchronized (mLock) {
2866 return mHeartbeat;
2867 }
2868 }
2869
Christopher Tated1aebb32018-01-31 13:24:14 -08002870 // Shell command infrastructure
Dianne Hackborn6d068262017-05-16 13:14:37 -07002871 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2872 try {
2873 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2874 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2875 if (uid < 0) {
2876 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2877 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2878 }
2879
2880 synchronized (mLock) {
2881 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2882 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2883 if (js == null) {
2884 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2885 pw.print("/jid"); pw.print(jobId); pw.println(")");
2886 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2887 }
2888
2889 boolean printed = false;
2890 if (mPendingJobs.contains(js)) {
2891 pw.print("pending");
2892 printed = true;
2893 }
2894 if (isCurrentlyActiveLocked(js)) {
2895 if (printed) {
2896 pw.print(" ");
2897 }
2898 printed = true;
2899 pw.println("active");
2900 }
2901 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2902 if (printed) {
2903 pw.print(" ");
2904 }
2905 printed = true;
2906 pw.println("user-stopped");
2907 }
2908 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2909 if (printed) {
2910 pw.print(" ");
2911 }
2912 printed = true;
2913 pw.println("backing-up");
2914 }
2915 boolean componentPresent = false;
2916 try {
2917 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2918 js.getServiceComponent(),
2919 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2920 js.getUserId()) != null);
2921 } catch (RemoteException e) {
2922 }
2923 if (!componentPresent) {
2924 if (printed) {
2925 pw.print(" ");
2926 }
2927 printed = true;
2928 pw.println("no-component");
2929 }
2930 if (js.isReady()) {
2931 if (printed) {
2932 pw.print(" ");
2933 }
2934 printed = true;
2935 pw.println("ready");
2936 }
2937 if (!printed) {
2938 pw.print("waiting");
2939 }
2940 pw.println();
2941 }
2942 } catch (RemoteException e) {
2943 // can't happen
2944 }
2945 return 0;
2946 }
2947
Christopher Tated1aebb32018-01-31 13:24:14 -08002948 // Shell command infrastructure
2949 int executeHeartbeatCommand(PrintWriter pw, int numBeats) {
2950 if (numBeats < 1) {
2951 pw.println(getCurrentHeartbeat());
2952 return 0;
2953 }
2954
2955 pw.print("Advancing standby heartbeat by ");
2956 pw.println(numBeats);
2957 synchronized (mLock) {
2958 advanceHeartbeatLocked(numBeats);
2959 }
2960 return 0;
2961 }
2962
Shreyas Basarge5db09082016-01-07 13:38:29 +00002963 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2964 StringBuilder s = new StringBuilder(initial + ": ");
2965 for (int i=0; i<map.length; i++) {
2966 s.append("(")
2967 .append(map[i] == null? -1: map[i].getJobId())
2968 .append(map[i] == null? -1: map[i].getUid())
2969 .append(")" );
2970 }
2971 return s.toString();
2972 }
2973
2974 private String printPendingQueue() {
2975 StringBuilder s = new StringBuilder("Pending queue: ");
2976 Iterator<JobStatus> it = mPendingJobs.iterator();
2977 while (it.hasNext()) {
2978 JobStatus js = it.next();
2979 s.append("(")
2980 .append(js.getJob().getId())
2981 .append(", ")
2982 .append(js.getUid())
2983 .append(") ");
2984 }
2985 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002986 }
Christopher Tate7060b042014-06-09 19:50:00 -07002987
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002988 static void dumpHelp(PrintWriter pw) {
2989 pw.println("Job Scheduler (jobscheduler) dump options:");
2990 pw.println(" [-h] [package] ...");
2991 pw.println(" -h: print this help");
2992 pw.println(" [package] is an optional package name to limit the output to.");
2993 }
2994
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002995 /** Sort jobs by caller UID, then by Job ID. */
2996 private static void sortJobs(List<JobStatus> jobs) {
2997 Collections.sort(jobs, new Comparator<JobStatus>() {
2998 @Override
2999 public int compare(JobStatus o1, JobStatus o2) {
3000 int uid1 = o1.getUid();
3001 int uid2 = o2.getUid();
3002 int id1 = o1.getJobId();
3003 int id2 = o2.getJobId();
3004 if (uid1 != uid2) {
3005 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003006 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003007 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003008 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003009 });
3010 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06003011
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003012 void dumpInternal(final IndentingPrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003013 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07003014 final long nowElapsed = sElapsedRealtimeClock.millis();
3015 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003016 final Predicate<JobStatus> predicate = (js) -> {
3017 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3018 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3019 };
Dianne Hackborn33d31c52016-02-16 10:30:33 -08003020 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003021 mConstants.dump(pw);
3022 pw.println();
Makoto Onukib5d5e972018-02-20 14:44:20 -08003023
3024 pw.println(" Heartbeat:");
3025 pw.print(" Current: "); pw.println(mHeartbeat);
3026 pw.println(" Next");
3027 pw.print(" ACTIVE: "); pw.println(mNextBucketHeartbeat[0]);
3028 pw.print(" WORKING: "); pw.println(mNextBucketHeartbeat[1]);
3029 pw.print(" FREQUENT: "); pw.println(mNextBucketHeartbeat[2]);
3030 pw.print(" RARE: "); pw.println(mNextBucketHeartbeat[3]);
3031 pw.print(" Last heartbeat: ");
3032 TimeUtils.formatDuration(mLastHeartbeatTime, nowElapsed, pw);
3033 pw.println();
3034 pw.print(" Next heartbeat: ");
3035 TimeUtils.formatDuration(mLastHeartbeatTime + mConstants.STANDBY_HEARTBEAT_TIME,
3036 nowElapsed, pw);
3037 pw.println();
3038 pw.println();
3039
Jeff Sharkey822cbd12016-02-25 11:09:55 -07003040 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003041 pw.print("Registered ");
3042 pw.print(mJobs.size());
3043 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07003044 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003045 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003046 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003047 for (JobStatus job : jobs) {
3048 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
3049 pw.println(job.toShortStringExceptUniqueId());
3050
3051 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003052 if (!predicate.test(job)) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003053 continue;
3054 }
3055
Dianne Hackborn6d068262017-05-16 13:14:37 -07003056 job.dump(pw, " ", true, nowElapsed);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003057 pw.print(" Last run heartbeat: ");
3058 pw.print(heartbeatWhenJobsLastRun(job));
3059 pw.println();
3060
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003061 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003062 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003063 pw.print(" (job=");
3064 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003065 pw.print(" user=");
3066 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003067 pw.print(" !pending=");
3068 pw.print(!mPendingJobs.contains(job));
3069 pw.print(" !active=");
3070 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003071 pw.print(" !backingup=");
3072 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003073 pw.print(" comp=");
3074 boolean componentPresent = false;
3075 try {
3076 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3077 job.getServiceComponent(),
3078 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3079 job.getUserId()) != null);
3080 } catch (RemoteException e) {
3081 }
3082 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003083 pw.println(")");
3084 }
Christopher Tate7060b042014-06-09 19:50:00 -07003085 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07003086 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07003087 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003088 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07003089 pw.println();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003090 pw.println(mControllers.get(i).getClass().getSimpleName() + ":");
3091 pw.increaseIndent();
3092 mControllers.get(i).dumpControllerStateLocked(pw, predicate);
3093 pw.decreaseIndent();
Christopher Tate7060b042014-06-09 19:50:00 -07003094 }
3095 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08003096 pw.println("Uid priority overrides:");
3097 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003098 int uid = mUidPriorityOverride.keyAt(i);
3099 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3100 pw.print(" "); pw.print(UserHandle.formatUid(uid));
3101 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
3102 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003103 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003104 if (mBackingUpUids.size() > 0) {
3105 pw.println();
3106 pw.println("Backing up uids:");
3107 boolean first = true;
3108 for (int i = 0; i < mBackingUpUids.size(); i++) {
3109 int uid = mBackingUpUids.keyAt(i);
3110 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3111 if (first) {
3112 pw.print(" ");
3113 first = false;
3114 } else {
3115 pw.print(", ");
3116 }
3117 pw.print(UserHandle.formatUid(uid));
3118 }
3119 }
3120 pw.println();
3121 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003122 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003123 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07003124 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003125 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
3126 pw.println();
3127 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003128 pw.println("Pending queue:");
3129 for (int i=0; i<mPendingJobs.size(); i++) {
3130 JobStatus job = mPendingJobs.get(i);
3131 pw.print(" Pending #"); pw.print(i); pw.print(": ");
3132 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07003133 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003134 int priority = evaluateJobPriorityLocked(job);
3135 if (priority != JobInfo.PRIORITY_DEFAULT) {
3136 pw.print(" Evaluated priority: "); pw.println(priority);
3137 }
3138 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07003139 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003140 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003141 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003142 }
Christopher Tate7060b042014-06-09 19:50:00 -07003143 pw.println();
3144 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003145 for (int i=0; i<mActiveServices.size(); i++) {
3146 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003147 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003148 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07003149 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07003150 if (jsc.mStoppedReason != null) {
3151 pw.print("inactive since ");
3152 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
3153 pw.print(", stopped because: ");
3154 pw.println(jsc.mStoppedReason);
3155 } else {
3156 pw.println("inactive");
3157 }
Christopher Tate7060b042014-06-09 19:50:00 -07003158 continue;
3159 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07003160 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08003161 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003162 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003163 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003164 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003165 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07003166 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003167 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003168 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08003169 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003170 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003171 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003172 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003173 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07003174 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
3175 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07003176 }
3177 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003178 if (filterUid == -1) {
3179 pw.println();
3180 pw.print("mReadyToRock="); pw.println(mReadyToRock);
3181 pw.print("mReportedActive="); pw.println(mReportedActive);
3182 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
3183 }
Makoto Onukie7b02982017-08-24 14:23:36 -07003184 pw.println();
3185 pw.print("PersistStats: ");
3186 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07003187 }
3188 pw.println();
3189 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003190
3191 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
3192 ProtoOutputStream proto = new ProtoOutputStream(fd);
3193 final int filterUidFinal = UserHandle.getAppId(filterUid);
3194 final long nowElapsed = sElapsedRealtimeClock.millis();
3195 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003196 final Predicate<JobStatus> predicate = (js) -> {
3197 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3198 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3199 };
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003200
3201 synchronized (mLock) {
3202 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003203 proto.write(JobSchedulerServiceDumpProto.CURRENT_HEARTBEAT, mHeartbeat);
3204 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[0]);
3205 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[1]);
3206 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[2]);
3207 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[3]);
3208 proto.write(JobSchedulerServiceDumpProto.LAST_HEARTBEAT_TIME_MILLIS,
3209 mLastHeartbeatTime - nowUptime);
3210 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT_TIME_MILLIS,
3211 mLastHeartbeatTime + mConstants.STANDBY_HEARTBEAT_TIME - nowUptime);
3212
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003213 for (int u : mStartedUsers) {
3214 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
3215 }
3216 if (mJobs.size() > 0) {
3217 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
3218 sortJobs(jobs);
3219 for (JobStatus job : jobs) {
3220 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
3221 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
3222
3223 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003224 if (!predicate.test(job)) {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003225 continue;
3226 }
3227
3228 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
3229
3230 // isReadyToBeExecuted
3231 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
3232 job.isReady());
3233 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
3234 ArrayUtils.contains(mStartedUsers, job.getUserId()));
3235 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
3236 mPendingJobs.contains(job));
3237 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
3238 isCurrentlyActiveLocked(job));
3239 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
3240 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
3241 boolean componentPresent = false;
3242 try {
3243 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3244 job.getServiceComponent(),
3245 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3246 job.getUserId()) != null);
3247 } catch (RemoteException e) {
3248 }
3249 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
3250 componentPresent);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003251 proto.write(RegisteredJob.LAST_RUN_HEARTBEAT, heartbeatWhenJobsLastRun(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003252
3253 proto.end(rjToken);
3254 }
3255 }
3256 for (StateController controller : mControllers) {
3257 controller.dumpControllerStateLocked(
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003258 proto, JobSchedulerServiceDumpProto.CONTROLLERS, predicate);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003259 }
3260 for (int i=0; i< mUidPriorityOverride.size(); i++) {
3261 int uid = mUidPriorityOverride.keyAt(i);
3262 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3263 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3264 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3265 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3266 mUidPriorityOverride.valueAt(i));
3267 proto.end(pToken);
3268 }
3269 }
3270 for (int i = 0; i < mBackingUpUids.size(); i++) {
3271 int uid = mBackingUpUids.keyAt(i);
3272 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3273 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3274 }
3275 }
3276
3277 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3278 filterUidFinal);
3279 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3280 filterUidFinal);
3281
3282 for (JobStatus job : mPendingJobs) {
3283 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3284
3285 job.writeToShortProto(proto, PendingJob.INFO);
3286 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
3287 int priority = evaluateJobPriorityLocked(job);
3288 if (priority != JobInfo.PRIORITY_DEFAULT) {
3289 proto.write(PendingJob.EVALUATED_PRIORITY, priority);
3290 }
3291 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
3292
3293 proto.end(pjToken);
3294 }
3295 for (JobServiceContext jsc : mActiveServices) {
3296 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
3297 final JobStatus job = jsc.getRunningJobLocked();
3298
3299 if (job == null) {
3300 final long ijToken = proto.start(ActiveJob.INACTIVE);
3301
3302 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
3303 nowElapsed - jsc.mStoppedTime);
3304 if (jsc.mStoppedReason != null) {
3305 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
3306 jsc.mStoppedReason);
3307 }
3308
3309 proto.end(ijToken);
3310 } else {
3311 final long rjToken = proto.start(ActiveJob.RUNNING);
3312
3313 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
3314
3315 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
3316 nowElapsed - jsc.getExecutionStartTimeElapsed());
3317 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
3318 jsc.getTimeoutElapsed() - nowElapsed);
3319
3320 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3321
3322 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
3323 if (priority != JobInfo.PRIORITY_DEFAULT) {
3324 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY, priority);
3325 }
3326
3327 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3328 nowUptime - job.madeActive);
3329 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3330 job.madeActive - job.madePending);
3331
3332 proto.end(rjToken);
3333 }
3334 proto.end(ajToken);
3335 }
3336 if (filterUid == -1) {
3337 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3338 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3339 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
3340 }
3341 }
3342
3343 proto.flush();
3344 }
Christopher Tate7060b042014-06-09 19:50:00 -07003345}