blob: e88865161dfa46bf0096bd8409b42708a6f31cdf [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;
Kweku Adamsc9793092019-04-30 11:54:48 -070021import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Christopher Tateb5c07882016-05-26 17:11:09 -070022
Kweku Adams649e2fc2019-03-18 14:55:38 -070023import android.annotation.NonNull;
Christopher Tate435c2f42018-01-18 12:59:15 -080024import android.annotation.UserIdInt;
Christopher Tateee7805b2016-07-15 16:56:56 -070025import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070026import android.app.ActivityManager;
Makoto Onuki15407842018-01-19 14:23:11 -080027import android.app.ActivityManagerInternal;
Christopher Tate5568f542014-06-18 13:53:31 -070028import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070029import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070030import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070031import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000032import android.app.job.JobParameters;
Tej Singh33a412b2018-03-16 18:43:59 -070033import android.app.job.JobProtoEnums;
Christopher Tate7060b042014-06-09 19:50:00 -070034import android.app.job.JobScheduler;
35import android.app.job.JobService;
Serik Beketayev75915d12018-08-01 16:56:59 -070036import android.app.job.JobSnapshot;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070037import android.app.job.JobWorkItem;
Amith Yamasaniafbccb72017-11-27 10:44:24 -080038import android.app.usage.UsageStatsManager;
Christopher Tatea732f012017-10-26 17:26:53 -070039import android.app.usage.UsageStatsManagerInternal;
Christopher Tate7060b042014-06-09 19:50:00 -070040import android.content.BroadcastReceiver;
41import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070042import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070043import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
Kweku Adams9239a1a2019-11-12 12:06:37 -080046import android.content.pm.ApplicationInfo;
Christopher Tate5568f542014-06-18 13:53:31 -070047import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070048import android.content.pm.PackageManager;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060049import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070050import android.content.pm.PackageManagerInternal;
Kweku Adamsd1f4b902019-05-07 12:22:47 -070051import android.content.pm.ParceledListSlice;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070052import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070053import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070054import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070055import android.os.BatteryStats;
Amith Yamasani977e11f2018-02-16 11:29:54 -080056import android.os.BatteryStatsInternal;
Christopher Tate7060b042014-06-09 19:50:00 -070057import android.os.Binder;
58import android.os.Handler;
Kweku Adams59bc73a2020-05-12 12:03:56 -070059import android.os.LimitExceededException;
Christopher Tate7060b042014-06-09 19:50:00 -070060import android.os.Looper;
61import android.os.Message;
Makoto Onukib8472182019-11-13 12:03:22 -080062import android.os.ParcelFileDescriptor;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070063import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070064import android.os.RemoteException;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070065import android.os.ServiceManager;
Christopher Tate7060b042014-06-09 19:50:00 -070066import android.os.SystemClock;
67import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070068import android.os.UserManagerInternal;
Kweku Adamsbffea5a2018-12-13 22:13:28 -080069import android.os.WorkSource;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070070import android.provider.Settings;
Amith Yamasani977e11f2018-02-16 11:29:54 -080071import android.text.format.DateUtils;
Kweku Adams9239a1a2019-11-12 12:06:37 -080072import android.util.ArrayMap;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070073import android.util.KeyValueListParser;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070074import android.util.Log;
Christopher Tate7060b042014-06-09 19:50:00 -070075import android.util.Slog;
76import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080077import android.util.SparseIntArray;
78import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080079import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080080
Suprabh Shukla08126472020-02-04 20:46:35 -080081import com.android.internal.R;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070082import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070083import com.android.internal.app.IBatteryStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070084import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060085import com.android.internal.util.DumpUtils;
Muhammad Qureshie9aec322020-01-28 10:27:18 -080086import com.android.internal.util.FrameworkStatsLog;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -070087import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070088import com.android.server.AppStateTracker;
Makoto Onukieaf7eed2019-08-12 15:27:15 -070089import com.android.server.DeviceIdleInternal;
Christopher Tate616541d2017-07-26 14:27:38 -070090import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080091import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080092import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
93import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070094import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070095import com.android.server.job.controllers.BatteryController;
96import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080097import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070098import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070099import com.android.server.job.controllers.IdleController;
100import com.android.server.job.controllers.JobStatus;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800101import com.android.server.job.controllers.QuotaController;
Kweku Adamsae9d6be2020-01-14 16:10:14 -0800102import com.android.server.job.controllers.RestrictingController;
Christopher Tate7060b042014-06-09 19:50:00 -0700103import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700104import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -0700105import com.android.server.job.controllers.TimeController;
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +0200106import com.android.server.job.restrictions.JobRestriction;
107import com.android.server.job.restrictions.ThermalStatusRestriction;
Christopher Tateb909c4d52019-10-21 12:50:37 -0700108import com.android.server.usage.AppStandbyInternal;
109import com.android.server.usage.AppStandbyInternal.AppIdleStateChangeListener;
Kweku Adams9239a1a2019-11-12 12:06:37 -0800110import com.android.server.utils.quota.Categorizer;
111import com.android.server.utils.quota.Category;
112import com.android.server.utils.quota.CountQuotaTracker;
Christopher Tate7060b042014-06-09 19:50:00 -0700113
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700114import libcore.util.EmptyArray;
115
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700116import java.io.FileDescriptor;
117import java.io.PrintWriter;
118import java.time.Clock;
Makoto Onuki0e1ce972019-10-09 12:51:55 -0700119import java.time.Instant;
120import java.time.ZoneId;
121import java.time.ZoneOffset;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700122import java.util.ArrayList;
123import java.util.Arrays;
124import java.util.Collections;
125import java.util.Comparator;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700126import java.util.List;
Daulet Zhanguzin489e9c32019-12-30 12:45:49 +0000127import java.util.Objects;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -0700128import java.util.function.Consumer;
Makoto Onuki15407842018-01-19 14:23:11 -0800129import java.util.function.Predicate;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700130
Christopher Tate7060b042014-06-09 19:50:00 -0700131/**
132 * Responsible for taking jobs representing work to be performed by a client app, and determining
133 * based on the criteria specified when that job should be run against the client application's
134 * endpoint.
135 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
136 * about constraints, or the state of active jobs. It receives callbacks from the various
137 * controllers and completed jobs and operates accordingly.
138 *
139 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
140 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
141 * @hide
142 */
Jeff Sharkey4d89e422018-03-29 18:22:41 -0600143public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700144 implements StateChangedListener, JobCompletedListener {
Jeff Sharkey01bb5302018-02-21 20:12:40 -0700145 public static final String TAG = "JobScheduler";
146 public static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Christopher Tatea732f012017-10-26 17:26:53 -0700147 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800148
Dianne Hackborn970510b2016-02-24 16:56:42 -0800149 /** The maximum number of concurrent jobs we run at one time. */
Makoto Onuki714f97d2018-12-05 11:18:13 -0800150 static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800151 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800152 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800153 /** The maximum number of jobs that we allow an unprivileged app to schedule */
154 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700155
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700156 @VisibleForTesting
157 public static Clock sSystemClock = Clock.systemUTC();
Makoto Onuki0e1ce972019-10-09 12:51:55 -0700158
159 private abstract static class MySimpleClock extends Clock {
160 private final ZoneId mZoneId;
161
162 MySimpleClock(ZoneId zoneId) {
163 this.mZoneId = zoneId;
164 }
165
166 @Override
167 public ZoneId getZone() {
168 return mZoneId;
169 }
170
171 @Override
172 public Clock withZone(ZoneId zone) {
173 return new MySimpleClock(zone) {
174 @Override
175 public long millis() {
176 return MySimpleClock.this.millis();
177 }
178 };
179 }
180
181 @Override
182 public abstract long millis();
183
184 @Override
185 public Instant instant() {
186 return Instant.ofEpochMilli(millis());
187 }
188 }
189
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700190 @VisibleForTesting
Makoto Onuki0e1ce972019-10-09 12:51:55 -0700191 public static Clock sUptimeMillisClock = new MySimpleClock(ZoneOffset.UTC) {
192 @Override
193 public long millis() {
194 return SystemClock.uptimeMillis();
195 }
196 };
197
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700198 @VisibleForTesting
Makoto Onuki0e1ce972019-10-09 12:51:55 -0700199 public static Clock sElapsedRealtimeClock = new MySimpleClock(ZoneOffset.UTC) {
200 @Override
201 public long millis() {
202 return SystemClock.elapsedRealtime();
203 }
204 };
Christopher Tate2f36fd62016-02-18 18:36:08 -0800205
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800206 /** Global local for all job scheduler state. */
207 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700208 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700209 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700210 /** Tracking the standby bucket state of each app */
211 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700212 /** Tracking amount of time each package runs for. */
213 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Makoto Onuki714f97d2018-12-05 11:18:13 -0800214 final JobConcurrencyManager mConcurrencyManager;
Christopher Tate7060b042014-06-09 19:50:00 -0700215
216 static final int MSG_JOB_EXPIRED = 0;
217 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700218 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000219 static final int MSG_CHECK_JOB_GREEDY = 3;
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800220 static final int MSG_UID_STATE_CHANGED = 4;
221 static final int MSG_UID_GONE = 5;
222 static final int MSG_UID_ACTIVE = 6;
223 static final int MSG_UID_IDLE = 7;
Christopher Tate7060b042014-06-09 19:50:00 -0700224
Christopher Tate7060b042014-06-09 19:50:00 -0700225 /**
226 * Track Services that have currently active or pending jobs. The index is provided by
227 * {@link JobStatus#getServiceToken()}
228 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700229 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700230
Christopher Tate7060b042014-06-09 19:50:00 -0700231 /** List of controllers that will notify this service of updates to jobs. */
Makoto Onuki714f97d2018-12-05 11:18:13 -0800232 final List<StateController> mControllers;
Kweku Adamsae9d6be2020-01-14 16:10:14 -0800233 /**
234 * List of controllers that will apply to all jobs in the RESTRICTED bucket. This is a subset of
235 * {@link #mControllers}.
236 */
237 private final List<RestrictingController> mRestrictiveControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800238 /** Need direct access to this for testing. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700239 private final BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700240 /** Need direct access to this for testing. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700241 private final StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700242 /** Need directly for sending uid state changes */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700243 private final DeviceIdleJobsController mDeviceIdleJobsController;
Kweku Adamsb4b8b9c2019-06-13 18:37:51 -0700244 /** Needed to get remaining quota time. */
245 private final QuotaController mQuotaController;
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +0200246 /**
247 * List of restrictions.
248 * Note: do not add to or remove from this list at runtime except in the constructor, because we
249 * do not synchronize access to this list.
250 */
251 private final List<JobRestriction> mJobRestrictions;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700252
Suprabh Shukla08126472020-02-04 20:46:35 -0800253 @NonNull
254 private final String mSystemGalleryPackage;
255
Kweku Adams9239a1a2019-11-12 12:06:37 -0800256 private final CountQuotaTracker mQuotaTracker;
Kweku Adamsfd983782020-01-14 15:26:23 -0800257 private static final String QUOTA_TRACKER_SCHEDULE_PERSISTED_TAG = ".schedulePersisted()";
Kweku Adams9239a1a2019-11-12 12:06:37 -0800258
Christopher Tate7060b042014-06-09 19:50:00 -0700259 /**
260 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
261 * when ready to execute them.
262 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700263 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700264
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700265 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700266
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700267 final JobHandler mHandler;
268 final JobSchedulerStub mJobSchedulerStub;
269
Christopher Tatea732f012017-10-26 17:26:53 -0700270 PackageManagerInternal mLocalPM;
Makoto Onuki15407842018-01-19 14:23:11 -0800271 ActivityManagerInternal mActivityManagerInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700272 IBatteryStats mBatteryStats;
Makoto Onukieaf7eed2019-08-12 15:27:15 -0700273 DeviceIdleInternal mLocalDeviceIdleController;
Makoto Onukie4918212018-02-06 11:30:15 -0800274 AppStateTracker mAppStateTracker;
Christopher Tated1aebb32018-01-31 13:24:14 -0800275 final UsageStatsManagerInternal mUsageStats;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800276 private final AppStandbyInternal mAppStandbyInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700277
278 /**
279 * Set to true once we are allowed to run third party apps.
280 */
281 boolean mReadyToRock;
282
Christopher Tate7060b042014-06-09 19:50:00 -0700283 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800284 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800285 */
286 boolean mReportedActive;
287
288 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800289 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800290 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800291 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
292
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700293 /**
294 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
295 */
296 final SparseIntArray mBackingUpUids = new SparseIntArray();
297
Christopher Tatea732f012017-10-26 17:26:53 -0700298 /**
Kweku Adams9239a1a2019-11-12 12:06:37 -0800299 * Cache of debuggable app status.
300 */
301 final ArrayMap<String, Boolean> mDebuggableApps = new ArrayMap<>();
302
303 /**
Kweku Adams6c5dc642019-07-25 10:29:38 -0700304 * Named indices into standby bucket arrays, for clarity in referring to
Christopher Tate325768c2018-03-07 16:07:56 -0800305 * specific buckets' bookkeeping.
306 */
Kweku Adams4836f9d2018-11-12 17:04:17 -0800307 public static final int ACTIVE_INDEX = 0;
308 public static final int WORKING_INDEX = 1;
309 public static final int FREQUENT_INDEX = 2;
310 public static final int RARE_INDEX = 3;
311 public static final int NEVER_INDEX = 4;
Kweku Adamsae9d6be2020-01-14 16:10:14 -0800312 // Putting RESTRICTED_INDEX after NEVER_INDEX to make it easier for proto dumping
313 // (ScheduledJobStateChanged and JobStatusDumpProto).
314 public static final int RESTRICTED_INDEX = 5;
Christopher Tate325768c2018-03-07 16:07:56 -0800315
Dianne Hackborn970510b2016-02-24 16:56:42 -0800316 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
317
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700318 private class ConstantsObserver extends ContentObserver {
319 private ContentResolver mResolver;
320
321 public ConstantsObserver(Handler handler) {
322 super(handler);
323 }
324
325 public void start(ContentResolver resolver) {
326 mResolver = resolver;
327 mResolver.registerContentObserver(Settings.Global.getUriFor(
328 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
329 updateConstants();
330 }
331
332 @Override
333 public void onChange(boolean selfChange, Uri uri) {
334 updateConstants();
335 }
336
337 private void updateConstants() {
338 synchronized (mLock) {
339 try {
340 mConstants.updateConstantsLocked(Settings.Global.getString(mResolver,
341 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Kweku Adams4836f9d2018-11-12 17:04:17 -0800342 for (int controller = 0; controller < mControllers.size(); controller++) {
343 final StateController sc = mControllers.get(controller);
344 sc.onConstantsUpdatedLocked();
345 }
Kweku Adams9239a1a2019-11-12 12:06:37 -0800346 mQuotaTracker.setEnabled(mConstants.ENABLE_API_QUOTAS);
347 mQuotaTracker.setCountLimit(Category.SINGLE_CATEGORY,
348 mConstants.API_QUOTA_SCHEDULE_COUNT,
349 mConstants.API_QUOTA_SCHEDULE_WINDOW_MS);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700350 } catch (IllegalArgumentException e) {
351 // Failed to parse the settings string, log this and move on
352 // with defaults.
353 Slog.e(TAG, "Bad jobscheduler settings", e);
354 }
355 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700356 }
357 }
358
Makoto Onukic279f2b2019-01-09 13:11:37 -0800359 static class MaxJobCounts {
Makoto Onuki66a51442018-12-20 14:23:50 -0800360 private final KeyValueListParser.IntValue mTotal;
Makoto Onukic279f2b2019-01-09 13:11:37 -0800361 private final KeyValueListParser.IntValue mMaxBg;
362 private final KeyValueListParser.IntValue mMinBg;
Makoto Onuki66a51442018-12-20 14:23:50 -0800363
Makoto Onukic279f2b2019-01-09 13:11:37 -0800364 MaxJobCounts(int totalDefault, String totalKey,
365 int maxBgDefault, String maxBgKey, int minBgDefault, String minBgKey) {
Makoto Onuki66a51442018-12-20 14:23:50 -0800366 mTotal = new KeyValueListParser.IntValue(totalKey, totalDefault);
Makoto Onukic279f2b2019-01-09 13:11:37 -0800367 mMaxBg = new KeyValueListParser.IntValue(maxBgKey, maxBgDefault);
368 mMinBg = new KeyValueListParser.IntValue(minBgKey, minBgDefault);
Makoto Onuki66a51442018-12-20 14:23:50 -0800369 }
370
371 public void parse(KeyValueListParser parser) {
372 mTotal.parse(parser);
Makoto Onukic279f2b2019-01-09 13:11:37 -0800373 mMaxBg.parse(parser);
374 mMinBg.parse(parser);
Makoto Onuki66a51442018-12-20 14:23:50 -0800375
Makoto Onukic279f2b2019-01-09 13:11:37 -0800376 if (mTotal.getValue() < 1) {
377 mTotal.setValue(1);
378 } else if (mTotal.getValue() > MAX_JOB_CONTEXTS_COUNT) {
379 mTotal.setValue(MAX_JOB_CONTEXTS_COUNT);
Makoto Onuki66a51442018-12-20 14:23:50 -0800380 }
381
Makoto Onukic279f2b2019-01-09 13:11:37 -0800382 if (mMaxBg.getValue() < 1) {
383 mMaxBg.setValue(1);
384 } else if (mMaxBg.getValue() > mTotal.getValue()) {
385 mMaxBg.setValue(mTotal.getValue());
386 }
387 if (mMinBg.getValue() < 0) {
388 mMinBg.setValue(0);
389 } else {
390 if (mMinBg.getValue() > mMaxBg.getValue()) {
391 mMinBg.setValue(mMaxBg.getValue());
392 }
393 if (mMinBg.getValue() >= mTotal.getValue()) {
394 mMinBg.setValue(mTotal.getValue() - 1);
395 }
396 }
Makoto Onuki66a51442018-12-20 14:23:50 -0800397 }
398
Makoto Onukif731c422019-01-22 13:23:31 -0800399 /** Total number of jobs to run simultaneously. */
400 public int getMaxTotal() {
Makoto Onuki66a51442018-12-20 14:23:50 -0800401 return mTotal.getValue();
402 }
403
Makoto Onukif731c422019-01-22 13:23:31 -0800404 /** Max number of BG (== owned by non-TOP apps) jobs to run simultaneously. */
Makoto Onukic279f2b2019-01-09 13:11:37 -0800405 public int getMaxBg() {
406 return mMaxBg.getValue();
407 }
408
Makoto Onukif731c422019-01-22 13:23:31 -0800409 /**
410 * We try to run at least this many BG (== owned by non-TOP apps) jobs, when there are any
411 * pending, rather than always running the TOTAL number of FG jobs.
412 */
Makoto Onukic279f2b2019-01-09 13:11:37 -0800413 public int getMinBg() {
414 return mMinBg.getValue();
Makoto Onuki66a51442018-12-20 14:23:50 -0800415 }
416
417 public void dump(PrintWriter pw, String prefix) {
418 mTotal.dump(pw, prefix);
Makoto Onukic279f2b2019-01-09 13:11:37 -0800419 mMaxBg.dump(pw, prefix);
420 mMinBg.dump(pw, prefix);
Makoto Onuki66a51442018-12-20 14:23:50 -0800421 }
422
Makoto Onukif731c422019-01-22 13:23:31 -0800423 public void dumpProto(ProtoOutputStream proto, long fieldId) {
424 final long token = proto.start(fieldId);
425 mTotal.dumpProto(proto, MaxJobCountsProto.TOTAL_JOBS);
426 mMaxBg.dumpProto(proto, MaxJobCountsProto.MAX_BG);
427 mMinBg.dumpProto(proto, MaxJobCountsProto.MIN_BG);
428 proto.end(token);
429 }
430 }
431
432 /** {@link MaxJobCounts} for each memory trim level. */
433 static class MaxJobCountsPerMemoryTrimLevel {
434 public final MaxJobCounts normal;
435 public final MaxJobCounts moderate;
436 public final MaxJobCounts low;
437 public final MaxJobCounts critical;
438
439 MaxJobCountsPerMemoryTrimLevel(
440 MaxJobCounts normal,
441 MaxJobCounts moderate, MaxJobCounts low,
442 MaxJobCounts critical) {
443 this.normal = normal;
444 this.moderate = moderate;
445 this.low = low;
446 this.critical = critical;
447 }
448
449 public void dumpProto(ProtoOutputStream proto, long fieldId) {
450 final long token = proto.start(fieldId);
451 normal.dumpProto(proto, MaxJobCountsPerMemoryTrimLevelProto.NORMAL);
452 moderate.dumpProto(proto, MaxJobCountsPerMemoryTrimLevelProto.MODERATE);
453 low.dumpProto(proto, MaxJobCountsPerMemoryTrimLevelProto.LOW);
454 critical.dumpProto(proto, MaxJobCountsPerMemoryTrimLevelProto.CRITICAL);
455 proto.end(token);
Makoto Onuki66a51442018-12-20 14:23:50 -0800456 }
457 }
458
Wei Wang8c0c3c12018-11-14 14:56:52 -0800459 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700460 * All times are in milliseconds. These constants are kept synchronized with the system
461 * global Settings. Any access to this class or its fields should be done while
462 * holding the JobSchedulerService.mLock lock.
463 */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700464 public static class Constants {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700465 // Key names stored in the settings value.
Kweku Adams111b8222020-02-11 12:06:26 -0800466 // TODO(124466289): remove deprecated flags when we migrate to DeviceConfig
467 private static final String DEPRECATED_KEY_MIN_IDLE_COUNT = "min_idle_count";
468 private static final String DEPRECATED_KEY_MIN_CHARGING_COUNT = "min_charging_count";
469 private static final String DEPRECATED_KEY_MIN_BATTERY_NOT_LOW_COUNT =
470 "min_battery_not_low_count";
471 private static final String DEPRECATED_KEY_MIN_STORAGE_NOT_LOW_COUNT =
472 "min_storage_not_low_count";
473 private static final String DEPRECATED_KEY_MIN_CONNECTIVITY_COUNT =
474 "min_connectivity_count";
475 private static final String DEPRECATED_KEY_MIN_CONTENT_COUNT = "min_content_count";
476 private static final String DEPRECATED_KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
Kweku Adams41cb3322019-06-26 14:42:26 -0700477 private static final String KEY_MIN_READY_NON_ACTIVE_JOBS_COUNT =
478 "min_ready_non_active_jobs_count";
479 private static final String KEY_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS =
480 "max_non_active_job_batch_delay_ms";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700481 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
482 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
Makoto Onukic279f2b2019-01-09 13:11:37 -0800483
484 // The following values used to be used on P and below. Do not reuse them.
485 private static final String DEPRECATED_KEY_FG_JOB_COUNT = "fg_job_count";
486 private static final String DEPRECATED_KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
487 private static final String DEPRECATED_KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
488 private static final String DEPRECATED_KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
489 private static final String DEPRECATED_KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
490
Kweku Adams7a1c76d2020-02-06 16:54:15 -0800491 private static final String DEPRECATED_KEY_MAX_STANDARD_RESCHEDULE_COUNT
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700492 = "max_standard_reschedule_count";
Kweku Adams7a1c76d2020-02-06 16:54:15 -0800493 private static final String DEPRECATED_KEY_MAX_WORK_RESCHEDULE_COUNT =
494 "max_work_reschedule_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700495 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
496 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Kweku Adams6c5dc642019-07-25 10:29:38 -0700497 private static final String DEPRECATED_KEY_STANDBY_HEARTBEAT_TIME =
498 "standby_heartbeat_time";
499 private static final String DEPRECATED_KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
500 private static final String DEPRECATED_KEY_STANDBY_FREQUENT_BEATS =
501 "standby_frequent_beats";
502 private static final String DEPRECATED_KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700503 private static final String KEY_CONN_CONGESTION_DELAY_FRAC = "conn_congestion_delay_frac";
504 private static final String KEY_CONN_PREFETCH_RELAX_FRAC = "conn_prefetch_relax_frac";
Kweku Adams6c5dc642019-07-25 10:29:38 -0700505 private static final String DEPRECATED_KEY_USE_HEARTBEATS = "use_heartbeats";
Kweku Adams9239a1a2019-11-12 12:06:37 -0800506 private static final String KEY_ENABLE_API_QUOTAS = "enable_api_quotas";
507 private static final String KEY_API_QUOTA_SCHEDULE_COUNT = "aq_schedule_count";
508 private static final String KEY_API_QUOTA_SCHEDULE_WINDOW_MS = "aq_schedule_window_ms";
509 private static final String KEY_API_QUOTA_SCHEDULE_THROW_EXCEPTION =
510 "aq_schedule_throw_exception";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700511
Kweku Adams41cb3322019-06-26 14:42:26 -0700512 private static final int DEFAULT_MIN_READY_NON_ACTIVE_JOBS_COUNT = 5;
513 private static final long DEFAULT_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS = 31 * MINUTE_IN_MILLIS;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700514 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
515 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700516 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
517 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700518 private static final float DEFAULT_CONN_CONGESTION_DELAY_FRAC = 0.5f;
519 private static final float DEFAULT_CONN_PREFETCH_RELAX_FRAC = 0.5f;
Kweku Adams9239a1a2019-11-12 12:06:37 -0800520 private static final boolean DEFAULT_ENABLE_API_QUOTAS = true;
Kweku Adamsfd983782020-01-14 15:26:23 -0800521 private static final int DEFAULT_API_QUOTA_SCHEDULE_COUNT = 250;
Kweku Adams9239a1a2019-11-12 12:06:37 -0800522 private static final long DEFAULT_API_QUOTA_SCHEDULE_WINDOW_MS = MINUTE_IN_MILLIS;
523 private static final boolean DEFAULT_API_QUOTA_SCHEDULE_THROW_EXCEPTION = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700524
525 /**
Kweku Adams41cb3322019-06-26 14:42:26 -0700526 * Minimum # of non-ACTIVE jobs for which the JMS will be happy running some work early.
527 */
528 int MIN_READY_NON_ACTIVE_JOBS_COUNT = DEFAULT_MIN_READY_NON_ACTIVE_JOBS_COUNT;
529
530 /**
531 * Don't batch a non-ACTIVE job if it's been delayed due to force batching attempts for
532 * at least this amount of time.
533 */
534 long MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS = DEFAULT_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS;
535
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700536 /**
537 * This is the job execution factor that is considered to be heavy use of the system.
538 */
539 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
540 /**
541 * This is the job execution factor that is considered to be moderate use of the system.
542 */
543 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
Makoto Onuki66a51442018-12-20 14:23:50 -0800544
545 // Max job counts for screen on / off, for each memory trim level.
Makoto Onukif731c422019-01-22 13:23:31 -0800546 final MaxJobCountsPerMemoryTrimLevel MAX_JOB_COUNTS_SCREEN_ON =
547 new MaxJobCountsPerMemoryTrimLevel(
548 new MaxJobCounts(
549 8, "max_job_total_on_normal",
550 6, "max_job_max_bg_on_normal",
551 2, "max_job_min_bg_on_normal"),
552 new MaxJobCounts(
553 8, "max_job_total_on_moderate",
554 4, "max_job_max_bg_on_moderate",
555 2, "max_job_min_bg_on_moderate"),
556 new MaxJobCounts(
557 5, "max_job_total_on_low",
558 1, "max_job_max_bg_on_low",
559 1, "max_job_min_bg_on_low"),
560 new MaxJobCounts(
561 5, "max_job_total_on_critical",
562 1, "max_job_max_bg_on_critical",
563 1, "max_job_min_bg_on_critical"));
Makoto Onuki66a51442018-12-20 14:23:50 -0800564
Makoto Onukif731c422019-01-22 13:23:31 -0800565 final MaxJobCountsPerMemoryTrimLevel MAX_JOB_COUNTS_SCREEN_OFF =
566 new MaxJobCountsPerMemoryTrimLevel(
567 new MaxJobCounts(
568 10, "max_job_total_off_normal",
569 6, "max_job_max_bg_off_normal",
570 2, "max_job_min_bg_off_normal"),
571 new MaxJobCounts(
572 10, "max_job_total_off_moderate",
573 4, "max_job_max_bg_off_moderate",
574 2, "max_job_min_bg_off_moderate"),
575 new MaxJobCounts(
576 5, "max_job_total_off_low",
577 1, "max_job_max_bg_off_low",
578 1, "max_job_min_bg_off_low"),
579 new MaxJobCounts(
580 5, "max_job_total_off_critical",
581 1, "max_job_max_bg_off_critical",
582 1, "max_job_min_bg_off_critical"));
Makoto Onuki66a51442018-12-20 14:23:50 -0800583
Makoto Onukic279f2b2019-01-09 13:11:37 -0800584
585 /** Wait for this long after screen off before increasing the job concurrency. */
586 final KeyValueListParser.IntValue SCREEN_OFF_JOB_CONCURRENCY_INCREASE_DELAY_MS =
587 new KeyValueListParser.IntValue(
588 "screen_off_job_concurrency_increase_delay_ms", 30_000);
Makoto Onuki66a51442018-12-20 14:23:50 -0800589
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700590 /**
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700591 * The minimum backoff time to allow for linear backoff.
592 */
593 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
594 /**
595 * The minimum backoff time to allow for exponential backoff.
596 */
597 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Kweku Adams6c5dc642019-07-25 10:29:38 -0700598
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700599 /**
600 * The fraction of a job's running window that must pass before we
601 * consider running it when the network is congested.
602 */
603 public float CONN_CONGESTION_DELAY_FRAC = DEFAULT_CONN_CONGESTION_DELAY_FRAC;
604 /**
605 * The fraction of a prefetch job's running window that must pass before
606 * we consider matching it against a metered network.
607 */
608 public float CONN_PREFETCH_RELAX_FRAC = DEFAULT_CONN_PREFETCH_RELAX_FRAC;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800609
Kweku Adams9239a1a2019-11-12 12:06:37 -0800610 /**
611 * Whether to enable quota limits on APIs.
612 */
613 public boolean ENABLE_API_QUOTAS = DEFAULT_ENABLE_API_QUOTAS;
614 /**
615 * The maximum number of schedule() calls an app can make in a set amount of time.
616 */
617 public int API_QUOTA_SCHEDULE_COUNT = DEFAULT_API_QUOTA_SCHEDULE_COUNT;
618 /**
619 * The time window that {@link #API_QUOTA_SCHEDULE_COUNT} should be evaluated over.
620 */
621 public long API_QUOTA_SCHEDULE_WINDOW_MS = DEFAULT_API_QUOTA_SCHEDULE_WINDOW_MS;
622 /**
623 * Whether to throw an exception when an app hits its schedule quota limit.
624 */
625 public boolean API_QUOTA_SCHEDULE_THROW_EXCEPTION =
626 DEFAULT_API_QUOTA_SCHEDULE_THROW_EXCEPTION;
627
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700628 private final KeyValueListParser mParser = new KeyValueListParser(',');
629
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700630 void updateConstantsLocked(String value) {
631 try {
632 mParser.setString(value);
633 } catch (Exception e) {
634 // Failed to parse the settings string, log this and move on
635 // with defaults.
636 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700637 }
Christopher Tated1aebb32018-01-31 13:24:14 -0800638
Kweku Adams41cb3322019-06-26 14:42:26 -0700639 MIN_READY_NON_ACTIVE_JOBS_COUNT = mParser.getInt(
640 KEY_MIN_READY_NON_ACTIVE_JOBS_COUNT,
641 DEFAULT_MIN_READY_NON_ACTIVE_JOBS_COUNT);
642 MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS = mParser.getLong(
643 KEY_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS,
644 DEFAULT_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700645 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
646 DEFAULT_HEAVY_USE_FACTOR);
647 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
648 DEFAULT_MODERATE_USE_FACTOR);
Makoto Onuki66a51442018-12-20 14:23:50 -0800649
Makoto Onukif731c422019-01-22 13:23:31 -0800650 MAX_JOB_COUNTS_SCREEN_ON.normal.parse(mParser);
651 MAX_JOB_COUNTS_SCREEN_ON.moderate.parse(mParser);
652 MAX_JOB_COUNTS_SCREEN_ON.low.parse(mParser);
653 MAX_JOB_COUNTS_SCREEN_ON.critical.parse(mParser);
Makoto Onuki66a51442018-12-20 14:23:50 -0800654
Makoto Onukif731c422019-01-22 13:23:31 -0800655 MAX_JOB_COUNTS_SCREEN_OFF.normal.parse(mParser);
656 MAX_JOB_COUNTS_SCREEN_OFF.moderate.parse(mParser);
657 MAX_JOB_COUNTS_SCREEN_OFF.low.parse(mParser);
658 MAX_JOB_COUNTS_SCREEN_OFF.critical.parse(mParser);
Makoto Onuki66a51442018-12-20 14:23:50 -0800659
Makoto Onukif996c2c2019-01-25 15:18:48 -0800660 SCREEN_OFF_JOB_CONCURRENCY_INCREASE_DELAY_MS.parse(mParser);
661
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700662 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
663 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
664 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
665 DEFAULT_MIN_EXP_BACKOFF_TIME);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700666 CONN_CONGESTION_DELAY_FRAC = mParser.getFloat(KEY_CONN_CONGESTION_DELAY_FRAC,
667 DEFAULT_CONN_CONGESTION_DELAY_FRAC);
668 CONN_PREFETCH_RELAX_FRAC = mParser.getFloat(KEY_CONN_PREFETCH_RELAX_FRAC,
669 DEFAULT_CONN_PREFETCH_RELAX_FRAC);
Kweku Adams9239a1a2019-11-12 12:06:37 -0800670
671 ENABLE_API_QUOTAS = mParser.getBoolean(KEY_ENABLE_API_QUOTAS,
672 DEFAULT_ENABLE_API_QUOTAS);
Kweku Adamsfd983782020-01-14 15:26:23 -0800673 // Set a minimum value on the quota limit so it's not so low that it interferes with
674 // legitimate use cases.
Kweku Adams9239a1a2019-11-12 12:06:37 -0800675 API_QUOTA_SCHEDULE_COUNT = Math.max(250,
676 mParser.getInt(KEY_API_QUOTA_SCHEDULE_COUNT, DEFAULT_API_QUOTA_SCHEDULE_COUNT));
677 API_QUOTA_SCHEDULE_WINDOW_MS = mParser.getDurationMillis(
678 KEY_API_QUOTA_SCHEDULE_WINDOW_MS, DEFAULT_API_QUOTA_SCHEDULE_WINDOW_MS);
679 API_QUOTA_SCHEDULE_THROW_EXCEPTION = mParser.getBoolean(
680 KEY_API_QUOTA_SCHEDULE_THROW_EXCEPTION,
681 DEFAULT_API_QUOTA_SCHEDULE_THROW_EXCEPTION);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700682 }
683
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700684 void dump(IndentingPrintWriter pw) {
685 pw.println("Settings:");
686 pw.increaseIndent();
Kweku Adams41cb3322019-06-26 14:42:26 -0700687 pw.printPair(KEY_MIN_READY_NON_ACTIVE_JOBS_COUNT,
688 MIN_READY_NON_ACTIVE_JOBS_COUNT).println();
689 pw.printPair(KEY_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS,
690 MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS).println();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700691 pw.printPair(KEY_HEAVY_USE_FACTOR, HEAVY_USE_FACTOR).println();
692 pw.printPair(KEY_MODERATE_USE_FACTOR, MODERATE_USE_FACTOR).println();
Makoto Onuki66a51442018-12-20 14:23:50 -0800693
Makoto Onukif731c422019-01-22 13:23:31 -0800694 MAX_JOB_COUNTS_SCREEN_ON.normal.dump(pw, "");
695 MAX_JOB_COUNTS_SCREEN_ON.moderate.dump(pw, "");
696 MAX_JOB_COUNTS_SCREEN_ON.low.dump(pw, "");
697 MAX_JOB_COUNTS_SCREEN_ON.critical.dump(pw, "");
Makoto Onuki66a51442018-12-20 14:23:50 -0800698
Makoto Onukif731c422019-01-22 13:23:31 -0800699 MAX_JOB_COUNTS_SCREEN_OFF.normal.dump(pw, "");
700 MAX_JOB_COUNTS_SCREEN_OFF.moderate.dump(pw, "");
701 MAX_JOB_COUNTS_SCREEN_OFF.low.dump(pw, "");
702 MAX_JOB_COUNTS_SCREEN_OFF.critical.dump(pw, "");
703
704 SCREEN_OFF_JOB_CONCURRENCY_INCREASE_DELAY_MS.dump(pw, "");
Makoto Onuki66a51442018-12-20 14:23:50 -0800705
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700706 pw.printPair(KEY_MIN_LINEAR_BACKOFF_TIME, MIN_LINEAR_BACKOFF_TIME).println();
707 pw.printPair(KEY_MIN_EXP_BACKOFF_TIME, MIN_EXP_BACKOFF_TIME).println();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700708 pw.printPair(KEY_CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC).println();
709 pw.printPair(KEY_CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC).println();
Kweku Adams4e774a32019-04-24 18:01:29 -0700710
Kweku Adams9239a1a2019-11-12 12:06:37 -0800711 pw.printPair(KEY_ENABLE_API_QUOTAS, ENABLE_API_QUOTAS).println();
712 pw.printPair(KEY_API_QUOTA_SCHEDULE_COUNT, API_QUOTA_SCHEDULE_COUNT).println();
713 pw.printPair(KEY_API_QUOTA_SCHEDULE_WINDOW_MS, API_QUOTA_SCHEDULE_WINDOW_MS).println();
714 pw.printPair(KEY_API_QUOTA_SCHEDULE_THROW_EXCEPTION,
715 API_QUOTA_SCHEDULE_THROW_EXCEPTION).println();
716
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700717 pw.decreaseIndent();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700718 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800719
Kweku Adams4e774a32019-04-24 18:01:29 -0700720 void dump(ProtoOutputStream proto) {
Kweku Adams41cb3322019-06-26 14:42:26 -0700721 proto.write(ConstantsProto.MIN_READY_NON_ACTIVE_JOBS_COUNT,
722 MIN_READY_NON_ACTIVE_JOBS_COUNT);
723 proto.write(ConstantsProto.MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS,
724 MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800725 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
726 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
Makoto Onuki66a51442018-12-20 14:23:50 -0800727
Makoto Onukif731c422019-01-22 13:23:31 -0800728 MAX_JOB_COUNTS_SCREEN_ON.dumpProto(proto, ConstantsProto.MAX_JOB_COUNTS_SCREEN_ON);
729 MAX_JOB_COUNTS_SCREEN_OFF.dumpProto(proto, ConstantsProto.MAX_JOB_COUNTS_SCREEN_OFF);
730
731 SCREEN_OFF_JOB_CONCURRENCY_INCREASE_DELAY_MS.dumpProto(proto,
732 ConstantsProto.SCREEN_OFF_JOB_CONCURRENCY_INCREASE_DELAY_MS);
Makoto Onuki66a51442018-12-20 14:23:50 -0800733
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800734 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
735 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700736 proto.write(ConstantsProto.CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC);
737 proto.write(ConstantsProto.CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC);
Kweku Adams9239a1a2019-11-12 12:06:37 -0800738
739 proto.write(ConstantsProto.ENABLE_API_QUOTAS, ENABLE_API_QUOTAS);
740 proto.write(ConstantsProto.API_QUOTA_SCHEDULE_COUNT, API_QUOTA_SCHEDULE_COUNT);
741 proto.write(ConstantsProto.API_QUOTA_SCHEDULE_WINDOW_MS, API_QUOTA_SCHEDULE_WINDOW_MS);
742 proto.write(ConstantsProto.API_QUOTA_SCHEDULE_THROW_EXCEPTION,
743 API_QUOTA_SCHEDULE_THROW_EXCEPTION);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800744 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700745 }
746
747 final Constants mConstants;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700748 final ConstantsObserver mConstantsObserver;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700749
Kweku Adamscdc2c992020-03-13 13:24:53 -0700750 private static final Comparator<JobStatus> sPendingJobComparator = (o1, o2) -> {
751 // Jobs with an override state set (via adb) should be put first as tests/developers
752 // expect the jobs to run immediately.
753 if (o1.overrideState != o2.overrideState) {
754 // Higher override state (OVERRIDE_FULL) should be before lower state (OVERRIDE_SOFT)
755 return o2.overrideState - o1.overrideState;
756 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700757 if (o1.enqueueTime < o2.enqueueTime) {
758 return -1;
759 }
760 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
761 };
762
763 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
764 int where = Collections.binarySearch(array, newItem, comparator);
765 if (where < 0) {
766 where = ~where;
767 }
768 array.add(where, newItem);
769 }
770
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700771 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700772 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
773 * still clean up. On reinstall the package will have a new uid.
774 */
775 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
776 @Override
777 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700778 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700779 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700780 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700781 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700782 final String pkgName = getPackageName(intent);
783 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
784
Christopher Tateee7805b2016-07-15 16:56:56 -0700785 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700786 // Purge the app's jobs if the whole package was just disabled. When this is
787 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700788 if (pkgName != null && pkgUid != -1) {
789 final String[] changedComponents = intent.getStringArrayExtra(
790 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
791 if (changedComponents != null) {
792 for (String component : changedComponents) {
793 if (component.equals(pkgName)) {
794 if (DEBUG) {
795 Slog.d(TAG, "Package state change: " + pkgName);
796 }
797 try {
798 final int userId = UserHandle.getUserId(pkgUid);
799 IPackageManager pm = AppGlobals.getPackageManager();
800 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
801 if (state == COMPONENT_ENABLED_STATE_DISABLED
802 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
803 if (DEBUG) {
804 Slog.d(TAG, "Removing jobs for package " + pkgName
805 + " in user " + userId);
806 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700807 cancelJobsForPackageAndUid(pkgName, pkgUid,
808 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700809 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700810 } catch (RemoteException|IllegalArgumentException e) {
811 /*
812 * IllegalArgumentException means that the package doesn't exist.
813 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
814 * behind outright uninstall, so by the time we try to act it's gone.
815 * We don't need to act on this PACKAGE_CHANGED when this happens;
816 * we'll get a PACKAGE_REMOVED later and clean up then.
817 *
818 * RemoteException can't actually happen; the package manager is
819 * running in this same process.
820 */
821 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700822 break;
823 }
824 }
Kweku Adamscdbfcb92018-12-06 17:05:15 -0800825 if (DEBUG) {
826 Slog.d(TAG, "Something in " + pkgName
827 + " changed. Reevaluating controller states.");
828 }
829 synchronized (mLock) {
830 for (int c = mControllers.size() - 1; c >= 0; --c) {
831 mControllers.get(c).reevaluateStateLocked(pkgUid);
832 }
833 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700834 }
835 } else {
836 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
837 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700838 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700839 // If this is an outright uninstall rather than the first half of an
840 // app update sequence, cancel the jobs associated with the app.
841 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
842 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
843 if (DEBUG) {
844 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
845 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700846 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Kweku Adamsa9f8e1f2018-12-12 16:06:54 -0800847 synchronized (mLock) {
848 for (int c = 0; c < mControllers.size(); ++c) {
849 mControllers.get(c).onAppRemovedLocked(pkgName, pkgUid);
850 }
Kweku Adams9239a1a2019-11-12 12:06:37 -0800851 mDebuggableApps.remove(pkgName);
Kweku Adamsa9f8e1f2018-12-12 16:06:54 -0800852 }
Christopher Tate7060b042014-06-09 19:50:00 -0700853 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700854 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700855 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
856 if (DEBUG) {
857 Slog.d(TAG, "Removing jobs for user: " + userId);
858 }
859 cancelJobsForUser(userId);
Kweku Adamsa9f8e1f2018-12-12 16:06:54 -0800860 synchronized (mLock) {
861 for (int c = 0; c < mControllers.size(); ++c) {
862 mControllers.get(c).onUserRemovedLocked(userId);
863 }
864 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700865 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
866 // Has this package scheduled any jobs, such that we will take action
867 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700868 if (pkgUid != -1) {
869 List<JobStatus> jobsForUid;
870 synchronized (mLock) {
871 jobsForUid = mJobs.getJobsByUid(pkgUid);
872 }
873 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
874 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
875 if (DEBUG) {
876 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
877 + pkgUid + " has jobs");
878 }
879 setResultCode(Activity.RESULT_OK);
880 break;
881 }
882 }
883 }
884 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
885 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700886 if (pkgUid != -1) {
887 if (DEBUG) {
888 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
889 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700890 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700891 }
Christopher Tate7060b042014-06-09 19:50:00 -0700892 }
893 }
894 };
895
Christopher Tateb5c07882016-05-26 17:11:09 -0700896 private String getPackageName(Intent intent) {
897 Uri uri = intent.getData();
898 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
899 return pkg;
900 }
901
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700902 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Hui Yu26969322019-08-21 14:56:35 -0700903 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq,
904 int capability) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800905 mHandler.obtainMessage(MSG_UID_STATE_CHANGED, uid, procState).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700906 }
907
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700908 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800909 mHandler.obtainMessage(MSG_UID_GONE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700910 }
911
912 @Override public void onUidActive(int uid) throws RemoteException {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800913 mHandler.obtainMessage(MSG_UID_ACTIVE, uid, 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700914 }
915
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700916 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800917 mHandler.obtainMessage(MSG_UID_IDLE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700918 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700919
920 @Override public void onUidCachedChanged(int uid, boolean cached) {
921 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700922 };
923
Jeff Sharkey4d89e422018-03-29 18:22:41 -0600924 public Context getTestableContext() {
925 return getContext();
926 }
927
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800928 public Object getLock() {
929 return mLock;
930 }
931
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700932 public JobStore getJobStore() {
933 return mJobs;
934 }
935
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700936 public Constants getConstants() {
937 return mConstants;
938 }
939
Kweku Adamsbffea5a2018-12-13 22:13:28 -0800940 public boolean isChainedAttributionEnabled() {
941 return WorkSource.isChainedBatteryAttributionEnabled(getContext());
942 }
943
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700944 @Override
945 public void onStartUser(int userHandle) {
Kweku Adams8bd5edc2018-12-07 18:33:39 -0800946 synchronized (mLock) {
947 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
948 }
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700949 // Let's kick any outstanding jobs for this user.
950 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
951 }
952
953 @Override
954 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700955 // Let's kick any outstanding jobs for this user.
956 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
957 }
958
959 @Override
960 public void onStopUser(int userHandle) {
Kweku Adams8bd5edc2018-12-07 18:33:39 -0800961 synchronized (mLock) {
962 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
963 }
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700964 }
965
Makoto Onuki15407842018-01-19 14:23:11 -0800966 /**
Makoto Onukie4918212018-02-06 11:30:15 -0800967 * Return whether an UID is active or idle.
Makoto Onuki15407842018-01-19 14:23:11 -0800968 */
Makoto Onukie4918212018-02-06 11:30:15 -0800969 private boolean isUidActive(int uid) {
970 return mAppStateTracker.isUidActiveSynced(uid);
Makoto Onuki15407842018-01-19 14:23:11 -0800971 }
972
Makoto Onukie4918212018-02-06 11:30:15 -0800973 private final Predicate<Integer> mIsUidActivePredicate = this::isUidActive;
Makoto Onuki15407842018-01-19 14:23:11 -0800974
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700975 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
976 int userId, String tag) {
Kweku Adamsfd983782020-01-14 15:26:23 -0800977 if (job.isPersisted()) {
978 // Only limit schedule calls for persisted jobs.
979 final String pkg =
980 packageName == null ? job.getService().getPackageName() : packageName;
981 if (!mQuotaTracker.isWithinQuota(userId, pkg, QUOTA_TRACKER_SCHEDULE_PERSISTED_TAG)) {
982 Slog.e(TAG, userId + "-" + pkg + " has called schedule() too many times");
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800983 mAppStandbyInternal.restrictApp(
Kweku Adamsaa461942020-03-16 11:59:05 -0700984 pkg, userId, UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY);
Kweku Adamsf327a3d2020-02-12 16:11:56 -0800985 if (mConstants.API_QUOTA_SCHEDULE_THROW_EXCEPTION) {
Kweku Adamsfd983782020-01-14 15:26:23 -0800986 final boolean isDebuggable;
987 synchronized (mLock) {
988 if (!mDebuggableApps.containsKey(packageName)) {
989 try {
990 final ApplicationInfo appInfo = AppGlobals.getPackageManager()
991 .getApplicationInfo(pkg, 0, userId);
992 if (appInfo != null) {
993 mDebuggableApps.put(packageName,
994 (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
995 } else {
996 return JobScheduler.RESULT_FAILURE;
997 }
998 } catch (RemoteException e) {
999 throw new RuntimeException(e);
Kweku Adams9239a1a2019-11-12 12:06:37 -08001000 }
Kweku Adams9239a1a2019-11-12 12:06:37 -08001001 }
Kweku Adamsfd983782020-01-14 15:26:23 -08001002 isDebuggable = mDebuggableApps.get(packageName);
Kweku Adams9239a1a2019-11-12 12:06:37 -08001003 }
Kweku Adamsfd983782020-01-14 15:26:23 -08001004 if (isDebuggable) {
1005 // Only throw the exception for debuggable apps.
Kweku Adams59bc73a2020-05-12 12:03:56 -07001006 throw new LimitExceededException(
Kweku Adamsfd983782020-01-14 15:26:23 -08001007 "schedule()/enqueue() called more than "
1008 + mQuotaTracker.getLimit(Category.SINGLE_CATEGORY)
1009 + " times in the past "
1010 + mQuotaTracker.getWindowSizeMs(Category.SINGLE_CATEGORY)
1011 + "ms");
1012 }
Kweku Adams9239a1a2019-11-12 12:06:37 -08001013 }
Kweku Adamsfd983782020-01-14 15:26:23 -08001014 return JobScheduler.RESULT_FAILURE;
Kweku Adams9239a1a2019-11-12 12:06:37 -08001015 }
Kweku Adamsfd983782020-01-14 15:26:23 -08001016 mQuotaTracker.noteEvent(userId, pkg, QUOTA_TRACKER_SCHEDULE_PERSISTED_TAG);
Kweku Adams9239a1a2019-11-12 12:06:37 -08001017 }
Kweku Adams9239a1a2019-11-12 12:06:37 -08001018
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001019 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001020 if (ActivityManager.getService().isAppStartModeDisabled(uId,
1021 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001022 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
1023 + " -- package not allowed to start");
1024 return JobScheduler.RESULT_FAILURE;
1025 }
1026 } catch (RemoteException e) {
1027 }
Christopher Tatea732f012017-10-26 17:26:53 -07001028
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001029 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001030 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
1031
1032 if (work != null && toCancel != null) {
1033 // Fast path: we are adding work to an existing job, and the JobInfo is not
1034 // changing. We can just directly enqueue this work in to the job.
1035 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -08001036
Christopher Tate1b1fca82019-08-14 16:59:33 -07001037 toCancel.enqueueWorkLocked(work);
Makoto Onuki15407842018-01-19 14:23:11 -08001038
1039 // If any of work item is enqueued when the source is in the foreground,
1040 // exempt the entire job.
Makoto Onukie4918212018-02-06 11:30:15 -08001041 toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -08001042
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001043 return JobScheduler.RESULT_SUCCESS;
1044 }
1045 }
1046
1047 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -08001048
1049 // Give exemption if the source is in the foreground just now.
1050 // Note if it's a sync job, this method is called on the handler so it's not exactly
1051 // the state when requestSync() was called, but that should be fine because of the
1052 // 1 minute foreground grace period.
Makoto Onukie4918212018-02-06 11:30:15 -08001053 jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -08001054
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001055 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -08001056 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -08001057 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001058 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
1059 Slog.w(TAG, "Too many jobs for uid " + uId);
1060 throw new IllegalStateException("Apps may not schedule more than "
1061 + MAX_JOBS_PER_APP + " distinct jobs");
1062 }
1063 }
1064
Dianne Hackborna47223f2017-03-30 13:49:13 -07001065 // This may throw a SecurityException.
Christopher Tate1b1fca82019-08-14 16:59:33 -07001066 jobStatus.prepareLocked();
Dianne Hackborna47223f2017-03-30 13:49:13 -07001067
Christopher Tate16032042018-10-05 15:53:50 -07001068 if (toCancel != null) {
1069 // Implicitly replaces the existing job record with the new instance
1070 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
1071 } else {
1072 startTrackingJobLocked(jobStatus, null);
1073 }
Christopher Tateb0da63c2019-10-09 14:26:52 -07001074
1075 if (work != null) {
1076 // If work has been supplied, enqueue it into the new job.
1077 jobStatus.enqueueWorkLocked(work);
1078 }
1079
Muhammad Qureshie9aec322020-01-28 10:27:18 -08001080 FrameworkStatsLog.write_non_chained(FrameworkStatsLog.SCHEDULED_JOB_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08001081 uId, null, jobStatus.getBatteryName(),
Muhammad Qureshie9aec322020-01-28 10:27:18 -08001082 FrameworkStatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
Ben Murdoch741e3352019-05-09 11:27:28 +01001083 JobProtoEnums.STOP_REASON_CANCELLED, jobStatus.getStandbyBucket(),
Suprabh Shukla1b5778d2020-02-18 16:39:02 -08001084 jobStatus.getJobId(),
1085 jobStatus.hasChargingConstraint(),
1086 jobStatus.hasBatteryNotLowConstraint(),
1087 jobStatus.hasStorageNotLowConstraint(),
1088 jobStatus.hasTimingDelayConstraint(),
1089 jobStatus.hasDeadlineConstraint(),
1090 jobStatus.hasIdleConstraint(),
1091 jobStatus.hasConnectivityConstraint(),
1092 jobStatus.hasContentTriggerConstraint());
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001093
1094 // If the job is immediately ready to run, then we can just immediately
1095 // put it in the pending list and try to schedule it. This is especially
1096 // important for jobs with a 0 deadline constraint, since they will happen a fair
1097 // amount, we want to handle them as quickly as possible, and semantically we want to
1098 // make sure we have started holding the wake lock for the job before returning to
1099 // the caller.
1100 // If the job is not yet ready to run, there is nothing more to do -- we are
1101 // now just waiting for one of its controllers to change state and schedule
1102 // the job appropriately.
1103 if (isReadyToBeExecutedLocked(jobStatus)) {
1104 // This is a new job, we can just immediately put it on the pending
1105 // list and try to run it.
1106 mJobPackageTracker.notePending(jobStatus);
Kweku Adamscdc2c992020-03-13 13:24:53 -07001107 addOrderedItem(mPendingJobs, jobStatus, sPendingJobComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001108 maybeRunPendingJobsLocked();
Kweku Adamscdbfcb92018-12-06 17:05:15 -08001109 } else {
1110 evaluateControllerStatesLocked(jobStatus);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001111 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001112 }
Christopher Tate7060b042014-06-09 19:50:00 -07001113 return JobScheduler.RESULT_SUCCESS;
1114 }
1115
1116 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001117 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001118 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
1119 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
1120 for (int i = jobs.size() - 1; i >= 0; i--) {
1121 JobStatus job = jobs.get(i);
1122 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -07001123 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001124 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -07001125 }
Christopher Tate7060b042014-06-09 19:50:00 -07001126 }
1127
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001128 public JobInfo getPendingJob(int uid, int jobId) {
1129 synchronized (mLock) {
1130 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
1131 for (int i = jobs.size() - 1; i >= 0; i--) {
1132 JobStatus job = jobs.get(i);
1133 if (job.getJobId() == jobId) {
1134 return job.getJob();
1135 }
1136 }
1137 return null;
1138 }
1139 }
1140
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001141 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001142 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001143 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
1144 for (int i=0; i<jobsForUser.size(); i++) {
1145 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -07001146 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001147 }
Christopher Tate7060b042014-06-09 19:50:00 -07001148 }
1149 }
1150
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001151 private void cancelJobsForNonExistentUsers() {
1152 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
1153 synchronized (mLock) {
1154 mJobs.removeJobsOfNonUsers(umi.getUserIds());
1155 }
1156 }
1157
Makoto Onukie7b96182017-08-30 14:53:16 -07001158 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
1159 if ("android".equals(pkgName)) {
1160 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
1161 return;
1162 }
Christopher Tateee7805b2016-07-15 16:56:56 -07001163 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001164 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
1165 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
1166 final JobStatus job = jobsForUid.get(i);
1167 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -07001168 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001169 }
Christopher Tateee7805b2016-07-15 16:56:56 -07001170 }
1171 }
1172 }
1173
Christopher Tate7060b042014-06-09 19:50:00 -07001174 /**
1175 * Entry point from client to cancel all jobs originating from their uid.
1176 * This will remove the job from the master list, and cancel the job if it was staged for
1177 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -07001178 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -08001179 *
Christopher Tate7060b042014-06-09 19:50:00 -07001180 */
Christopher Tate8c67d122017-09-29 16:54:26 -07001181 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -07001182 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -07001183 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -07001184 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -07001185 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001186
1187 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001188 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001189 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
1190 for (int i=0; i<jobsForUid.size(); i++) {
1191 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -07001192 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -07001193 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001194 }
Christopher Tate7060b042014-06-09 19:50:00 -07001195 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001196 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -07001197 }
1198
1199 /**
1200 * Entry point from client to cancel the job corresponding to the jobId provided.
1201 * This will remove the job from the master list, and cancel the job if it was staged for
1202 * execution or being executed.
1203 * @param uid Uid of the calling client.
1204 * @param jobId Id of the job, provided at schedule-time.
1205 */
Makoto Onukid2bfec62018-01-12 13:58:01 -08001206 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -07001207 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001208 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -07001209 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001210 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -08001211 cancelJobImplLocked(toCancel, null,
1212 "cancel() called by app, callingUid=" + callingUid
1213 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001214 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001215 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -07001216 }
1217 }
1218
Christopher Tate16032042018-10-05 15:53:50 -07001219 /**
1220 * Cancel the given job, stopping it if it's currently executing. If {@code incomingJob}
1221 * is null, the cancelled job is removed outright from the system. If
1222 * {@code incomingJob} is non-null, it replaces {@code cancelled} in the store of
1223 * currently scheduled jobs.
1224 */
Dianne Hackborn729a3282017-06-09 16:06:01 -07001225 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001226 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
Christopher Tate1b1fca82019-08-14 16:59:33 -07001227 cancelled.unprepareLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001228 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
1229 // Remove from pending queue.
1230 if (mPendingJobs.remove(cancelled)) {
1231 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -07001232 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001233 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -07001234 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Christopher Tate16032042018-10-05 15:53:50 -07001235 // If this is a replacement, bring in the new version of the job
1236 if (incomingJob != null) {
1237 if (DEBUG) Slog.i(TAG, "Tracking replacement job " + incomingJob.toShortString());
1238 startTrackingJobLocked(incomingJob, cancelled);
1239 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001240 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001241 }
1242
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001243 void updateUidState(int uid, int procState) {
1244 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001245 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1246 // Only use this if we are exactly the top app. All others can live
1247 // with just the foreground priority. This means that persistent processes
1248 // can never be the top app priority... that is fine.
1249 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08001250 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
1251 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_SERVICE);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001252 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Makoto Onukiec8b14d2018-12-05 13:22:24 -08001253 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_BOUND_FOREGROUND_SERVICE);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001254 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001255 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001256 }
1257 }
1258 }
1259
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001260 @Override
1261 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001262 synchronized (mLock) {
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001263 if (DEBUG) {
1264 Slog.d(TAG, "Doze state changed: " + deviceIdle);
1265 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001266 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001267 // When becoming idle, make sure no jobs are actively running,
1268 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001269 for (int i=0; i<mActiveServices.size(); i++) {
1270 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001271 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001272 if (executing != null
1273 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001274 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1275 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001276 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001277 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001278 } else {
1279 // When coming out of idle, allow thing to start back up.
1280 if (mReadyToRock) {
1281 if (mLocalDeviceIdleController != null) {
1282 if (!mReportedActive) {
1283 mReportedActive = true;
1284 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001285 }
1286 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001287 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001288 }
1289 }
1290 }
1291 }
1292
Kweku Adamsae9d6be2020-01-14 16:10:14 -08001293 @Override
1294 public void onRestrictedBucketChanged(List<JobStatus> jobs) {
1295 final int len = jobs.size();
1296 if (len == 0) {
1297 Slog.wtf(TAG, "onRestrictedBucketChanged called with no jobs");
1298 return;
1299 }
1300 synchronized (mLock) {
1301 for (int i = 0; i < len; ++i) {
1302 JobStatus js = jobs.get(i);
1303 for (int j = mRestrictiveControllers.size() - 1; j >= 0; --j) {
1304 // Effective standby bucket can change after this in some situations so use
1305 // the real bucket so that the job is tracked by the controllers.
1306 if (js.getStandbyBucket() == RESTRICTED_INDEX) {
Kweku Adamsae9d6be2020-01-14 16:10:14 -08001307 mRestrictiveControllers.get(j).startTrackingRestrictedJobLocked(js);
1308 } else {
Kweku Adamsae9d6be2020-01-14 16:10:14 -08001309 mRestrictiveControllers.get(j).stopTrackingRestrictedJobLocked(js);
1310 }
1311 }
1312 }
1313 }
1314 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1315 }
1316
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001317 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001318 // active is true if pending queue contains jobs OR some job is running.
1319 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001320 if (mPendingJobs.size() <= 0) {
1321 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001322 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001323 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001324 if (job != null
1325 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
Christopher Tate20afddd2018-02-28 15:19:19 -08001326 && !job.dozeWhitelisted
1327 && !job.uidActive) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001328 // We will report active if we have a job running and it is not an exception
1329 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001330 active = true;
1331 break;
1332 }
1333 }
1334 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001335
1336 if (mReportedActive != active) {
1337 mReportedActive = active;
1338 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001339 mLocalDeviceIdleController.setJobsActive(active);
1340 }
1341 }
1342 }
1343
Christopher Tated117b292018-01-05 17:32:36 -08001344 void reportAppUsage(String packageName, int userId) {
1345 // This app just transitioned into interactive use or near equivalent, so we should
1346 // take a look at its job state for feedback purposes.
1347 }
1348
Christopher Tate7060b042014-06-09 19:50:00 -07001349 /**
1350 * Initializes the system service.
1351 * <p>
1352 * Subclasses must define a single argument constructor that accepts the context
1353 * and passes it to super.
1354 * </p>
1355 *
1356 * @param context The system server context.
1357 */
1358 public JobSchedulerService(Context context) {
1359 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001360
1361 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Daulet Zhanguzin489e9c32019-12-30 12:45:49 +00001362 mActivityManagerInternal = Objects.requireNonNull(
Makoto Onuki15407842018-01-19 14:23:11 -08001363 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001364
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001365 mHandler = new JobHandler(context.getMainLooper());
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001366 mConstants = new Constants();
1367 mConstantsObserver = new ConstantsObserver(mHandler);
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001368 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001369
Makoto Onuki714f97d2018-12-05 11:18:13 -08001370 mConcurrencyManager = new JobConcurrencyManager(this);
1371
Christopher Tatea732f012017-10-26 17:26:53 -07001372 // Set up the app standby bucketing tracker
Christopher Tated1aebb32018-01-31 13:24:14 -08001373 mStandbyTracker = new StandbyTracker();
1374 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Kweku Adams9239a1a2019-11-12 12:06:37 -08001375 mQuotaTracker = new CountQuotaTracker(context, Categorizer.SINGLE_CATEGORIZER);
1376 mQuotaTracker.setCountLimit(Category.SINGLE_CATEGORY,
1377 mConstants.API_QUOTA_SCHEDULE_COUNT,
1378 mConstants.API_QUOTA_SCHEDULE_WINDOW_MS);
Christopher Tateb909c4d52019-10-21 12:50:37 -07001379
Kweku Adamsc6a9b342020-01-08 18:37:26 -08001380 mAppStandbyInternal = LocalServices.getService(AppStandbyInternal.class);
1381 mAppStandbyInternal.addListener(mStandbyTracker);
Christopher Tatea732f012017-10-26 17:26:53 -07001382
1383 // The job store needs to call back
1384 publishLocalService(JobSchedulerInternal.class, new LocalService());
1385
1386 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001387 mJobs = JobStore.initAndGet(this);
1388
Christopher Tate7060b042014-06-09 19:50:00 -07001389 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001390 mControllers = new ArrayList<StateController>();
Kweku Adamsae9d6be2020-01-14 16:10:14 -08001391 final ConnectivityController connectivityController = new ConnectivityController(this);
1392 mControllers.add(connectivityController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001393 mControllers.add(new TimeController(this));
Kweku Adamsae9d6be2020-01-14 16:10:14 -08001394 final IdleController idleController = new IdleController(this);
1395 mControllers.add(idleController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001396 mBatteryController = new BatteryController(this);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001397 mControllers.add(mBatteryController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001398 mStorageController = new StorageController(this);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001399 mControllers.add(mStorageController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001400 mControllers.add(new BackgroundJobsController(this));
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001401 mControllers.add(new ContentObserverController(this));
1402 mDeviceIdleJobsController = new DeviceIdleJobsController(this);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001403 mControllers.add(mDeviceIdleJobsController);
Kweku Adamsb4b8b9c2019-06-13 18:37:51 -07001404 mQuotaController = new QuotaController(this);
1405 mControllers.add(mQuotaController);
Christopher Tate616541d2017-07-26 14:27:38 -07001406
Kweku Adamsae9d6be2020-01-14 16:10:14 -08001407 mRestrictiveControllers = new ArrayList<>();
1408 mRestrictiveControllers.add(mBatteryController);
1409 mRestrictiveControllers.add(connectivityController);
1410 mRestrictiveControllers.add(idleController);
1411
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02001412 // Create restrictions
1413 mJobRestrictions = new ArrayList<>();
1414 mJobRestrictions.add(new ThermalStatusRestriction(this));
1415
Suprabh Shukla08126472020-02-04 20:46:35 -08001416 mSystemGalleryPackage = Objects.requireNonNull(
1417 context.getString(R.string.config_systemGallery));
1418
Christopher Tate616541d2017-07-26 14:27:38 -07001419 // If the job store determined that it can't yet reschedule persisted jobs,
1420 // we need to start watching the clock.
1421 if (!mJobs.jobTimesInflatedValid()) {
1422 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1423 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1424 }
Christopher Tate7060b042014-06-09 19:50:00 -07001425 }
1426
Christopher Tate616541d2017-07-26 14:27:38 -07001427 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1428 @Override
1429 public void onReceive(Context context, Intent intent) {
1430 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1431 // When we reach clock sanity, recalculate the temporal windows
1432 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001433 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001434 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1435
1436 // We've done our job now, so stop watching the time.
1437 context.unregisterReceiver(this);
1438
1439 // And kick off the work to update the affected jobs, using a secondary
1440 // thread instead of chugging away here on the main looper thread.
1441 FgThread.getHandler().post(mJobTimeUpdater);
1442 }
1443 }
1444 }
1445 };
1446
1447 private final Runnable mJobTimeUpdater = () -> {
1448 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1449 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1450 synchronized (mLock) {
1451 // Note: we intentionally both look up the existing affected jobs and replace them
1452 // with recalculated ones inside the same lock lifetime.
1453 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1454
1455 // Now, at each position [i], we have both the existing JobStatus
1456 // and the one that replaces it.
1457 final int N = toAdd.size();
1458 for (int i = 0; i < N; i++) {
1459 final JobStatus oldJob = toRemove.get(i);
1460 final JobStatus newJob = toAdd.get(i);
1461 if (DEBUG) {
1462 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1463 }
1464 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1465 }
1466 }
1467 };
1468
Christopher Tate7060b042014-06-09 19:50:00 -07001469 @Override
1470 public void onStart() {
1471 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1472 }
1473
1474 @Override
1475 public void onBootPhase(int phase) {
1476 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001477 mConstantsObserver.start(getContext().getContentResolver());
Kweku Adams4e774a32019-04-24 18:01:29 -07001478 for (StateController controller : mControllers) {
1479 controller.onSystemServicesReady();
1480 }
Makoto Onuki15407842018-01-19 14:23:11 -08001481
Daulet Zhanguzin489e9c32019-12-30 12:45:49 +00001482 mAppStateTracker = Objects.requireNonNull(
Makoto Onukie4918212018-02-06 11:30:15 -08001483 LocalServices.getService(AppStateTracker.class));
Makoto Onuki15407842018-01-19 14:23:11 -08001484
Shreyas Basarge5db09082016-01-07 13:38:29 +00001485 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001486 final IntentFilter filter = new IntentFilter();
1487 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1488 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001489 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1490 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001491 filter.addDataScheme("package");
1492 getContext().registerReceiverAsUser(
1493 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1494 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1495 getContext().registerReceiverAsUser(
1496 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001497 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001498 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001499 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001500 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1501 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001502 } catch (RemoteException e) {
1503 // ignored; both services live in system_server
1504 }
Makoto Onukic279f2b2019-01-09 13:11:37 -08001505
1506 mConcurrencyManager.onSystemReady();
1507
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001508 // Remove any jobs that are not associated with any of the current users.
1509 cancelJobsForNonExistentUsers();
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02001510
1511 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
1512 mJobRestrictions.get(i).onSystemServicesReady();
Wei Wang8c0c3c12018-11-14 14:56:52 -08001513 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001514 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001515 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001516 // Let's go!
1517 mReadyToRock = true;
1518 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1519 BatteryStats.SERVICE_NAME));
Makoto Onukieaf7eed2019-08-12 15:27:15 -07001520 mLocalDeviceIdleController =
1521 LocalServices.getService(DeviceIdleInternal.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001522 // Create the "runners".
1523 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1524 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001525 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001526 getContext().getMainLooper()));
1527 }
1528 // Attach jobs to their controllers.
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001529 mJobs.forEachJob((job) -> {
1530 for (int controller = 0; controller < mControllers.size(); controller++) {
1531 final StateController sc = mControllers.get(controller);
1532 sc.maybeStartTrackingJobLocked(job, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001533 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001534 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001535 // GO GO GO!
1536 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1537 }
Christopher Tate7060b042014-06-09 19:50:00 -07001538 }
1539 }
1540
1541 /**
1542 * Called when we have a job status object that we need to insert in our
1543 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1544 * about.
1545 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001546 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1547 if (!jobStatus.isPreparedLocked()) {
1548 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1549 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001550 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001551 final boolean update = mJobs.add(jobStatus);
1552 if (mReadyToRock) {
1553 for (int i = 0; i < mControllers.size(); i++) {
1554 StateController controller = mControllers.get(i);
1555 if (update) {
1556 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001557 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001558 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001559 }
Christopher Tate7060b042014-06-09 19:50:00 -07001560 }
1561 }
1562
1563 /**
Kweku Adams8843a2812019-07-02 15:30:23 -07001564 * Called when we want to remove a JobStatus object that we've finished executing.
1565 * @return true if the job was removed.
Christopher Tate7060b042014-06-09 19:50:00 -07001566 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001567 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Kweku Adams8843a2812019-07-02 15:30:23 -07001568 boolean removeFromPersisted) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001569 // Deal with any remaining work items in the old job.
Christopher Tate1b1fca82019-08-14 16:59:33 -07001570 jobStatus.stopTrackingJobLocked(incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001571
1572 // Remove from store as well as controllers.
Kweku Adams8843a2812019-07-02 15:30:23 -07001573 final boolean removed = mJobs.remove(jobStatus, removeFromPersisted);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001574 if (removed && mReadyToRock) {
1575 for (int i=0; i<mControllers.size(); i++) {
1576 StateController controller = mControllers.get(i);
1577 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001578 }
1579 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001580 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001581 }
1582
Dianne Hackborn729a3282017-06-09 16:06:01 -07001583 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001584 for (int i=0; i<mActiveServices.size(); i++) {
1585 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001586 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001587 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001588 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001589 return true;
1590 }
1591 }
1592 return false;
1593 }
1594
1595 /**
1596 * @param job JobStatus we are querying against.
1597 * @return Whether or not the job represented by the status object is currently being run or
1598 * is pending.
1599 */
1600 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001601 for (int i=0; i<mActiveServices.size(); i++) {
1602 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001603 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001604 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1605 return true;
1606 }
1607 }
1608 return false;
1609 }
1610
Dianne Hackborn807de782016-04-07 17:54:41 -07001611 void noteJobsPending(List<JobStatus> jobs) {
1612 for (int i = jobs.size() - 1; i >= 0; i--) {
1613 JobStatus job = jobs.get(i);
1614 mJobPackageTracker.notePending(job);
1615 }
1616 }
1617
1618 void noteJobsNonpending(List<JobStatus> jobs) {
1619 for (int i = jobs.size() - 1; i >= 0; i--) {
1620 JobStatus job = jobs.get(i);
1621 mJobPackageTracker.noteNonpending(job);
1622 }
1623 }
1624
Christopher Tate7060b042014-06-09 19:50:00 -07001625 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001626 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1627 * specify an override deadline on a failed job (the failed job will run even though it's not
1628 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
Makoto Onukic279f2b2019-01-09 13:11:37 -08001629 * ready job with {@link JobStatus#getNumFailures()} > 0 will be executed.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001630 *
Christopher Tate7060b042014-06-09 19:50:00 -07001631 * @param failureToReschedule Provided job status that we will reschedule.
1632 * @return A newly instantiated JobStatus with the same constraints as the last job except
1633 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001634 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001635 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001636 */
Kweku Adamsc9793092019-04-30 11:54:48 -07001637 @VisibleForTesting
1638 JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001639 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001640 final JobInfo job = failureToReschedule.getJob();
1641
1642 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001643 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1644 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001645
1646 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001647 case JobInfo.BACKOFF_POLICY_LINEAR: {
1648 long backoff = initialBackoffMillis;
1649 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1650 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1651 }
1652 delayMillis = backoff * backoffAttempts;
1653 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001654 default:
1655 if (DEBUG) {
1656 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1657 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001658 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1659 long backoff = initialBackoffMillis;
1660 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1661 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1662 }
1663 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1664 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001665 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001666 delayMillis =
1667 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Kweku Adams6c5dc642019-07-25 10:29:38 -07001668 JobStatus newJob = new JobStatus(failureToReschedule,
Christopher Tatea732f012017-10-26 17:26:53 -07001669 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001670 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001671 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Kweku Adamsc9793092019-04-30 11:54:48 -07001672 if (job.isPeriodic()) {
1673 newJob.setOriginalLatestRunTimeElapsed(
1674 failureToReschedule.getOriginalLatestRunTimeElapsed());
1675 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001676 for (int ic=0; ic<mControllers.size(); ic++) {
1677 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001678 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001679 }
1680 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001681 }
1682
1683 /**
Kweku Adamsb6722782019-05-01 14:46:05 -07001684 * Maximum time buffer in which JobScheduler will try to optimize periodic job scheduling. This
1685 * does not cause a job's period to be larger than requested (eg: if the requested period is
1686 * shorter than this buffer). This is used to put a limit on when JobScheduler will intervene
1687 * and try to optimize scheduling if the current job finished less than this amount of time to
1688 * the start of the next period
1689 */
1690 private static final long PERIODIC_JOB_WINDOW_BUFFER = 30 * MINUTE_IN_MILLIS;
1691
Kweku Adams966e72b2019-05-30 14:45:39 -07001692 /** The maximum period a periodic job can have. Anything higher will be clamped down to this. */
1693 public static final long MAX_ALLOWED_PERIOD_MS = 365 * 24 * 60 * 60 * 1000L;
1694
Kweku Adamsb6722782019-05-01 14:46:05 -07001695 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001696 * Called after a periodic has executed so we can reschedule it. We take the last execution
1697 * time of the job to be the time of completion (i.e. the time at which this function is
1698 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001699 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001700 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1701 * to underscheduling at least, rather than if we had taken the last execution time to be the
1702 * start of the execution.
Kweku Adams6c5dc642019-07-25 10:29:38 -07001703 *
Christopher Tate7060b042014-06-09 19:50:00 -07001704 * @return A new job representing the execution criteria for this instantiation of the
1705 * recurring job.
1706 */
Kweku Adamsc9793092019-04-30 11:54:48 -07001707 @VisibleForTesting
1708 JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001709 final long elapsedNow = sElapsedRealtimeClock.millis();
Kweku Adamsc9793092019-04-30 11:54:48 -07001710 final long newLatestRuntimeElapsed;
Kweku Adams966e72b2019-05-30 14:45:39 -07001711 // Make sure period is in the interval [min_possible_period, max_possible_period].
1712 final long period = Math.max(JobInfo.getMinPeriodMillis(),
1713 Math.min(MAX_ALLOWED_PERIOD_MS, periodicToReschedule.getJob().getIntervalMillis()));
1714 // Make sure flex is in the interval [min_possible_flex, period].
1715 final long flex = Math.max(JobInfo.getMinFlexMillis(),
1716 Math.min(period, periodicToReschedule.getJob().getFlexMillis()));
Kweku Adamsb6722782019-05-01 14:46:05 -07001717 long rescheduleBuffer = 0;
Matthew Williams1bde39a2015-10-07 14:29:30 -07001718
Kweku Adams966e72b2019-05-30 14:45:39 -07001719 long olrte = periodicToReschedule.getOriginalLatestRunTimeElapsed();
1720 if (olrte < 0 || olrte == JobStatus.NO_LATEST_RUNTIME) {
1721 Slog.wtf(TAG, "Invalid periodic job original latest run time: " + olrte);
1722 olrte = elapsedNow;
1723 }
1724 final long latestRunTimeElapsed = olrte;
1725
Kweku Adamsb6722782019-05-01 14:46:05 -07001726 final long diffMs = Math.abs(elapsedNow - latestRunTimeElapsed);
Kweku Adamsc9793092019-04-30 11:54:48 -07001727 if (elapsedNow > latestRunTimeElapsed) {
1728 // The job ran past its expected run window. Have it count towards the current window
1729 // and schedule a new job for the next window.
1730 if (DEBUG) {
1731 Slog.i(TAG, "Periodic job ran after its intended window.");
1732 }
Kweku Adams966e72b2019-05-30 14:45:39 -07001733 long numSkippedWindows = (diffMs / period) + 1; // +1 to include original window
Kweku Adamsb6722782019-05-01 14:46:05 -07001734 if (period != flex && diffMs > Math.min(PERIODIC_JOB_WINDOW_BUFFER,
1735 (period - flex) / 2)) {
Kweku Adamsc9793092019-04-30 11:54:48 -07001736 if (DEBUG) {
1737 Slog.d(TAG, "Custom flex job ran too close to next window.");
1738 }
1739 // For custom flex periods, if the job was run too close to the next window,
1740 // skip the next window and schedule for the following one.
1741 numSkippedWindows += 1;
1742 }
1743 newLatestRuntimeElapsed = latestRunTimeElapsed + (period * numSkippedWindows);
1744 } else {
1745 newLatestRuntimeElapsed = latestRunTimeElapsed + period;
Kweku Adamsb6722782019-05-01 14:46:05 -07001746 if (diffMs < PERIODIC_JOB_WINDOW_BUFFER && diffMs < period / 6) {
1747 // Add a little buffer to the start of the next window so the job doesn't run
1748 // too soon after this completed one.
1749 rescheduleBuffer = Math.min(PERIODIC_JOB_WINDOW_BUFFER, period / 6 - diffMs);
1750 }
Matthew Williams1bde39a2015-10-07 14:29:30 -07001751 }
Kweku Adamsc9793092019-04-30 11:54:48 -07001752
Kweku Adams966e72b2019-05-30 14:45:39 -07001753 if (newLatestRuntimeElapsed < elapsedNow) {
1754 Slog.wtf(TAG, "Rescheduling calculated latest runtime in the past: "
1755 + newLatestRuntimeElapsed);
Kweku Adams6c5dc642019-07-25 10:29:38 -07001756 return new JobStatus(periodicToReschedule,
Kweku Adams966e72b2019-05-30 14:45:39 -07001757 elapsedNow + period - flex, elapsedNow + period,
1758 0 /* backoffAttempt */,
1759 sSystemClock.millis() /* lastSuccessfulRunTime */,
1760 periodicToReschedule.getLastFailedRunTime());
1761 }
1762
Kweku Adamsb6722782019-05-01 14:46:05 -07001763 final long newEarliestRunTimeElapsed = newLatestRuntimeElapsed
1764 - Math.min(flex, period - rescheduleBuffer);
Christopher Tate7060b042014-06-09 19:50:00 -07001765
1766 if (DEBUG) {
1767 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
Kweku Adamsc9793092019-04-30 11:54:48 -07001768 newEarliestRunTimeElapsed / 1000 + ", " + newLatestRuntimeElapsed / 1000
1769 + "]s");
Christopher Tate7060b042014-06-09 19:50:00 -07001770 }
Kweku Adams6c5dc642019-07-25 10:29:38 -07001771 return new JobStatus(periodicToReschedule,
Christopher Tatea732f012017-10-26 17:26:53 -07001772 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1773 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001774 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001775 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001776 }
1777
1778 // JobCompletedListener implementations.
1779
1780 /**
1781 * A job just finished executing. We fetch the
1782 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
Christopher Tate325768c2018-03-07 16:07:56 -08001783 * whether we want to reschedule we re-add it to the controllers.
Christopher Tate7060b042014-06-09 19:50:00 -07001784 * @param jobStatus Completed job.
1785 * @param needsReschedule Whether the implementing class should reschedule this job.
1786 */
1787 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001788 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001789 if (DEBUG) {
1790 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1791 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001792
1793 // If the job wants to be rescheduled, we first need to make the next upcoming
1794 // job so we can transfer any appropriate state over from the previous job when
1795 // we stop it.
1796 final JobStatus rescheduledJob = needsReschedule
1797 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1798
Shreyas Basarge73f10252016-02-11 17:06:13 +00001799 // Do not write back immediately if this is a periodic job. The job may get lost if system
1800 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001801 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001802 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001803 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001804 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001805 // We still want to check for jobs to execute, because this job may have
1806 // scheduled a new job under the same job id, and now we can run it.
1807 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001808 return;
1809 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001810
1811 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001812 try {
Christopher Tate1b1fca82019-08-14 16:59:33 -07001813 rescheduledJob.prepareLocked();
Dianne Hackborna47223f2017-03-30 13:49:13 -07001814 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001815 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001816 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001817 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001818 } else if (jobStatus.getJob().isPeriodic()) {
1819 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001820 try {
Christopher Tate1b1fca82019-08-14 16:59:33 -07001821 rescheduledPeriodic.prepareLocked();
Dianne Hackborna47223f2017-03-30 13:49:13 -07001822 } catch (SecurityException e) {
1823 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1824 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001825 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001826 }
Christopher Tate1b1fca82019-08-14 16:59:33 -07001827 jobStatus.unprepareLocked();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001828 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001829 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001830 }
1831
1832 // StateChangedListener implementations.
1833
1834 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001835 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1836 * some controller's state has changed, so as to run through the list of jobs and start/stop
1837 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001838 */
1839 @Override
1840 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001841 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001842 }
1843
1844 @Override
1845 public void onRunJobNow(JobStatus jobStatus) {
1846 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1847 }
1848
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001849 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001850
1851 public JobHandler(Looper looper) {
1852 super(looper);
1853 }
1854
1855 @Override
1856 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001857 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001858 if (!mReadyToRock) {
1859 return;
1860 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001861 switch (message.what) {
1862 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001863 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001864 // runNow can be null, which is a controller's way of indicating that its
1865 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001866 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001867 mJobPackageTracker.notePending(runNow);
Kweku Adamscdc2c992020-03-13 13:24:53 -07001868 addOrderedItem(mPendingJobs, runNow, sPendingJobComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001869 } else {
1870 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001871 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001872 } break;
1873 case MSG_CHECK_JOB:
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001874 if (DEBUG) {
1875 Slog.d(TAG, "MSG_CHECK_JOB");
1876 }
Kulwinder Singh9557fe82018-08-31 13:14:03 +05301877 removeMessages(MSG_CHECK_JOB);
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001878 if (mReportedActive) {
1879 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001880 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001881 } else {
1882 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001883 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001884 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001885 break;
1886 case MSG_CHECK_JOB_GREEDY:
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001887 if (DEBUG) {
1888 Slog.d(TAG, "MSG_CHECK_JOB_GREEDY");
1889 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001890 queueReadyJobsForExecutionLocked();
1891 break;
1892 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001893 cancelJobImplLocked((JobStatus) message.obj, null,
1894 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001895 break;
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001896
1897 case MSG_UID_STATE_CHANGED: {
1898 final int uid = message.arg1;
1899 final int procState = message.arg2;
1900 updateUidState(uid, procState);
1901 break;
1902 }
1903 case MSG_UID_GONE: {
1904 final int uid = message.arg1;
1905 final boolean disabled = message.arg2 != 0;
1906 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1907 if (disabled) {
1908 cancelJobsForUid(uid, "uid gone");
1909 }
1910 synchronized (mLock) {
1911 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1912 }
1913 break;
1914 }
1915 case MSG_UID_ACTIVE: {
1916 final int uid = message.arg1;
1917 synchronized (mLock) {
1918 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
1919 }
1920 break;
1921 }
1922 case MSG_UID_IDLE: {
1923 final int uid = message.arg1;
1924 final boolean disabled = message.arg2 != 0;
1925 if (disabled) {
1926 cancelJobsForUid(uid, "app uid idle");
1927 }
1928 synchronized (mLock) {
1929 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1930 }
1931 break;
1932 }
1933
Matthew Williams75fc5252014-09-02 16:17:53 -07001934 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001935 maybeRunPendingJobsLocked();
1936 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
Christopher Tate7060b042014-06-09 19:50:00 -07001937 }
1938 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001939 }
Christopher Tate7060b042014-06-09 19:50:00 -07001940
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02001941 /**
1942 * Check if a job is restricted by any of the declared {@link JobRestriction}s.
1943 * Note, that the jobs with {@link JobInfo#PRIORITY_FOREGROUND_APP} priority or higher may not
1944 * be restricted, thus we won't even perform the check, but simply return null early.
1945 *
1946 * @param job to be checked
1947 * @return the first {@link JobRestriction} restricting the given job that has been found; null
1948 * - if passes all the restrictions or has priority {@link JobInfo#PRIORITY_FOREGROUND_APP}
1949 * or higher.
1950 */
1951 private JobRestriction checkIfRestricted(JobStatus job) {
1952 if (evaluateJobPriorityLocked(job) >= JobInfo.PRIORITY_FOREGROUND_APP) {
1953 // Jobs with PRIORITY_FOREGROUND_APP or higher should not be restricted
1954 return null;
1955 }
1956 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
1957 final JobRestriction restriction = mJobRestrictions.get(i);
1958 if (restriction.isJobRestricted(job)) {
1959 return restriction;
1960 }
1961 }
1962 return null;
Wei Wang8c0c3c12018-11-14 14:56:52 -08001963 }
1964
Dianne Hackborn6d068262017-05-16 13:14:37 -07001965 private void stopNonReadyActiveJobsLocked() {
1966 for (int i=0; i<mActiveServices.size(); i++) {
1967 JobServiceContext serviceContext = mActiveServices.get(i);
1968 final JobStatus running = serviceContext.getRunningJobLocked();
Wei Wang8c0c3c12018-11-14 14:56:52 -08001969 if (running == null) {
1970 continue;
1971 }
1972 if (!running.isReady()) {
Kweku Adams338ce0b2020-02-25 14:46:59 -08001973 // If a restricted job doesn't have dynamic constraints satisfied, assume that's
1974 // the reason the job is being stopped, instead of because of other constraints
1975 // not being satisfied.
1976 if (running.getEffectiveStandbyBucket() == RESTRICTED_INDEX
1977 && !running.areDynamicConstraintsSatisfied()) {
1978 serviceContext.cancelExecutingJobLocked(
1979 JobParameters.REASON_RESTRICTED_BUCKET,
1980 "cancelled due to restricted bucket");
1981 } else {
1982 serviceContext.cancelExecutingJobLocked(
1983 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1984 "cancelled due to unsatisfied constraints");
1985 }
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02001986 } else {
1987 final JobRestriction restriction = checkIfRestricted(running);
1988 if (restriction != null) {
1989 final int reason = restriction.getReason();
1990 serviceContext.cancelExecutingJobLocked(reason,
Kweku Adams13289702020-02-19 17:28:55 -08001991 "restricted due to " + JobParameters.getReasonCodeDescription(reason));
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02001992 }
Dianne Hackborn6d068262017-05-16 13:14:37 -07001993 }
1994 }
1995 }
1996
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001997 /**
1998 * Run through list of jobs and execute all possible - at least one is expired so we do
1999 * as many as we can.
2000 */
2001 private void queueReadyJobsForExecutionLocked() {
2002 if (DEBUG) {
2003 Slog.d(TAG, "queuing all ready jobs for execution:");
2004 }
2005 noteJobsNonpending(mPendingJobs);
2006 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002007 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002008 mJobs.forEachJob(mReadyQueueFunctor);
2009 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08002010
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002011 if (DEBUG) {
2012 final int queuedJobs = mPendingJobs.size();
2013 if (queuedJobs == 0) {
2014 Slog.d(TAG, "No jobs pending.");
2015 } else {
2016 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08002017 }
2018 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002019 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002020
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002021 final class ReadyJobQueueFunctor implements Consumer<JobStatus> {
Kweku Adams41cb3322019-06-26 14:42:26 -07002022 final ArrayList<JobStatus> newReadyJobs = new ArrayList<>();
Christopher Tate2f36fd62016-02-18 18:36:08 -08002023
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002024 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002025 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002026 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07002027 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002028 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07002029 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002030 newReadyJobs.add(job);
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002031 } else {
2032 evaluateControllerStatesLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -07002033 }
2034 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002035
2036 public void postProcess() {
Kweku Adams41cb3322019-06-26 14:42:26 -07002037 noteJobsPending(newReadyJobs);
2038 mPendingJobs.addAll(newReadyJobs);
2039 if (mPendingJobs.size() > 1) {
Kweku Adamscdc2c992020-03-13 13:24:53 -07002040 mPendingJobs.sort(sPendingJobComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002041 }
Kweku Adams41cb3322019-06-26 14:42:26 -07002042
2043 newReadyJobs.clear();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002044 }
2045 }
2046 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
2047
2048 /**
2049 * The state of at least one job has changed. Here is where we could enforce various
2050 * policies on when we want to execute jobs.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002051 */
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002052 final class MaybeReadyJobQueueFunctor implements Consumer<JobStatus> {
Kweku Adams41cb3322019-06-26 14:42:26 -07002053 int forceBatchedCount;
2054 int unbatchedCount;
2055 final List<JobStatus> runnableJobs = new ArrayList<>();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002056
2057 public MaybeReadyJobQueueFunctor() {
2058 reset();
2059 }
2060
2061 // Functor method invoked for each job via JobStore.forEachJob()
2062 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002063 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002064 if (isReadyToBeExecutedLocked(job)) {
2065 try {
2066 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
2067 job.getJob().getService().getPackageName())) {
2068 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
2069 + job.getJob().toString() + " -- package not allowed to start");
2070 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
2071 return;
2072 }
2073 } catch (RemoteException e) {
2074 }
Kweku Adams111b8222020-02-11 12:06:26 -08002075
2076 final boolean shouldForceBatchJob;
Kweku Adamsae9d6be2020-01-14 16:10:14 -08002077 // Restricted jobs must always be batched
Kweku Adams111b8222020-02-11 12:06:26 -08002078 if (job.getEffectiveStandbyBucket() == RESTRICTED_INDEX) {
2079 shouldForceBatchJob = true;
2080 } else if (job.getNumFailures() > 0) {
2081 shouldForceBatchJob = false;
2082 } else {
2083 final long nowElapsed = sElapsedRealtimeClock.millis();
2084 final boolean batchDelayExpired = job.getFirstForceBatchedTimeElapsed() > 0
2085 && nowElapsed - job.getFirstForceBatchedTimeElapsed()
2086 >= mConstants.MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS;
2087 shouldForceBatchJob =
2088 mConstants.MIN_READY_NON_ACTIVE_JOBS_COUNT > 1
2089 && job.getEffectiveStandbyBucket() != ACTIVE_INDEX
2090 && !batchDelayExpired;
2091 }
2092
2093 if (shouldForceBatchJob) {
Kweku Adams41cb3322019-06-26 14:42:26 -07002094 // Force batching non-ACTIVE jobs. Don't include them in the other counts.
2095 forceBatchedCount++;
2096 if (job.getFirstForceBatchedTimeElapsed() == 0) {
2097 job.setFirstForceBatchedTimeElapsed(sElapsedRealtimeClock.millis());
2098 }
2099 } else {
2100 unbatchedCount++;
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002101 }
2102 runnableJobs.add(job);
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002103 } else {
2104 evaluateControllerStatesLocked(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002105 }
2106 }
2107
2108 public void postProcess() {
Kweku Adams111b8222020-02-11 12:06:26 -08002109 if (unbatchedCount > 0
2110 || forceBatchedCount >= mConstants.MIN_READY_NON_ACTIVE_JOBS_COUNT) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002111 if (DEBUG) {
2112 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
2113 }
2114 noteJobsPending(runnableJobs);
2115 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002116 if (mPendingJobs.size() > 1) {
Kweku Adamscdc2c992020-03-13 13:24:53 -07002117 mPendingJobs.sort(sPendingJobComparator);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002118 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002119 } else {
2120 if (DEBUG) {
2121 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
2122 }
2123 }
2124
2125 // Be ready for next time
2126 reset();
2127 }
2128
Kweku Adams41cb3322019-06-26 14:42:26 -07002129 @VisibleForTesting
2130 void reset() {
Kweku Adams41cb3322019-06-26 14:42:26 -07002131 forceBatchedCount = 0;
2132 unbatchedCount = 0;
2133 runnableJobs.clear();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002134 }
2135 }
2136 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
2137
2138 private void maybeQueueReadyJobsForExecutionLocked() {
2139 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
2140
2141 noteJobsNonpending(mPendingJobs);
2142 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002143 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002144 mJobs.forEachJob(mMaybeQueueFunctor);
2145 mMaybeQueueFunctor.postProcess();
2146 }
2147
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002148 /** Returns true if both the calling and source users for the job are started. */
2149 private boolean areUsersStartedLocked(final JobStatus job) {
2150 boolean sourceStarted = ArrayUtils.contains(mStartedUsers, job.getSourceUserId());
2151 if (job.getUserId() == job.getSourceUserId()) {
2152 return sourceStarted;
2153 }
2154 return sourceStarted && ArrayUtils.contains(mStartedUsers, job.getUserId());
2155 }
2156
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002157 /**
2158 * Criteria for moving a job into the pending queue:
2159 * - It's ready.
2160 * - It's not pending.
2161 * - It's not already running on a JSC.
2162 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07002163 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002164 * - The component is enabled and runnable.
2165 */
Kweku Adams41cb3322019-06-26 14:42:26 -07002166 @VisibleForTesting
2167 boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002168 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002169
2170 if (DEBUG) {
2171 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2172 + " ready=" + jobReady);
2173 }
2174
2175 // This is a condition that is very likely to be false (most jobs that are
2176 // scheduled are sitting there, not ready yet) and very cheap to check (just
2177 // a few conditions on data in JobStatus).
2178 if (!jobReady) {
Christopher Tate20afddd2018-02-28 15:19:19 -08002179 if (job.getSourcePackageName().equals("android.jobscheduler.cts.jobtestapp")) {
2180 Slog.v(TAG, " NOT READY: " + job);
2181 }
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002182 return false;
2183 }
2184
2185 final boolean jobExists = mJobs.containsJob(job);
Kweku Adams8bd5edc2018-12-07 18:33:39 -08002186 final boolean userStarted = areUsersStartedLocked(job);
Christopher Tate18c58702020-03-31 09:40:59 -07002187 final boolean backingUp = mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0;
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002188
2189 if (DEBUG) {
2190 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Christopher Tate18c58702020-03-31 09:40:59 -07002191 + " exists=" + jobExists + " userStarted=" + userStarted
2192 + " backingUp=" + backingUp);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002193 }
2194
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002195 // These are also fairly cheap to check, though they typically will not
2196 // be conditions we fail.
Christopher Tate18c58702020-03-31 09:40:59 -07002197 if (!jobExists || !userStarted || backingUp) {
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002198 return false;
2199 }
2200
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02002201 if (checkIfRestricted(job) != null) {
Wei Wang8c0c3c12018-11-14 14:56:52 -08002202 return false;
2203 }
2204
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002205 final boolean jobPending = mPendingJobs.contains(job);
2206 final boolean jobActive = isCurrentlyActiveLocked(job);
2207
2208 if (DEBUG) {
2209 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2210 + " pending=" + jobPending + " active=" + jobActive);
2211 }
2212
2213 // These can be a little more expensive (especially jobActive, since we need to
2214 // go through the array of all potentially active jobs), so we are doing them
2215 // later... but still before checking with the package manager!
2216 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002217 return false;
2218 }
2219
Christopher Tate8e737852019-03-15 14:56:53 -07002220 // The expensive check: validate that the defined package+service is
Christopher Tatea732f012017-10-26 17:26:53 -07002221 // still present & viable.
Kweku Adams649e2fc2019-03-18 14:55:38 -07002222 return isComponentUsable(job);
2223 }
2224
2225 private boolean isComponentUsable(@NonNull JobStatus job) {
Christopher Tate8e737852019-03-15 14:56:53 -07002226 final ServiceInfo service;
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002227 try {
Kweku Adams649e2fc2019-03-18 14:55:38 -07002228 // TODO: cache result until we're notified that something in the package changed.
Christopher Tate8e737852019-03-15 14:56:53 -07002229 service = AppGlobals.getPackageManager().getServiceInfo(
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002230 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
Christopher Tate8e737852019-03-15 14:56:53 -07002231 job.getUserId());
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002232 } catch (RemoteException e) {
Makoto Onuki0e1ce972019-10-09 12:51:55 -07002233 throw new RuntimeException(e);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002234 }
2235
Christopher Tate8e737852019-03-15 14:56:53 -07002236 if (service == null) {
2237 if (DEBUG) {
Kweku Adams649e2fc2019-03-18 14:55:38 -07002238 Slog.v(TAG, "isComponentUsable: " + job.toShortString()
Christopher Tate8e737852019-03-15 14:56:53 -07002239 + " component not present");
2240 }
2241 return false;
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002242 }
2243
2244 // Everything else checked out so far, so this is the final yes/no check
Christopher Tate8e737852019-03-15 14:56:53 -07002245 final boolean appIsBad = mActivityManagerInternal.isAppBad(service.applicationInfo);
Kweku Adams649e2fc2019-03-18 14:55:38 -07002246 if (DEBUG && appIsBad) {
2247 Slog.i(TAG, "App is bad for " + job.toShortString() + " so not runnable");
Christopher Tate8e737852019-03-15 14:56:53 -07002248 }
2249 return !appIsBad;
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002250 }
2251
Kweku Adams41cb3322019-06-26 14:42:26 -07002252 @VisibleForTesting
2253 void evaluateControllerStatesLocked(final JobStatus job) {
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002254 for (int c = mControllers.size() - 1; c >= 0; --c) {
2255 final StateController sc = mControllers.get(c);
2256 sc.evaluateStateLocked(job);
2257 }
2258 }
2259
2260 /**
2261 * Returns true if non-job constraint components are in place -- if job.isReady() returns true
2262 * and this method returns true, then the job is ready to be executed.
2263 */
2264 public boolean areComponentsInPlaceLocked(JobStatus job) {
2265 // This code is very similar to the code in isReadyToBeExecutedLocked --- it uses the same
2266 // conditions.
2267
2268 final boolean jobExists = mJobs.containsJob(job);
2269 final boolean userStarted = areUsersStartedLocked(job);
Christopher Tate18c58702020-03-31 09:40:59 -07002270 final boolean backingUp = mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0;
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002271
2272 if (DEBUG) {
2273 Slog.v(TAG, "areComponentsInPlaceLocked: " + job.toShortString()
Christopher Tate18c58702020-03-31 09:40:59 -07002274 + " exists=" + jobExists + " userStarted=" + userStarted
2275 + " backingUp=" + backingUp);
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002276 }
2277
2278 // These are also fairly cheap to check, though they typically will not
2279 // be conditions we fail.
Christopher Tate18c58702020-03-31 09:40:59 -07002280 if (!jobExists || !userStarted || backingUp) {
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002281 return false;
2282 }
2283
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02002284 if (checkIfRestricted(job) != null) {
Kweku Adams649e2fc2019-03-18 14:55:38 -07002285 return false;
2286 }
2287
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002288 // Job pending/active doesn't affect the readiness of a job.
2289
Kweku Adams649e2fc2019-03-18 14:55:38 -07002290 // The expensive check: validate that the defined package+service is
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002291 // still present & viable.
Kweku Adams649e2fc2019-03-18 14:55:38 -07002292 return isComponentUsable(job);
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002293 }
2294
Kweku Adamsb4b8b9c2019-06-13 18:37:51 -07002295 /** Returns the maximum amount of time this job could run for. */
2296 public long getMaxJobExecutionTimeMs(JobStatus job) {
2297 synchronized (mLock) {
Kweku Adamsb4b8b9c2019-06-13 18:37:51 -07002298 return Math.min(mQuotaController.getMaxJobExecutionTimeMsLocked(job),
2299 JobServiceContext.EXECUTING_TIMESLICE_MILLIS);
2300 }
2301 }
2302
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002303 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002304 * Reconcile jobs in the pending queue against available execution contexts.
2305 * A controller can force a job into the pending queue even if it's already running, but
2306 * here is where we decide whether to actually execute it.
2307 */
Makoto Onukic279f2b2019-01-09 13:11:37 -08002308 void maybeRunPendingJobsLocked() {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002309 if (DEBUG) {
2310 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
2311 }
Makoto Onuki714f97d2018-12-05 11:18:13 -08002312 mConcurrencyManager.assignJobsToContextsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002313 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07002314 }
2315
Dianne Hackborn807de782016-04-07 17:54:41 -07002316 private int adjustJobPriority(int curPriority, JobStatus job) {
2317 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
2318 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002319 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002320 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002321 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002322 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
2323 }
2324 }
2325 return curPriority;
2326 }
2327
Makoto Onuki714f97d2018-12-05 11:18:13 -08002328 int evaluateJobPriorityLocked(JobStatus job) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002329 int priority = job.getPriority();
Makoto Onukiec8b14d2018-12-05 13:22:24 -08002330 if (priority >= JobInfo.PRIORITY_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002331 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002332 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002333 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
2334 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002335 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002336 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002337 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002338 }
2339
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002340 final class LocalService implements JobSchedulerInternal {
2341
2342 /**
2343 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2344 * jobs are always considered pending.
2345 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002346 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002347 public List<JobInfo> getSystemScheduledPendingJobs() {
2348 synchronized (mLock) {
2349 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002350 mJobs.forEachJob(Process.SYSTEM_UID, (job) -> {
2351 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2352 pendingJobs.add(job.getJob());
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002353 }
2354 });
2355 return pendingJobs;
2356 }
2357 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002358
2359 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002360 public void cancelJobsForUid(int uid, String reason) {
2361 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2362 }
2363
2364 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002365 public void addBackingUpUid(int uid) {
2366 synchronized (mLock) {
2367 // No need to actually do anything here, since for a full backup the
2368 // activity manager will kill the process which will kill the job (and
2369 // cause it to restart, but now it can't run).
2370 mBackingUpUids.put(uid, uid);
2371 }
2372 }
2373
2374 @Override
2375 public void removeBackingUpUid(int uid) {
2376 synchronized (mLock) {
2377 mBackingUpUids.delete(uid);
2378 // If there are any jobs for this uid, we need to rebuild the pending list
2379 // in case they are now ready to run.
2380 if (mJobs.countJobsForUid(uid) > 0) {
2381 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2382 }
2383 }
2384 }
2385
2386 @Override
2387 public void clearAllBackingUpUids() {
2388 synchronized (mLock) {
2389 if (mBackingUpUids.size() > 0) {
2390 mBackingUpUids.clear();
2391 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2392 }
2393 }
2394 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002395
2396 @Override
Suprabh Shukla08126472020-02-04 20:46:35 -08002397 public String getMediaBackupPackage() {
2398 return mSystemGalleryPackage;
2399 }
2400
2401 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002402 public void reportAppUsage(String packageName, int userId) {
2403 JobSchedulerService.this.reportAppUsage(packageName, userId);
2404 }
2405
2406 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002407 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002408 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002409 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002410 }
2411 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002412 }
2413
Shreyas Basarge5db09082016-01-07 13:38:29 +00002414 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002415 * Tracking of app assignments to standby buckets
2416 */
2417 final class StandbyTracker extends AppIdleStateChangeListener {
Christopher Tate435c2f42018-01-18 12:59:15 -08002418
Christopher Tatea732f012017-10-26 17:26:53 -07002419 // AppIdleStateChangeListener interface for live updates
2420
2421 @Override
Christopher Tate435c2f42018-01-18 12:59:15 -08002422 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08002423 boolean idle, int bucket, int reason) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002424 // QuotaController handles this now.
Christopher Tatea732f012017-10-26 17:26:53 -07002425 }
2426
2427 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002428 public void onUserInteractionStarted(String packageName, int userId) {
2429 final int uid = mLocalPM.getPackageUid(packageName,
2430 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2431 if (uid < 0) {
2432 // Quietly ignore; the case is already logged elsewhere
2433 return;
2434 }
2435
Amith Yamasani977e11f2018-02-16 11:29:54 -08002436 long sinceLast = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2437 if (sinceLast > 2 * DateUtils.DAY_IN_MILLIS) {
2438 // Too long ago, not worth logging
2439 sinceLast = 0L;
2440 }
Christopher Tated117b292018-01-05 17:32:36 -08002441 final DeferredJobCounter counter = new DeferredJobCounter();
2442 synchronized (mLock) {
2443 mJobs.forEachJobForSourceUid(uid, counter);
2444 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08002445 if (counter.numDeferred() > 0 || sinceLast > 0) {
2446 BatteryStatsInternal mBatteryStatsInternal = LocalServices.getService
2447 (BatteryStatsInternal.class);
2448 mBatteryStatsInternal.noteJobsDeferred(uid, counter.numDeferred(), sinceLast);
Muhammad Qureshie9aec322020-01-28 10:27:18 -08002449 FrameworkStatsLog.write_non_chained(
2450 FrameworkStatsLog.DEFERRED_JOB_STATS_REPORTED, uid, null,
Yangster-mac96353002018-09-05 11:18:55 -07002451 counter.numDeferred(), sinceLast);
Amith Yamasani977e11f2018-02-16 11:29:54 -08002452 }
Christopher Tated117b292018-01-05 17:32:36 -08002453 }
2454 }
2455
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002456 static class DeferredJobCounter implements Consumer<JobStatus> {
Christopher Tated117b292018-01-05 17:32:36 -08002457 private int mDeferred = 0;
2458
2459 public int numDeferred() {
2460 return mDeferred;
2461 }
2462
2463 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002464 public void accept(JobStatus job) {
Christopher Tated117b292018-01-05 17:32:36 -08002465 if (job.getWhenStandbyDeferred() > 0) {
2466 mDeferred++;
2467 }
2468 }
Christopher Tatea732f012017-10-26 17:26:53 -07002469 }
2470
2471 public static int standbyBucketToBucketIndex(int bucket) {
2472 // Normalize AppStandby constants to indices into our bookkeeping
Kweku Adamsae9d6be2020-01-14 16:10:14 -08002473 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) {
2474 return NEVER_INDEX;
2475 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_RARE) {
2476 return RESTRICTED_INDEX;
2477 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
2478 return RARE_INDEX;
2479 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
2480 return FREQUENT_INDEX;
2481 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) {
2482 return WORKING_INDEX;
2483 } else {
2484 return ACTIVE_INDEX;
2485 }
Christopher Tatea732f012017-10-26 17:26:53 -07002486 }
2487
Christopher Tated1aebb32018-01-31 13:24:14 -08002488 // Static to support external callers
Christopher Tatea732f012017-10-26 17:26:53 -07002489 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2490 UsageStatsManagerInternal usageStats = LocalServices.getService(
2491 UsageStatsManagerInternal.class);
2492 int bucket = usageStats != null
2493 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2494 : 0;
2495
2496 bucket = standbyBucketToBucketIndex(bucket);
2497
2498 if (DEBUG_STANDBY) {
2499 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2500 }
2501 return bucket;
2502 }
2503
2504 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002505 * Binder stub trampoline implementation
2506 */
2507 final class JobSchedulerStub extends IJobScheduler.Stub {
2508 /** Cache determination of whether a given app can persist jobs
2509 * key is uid of the calling app; value is undetermined/true/false
2510 */
2511 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2512
2513 // Enforce that only the app itself (or shared uid participant) can schedule a
2514 // job that runs one of the app's services, as well as verifying that the
2515 // named service properly requires the BIND_JOB_SERVICE permission
2516 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002517 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002518 final ComponentName service = job.getService();
2519 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002520 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002521 PackageManager.MATCH_DIRECT_BOOT_AWARE
2522 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002523 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002524 if (si == null) {
2525 throw new IllegalArgumentException("No such service " + service);
2526 }
Christopher Tate7060b042014-06-09 19:50:00 -07002527 if (si.applicationInfo.uid != uid) {
2528 throw new IllegalArgumentException("uid " + uid +
2529 " cannot schedule job in " + service.getPackageName());
2530 }
2531 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2532 throw new IllegalArgumentException("Scheduled service " + service
2533 + " does not require android.permission.BIND_JOB_SERVICE permission");
2534 }
Christopher Tate5568f542014-06-18 13:53:31 -07002535 } catch (RemoteException e) {
2536 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002537 }
2538 }
2539
2540 private boolean canPersistJobs(int pid, int uid) {
2541 // If we get this far we're good to go; all we need to do now is check
2542 // whether the app is allowed to persist its scheduled work.
2543 final boolean canPersist;
2544 synchronized (mPersistCache) {
2545 Boolean cached = mPersistCache.get(uid);
2546 if (cached != null) {
2547 canPersist = cached.booleanValue();
2548 } else {
2549 // Persisting jobs is tantamount to running at boot, so we permit
2550 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2551 // permission
2552 int result = getContext().checkPermission(
2553 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2554 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2555 mPersistCache.put(uid, canPersist);
2556 }
2557 }
2558 return canPersist;
2559 }
2560
Makoto Onuki959acb52018-01-26 14:10:03 -08002561 private void validateJobFlags(JobInfo job, int callingUid) {
2562 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2563 getContext().enforceCallingOrSelfPermission(
2564 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2565 }
2566 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
2567 if (callingUid != Process.SYSTEM_UID) {
2568 throw new SecurityException("Job has invalid flags");
2569 }
Makoto Onuki2b5811a2018-02-08 11:09:42 -08002570 if (job.isPeriodic()) {
2571 Slog.wtf(TAG, "Periodic jobs mustn't have"
2572 + " FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
Makoto Onuki959acb52018-01-26 14:10:03 -08002573 }
2574 }
2575 }
2576
Christopher Tate7060b042014-06-09 19:50:00 -07002577 // IJobScheduler implementation
2578 @Override
2579 public int schedule(JobInfo job) throws RemoteException {
2580 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002581 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002582 }
2583 final int pid = Binder.getCallingPid();
2584 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002585 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002586
2587 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002588 if (job.isPersisted()) {
2589 if (!canPersistJobs(pid, uid)) {
2590 throw new IllegalArgumentException("Error: requested job be persisted without"
2591 + " holding RECEIVE_BOOT_COMPLETED permission.");
2592 }
2593 }
Christopher Tate7060b042014-06-09 19:50:00 -07002594
Makoto Onuki959acb52018-01-26 14:10:03 -08002595 validateJobFlags(job, uid);
Jeff Sharkey785f4942016-07-14 10:31:15 -06002596
Christopher Tate7060b042014-06-09 19:50:00 -07002597 long ident = Binder.clearCallingIdentity();
2598 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002599 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2600 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002601 } finally {
2602 Binder.restoreCallingIdentity(ident);
2603 }
2604 }
2605
2606 // IJobScheduler implementation
2607 @Override
2608 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2609 if (DEBUG) {
2610 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2611 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002612 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002613 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002614
2615 enforceValidJobRequest(uid, job);
2616 if (job.isPersisted()) {
2617 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2618 }
2619 if (work == null) {
2620 throw new NullPointerException("work is null");
2621 }
2622
Makoto Onuki959acb52018-01-26 14:10:03 -08002623 validateJobFlags(job, uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002624
2625 long ident = Binder.clearCallingIdentity();
2626 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002627 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2628 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002629 } finally {
2630 Binder.restoreCallingIdentity(ident);
2631 }
2632 }
2633
2634 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002635 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002636 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002637 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002638 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002639 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002640 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002641 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002642
2643 if (packageName == null) {
2644 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002645 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002646
2647 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2648 android.Manifest.permission.UPDATE_DEVICE_STATS);
2649 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2650 throw new SecurityException("Caller uid " + callerUid
2651 + " not permitted to schedule jobs for other apps");
2652 }
2653
Makoto Onuki959acb52018-01-26 14:10:03 -08002654 validateJobFlags(job, callerUid);
Jeff Sharkey4f100402016-05-03 17:44:23 -06002655
Shreyas Basarge968ac752016-01-11 23:09:26 +00002656 long ident = Binder.clearCallingIdentity();
2657 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002658 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002659 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002660 } finally {
2661 Binder.restoreCallingIdentity(ident);
2662 }
2663 }
2664
2665 @Override
Kweku Adamsd1f4b902019-05-07 12:22:47 -07002666 public ParceledListSlice<JobInfo> getAllPendingJobs() throws RemoteException {
Christopher Tate7060b042014-06-09 19:50:00 -07002667 final int uid = Binder.getCallingUid();
2668
2669 long ident = Binder.clearCallingIdentity();
2670 try {
Kweku Adamsd1f4b902019-05-07 12:22:47 -07002671 return new ParceledListSlice<>(JobSchedulerService.this.getPendingJobs(uid));
Christopher Tate7060b042014-06-09 19:50:00 -07002672 } finally {
2673 Binder.restoreCallingIdentity(ident);
2674 }
2675 }
2676
2677 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002678 public JobInfo getPendingJob(int jobId) throws RemoteException {
2679 final int uid = Binder.getCallingUid();
2680
2681 long ident = Binder.clearCallingIdentity();
2682 try {
2683 return JobSchedulerService.this.getPendingJob(uid, jobId);
2684 } finally {
2685 Binder.restoreCallingIdentity(ident);
2686 }
2687 }
2688
2689 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002690 public void cancelAll() throws RemoteException {
2691 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002692 long ident = Binder.clearCallingIdentity();
2693 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002694 JobSchedulerService.this.cancelJobsForUid(uid,
2695 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002696 } finally {
2697 Binder.restoreCallingIdentity(ident);
2698 }
2699 }
2700
2701 @Override
2702 public void cancel(int jobId) throws RemoteException {
2703 final int uid = Binder.getCallingUid();
2704
2705 long ident = Binder.clearCallingIdentity();
2706 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002707 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002708 } finally {
2709 Binder.restoreCallingIdentity(ident);
2710 }
2711 }
2712
2713 /**
2714 * "dumpsys" infrastructure
2715 */
2716 @Override
2717 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002718 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002719
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002720 int filterUid = -1;
2721 boolean proto = false;
2722 if (!ArrayUtils.isEmpty(args)) {
2723 int opti = 0;
2724 while (opti < args.length) {
2725 String arg = args[opti];
2726 if ("-h".equals(arg)) {
2727 dumpHelp(pw);
2728 return;
2729 } else if ("-a".equals(arg)) {
2730 // Ignore, we always dump all.
2731 } else if ("--proto".equals(arg)) {
2732 proto = true;
2733 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2734 pw.println("Unknown option: " + arg);
2735 return;
2736 } else {
2737 break;
2738 }
2739 opti++;
2740 }
2741 if (opti < args.length) {
2742 String pkg = args[opti];
2743 try {
2744 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2745 PackageManager.MATCH_ANY_USER);
2746 } catch (NameNotFoundException ignored) {
2747 pw.println("Invalid package: " + pkg);
2748 return;
2749 }
2750 }
2751 }
2752
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002753 final long identityToken = Binder.clearCallingIdentity();
Christopher Tate7060b042014-06-09 19:50:00 -07002754 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002755 if (proto) {
2756 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2757 } else {
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002758 JobSchedulerService.this.dumpInternal(new IndentingPrintWriter(pw, " "),
2759 filterUid);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002760 }
Christopher Tate7060b042014-06-09 19:50:00 -07002761 } finally {
2762 Binder.restoreCallingIdentity(identityToken);
2763 }
2764 }
Christopher Tate5d346052016-03-08 12:56:08 -08002765
2766 @Override
Makoto Onukif8f55022019-12-02 15:07:00 -08002767 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
Makoto Onukib8472182019-11-13 12:03:22 -08002768 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
2769 @NonNull String[] args) {
Makoto Onuki4c7073b2019-11-04 10:37:15 -08002770 return (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Makoto Onukib8472182019-11-13 12:03:22 -08002771 this, in.getFileDescriptor(), out.getFileDescriptor(), err.getFileDescriptor(),
2772 args);
Christopher Tate5d346052016-03-08 12:56:08 -08002773 }
Serik Beketayev75915d12018-08-01 16:56:59 -07002774
2775 /**
2776 * <b>For internal system user only!</b>
2777 * Returns a list of all currently-executing jobs.
2778 */
2779 @Override
2780 public List<JobInfo> getStartedJobs() {
2781 final int uid = Binder.getCallingUid();
2782 if (uid != Process.SYSTEM_UID) {
2783 throw new SecurityException(
2784 "getStartedJobs() is system internal use only.");
2785 }
2786
2787 final ArrayList<JobInfo> runningJobs;
2788
2789 synchronized (mLock) {
2790 runningJobs = new ArrayList<>(mActiveServices.size());
2791 for (JobServiceContext jsc : mActiveServices) {
2792 final JobStatus job = jsc.getRunningJobLocked();
2793 if (job != null) {
2794 runningJobs.add(job.getJob());
2795 }
2796 }
2797 }
2798
2799 return runningJobs;
2800 }
2801
2802 /**
2803 * <b>For internal system user only!</b>
2804 * Returns a snapshot of the state of all jobs known to the system.
2805 *
2806 * <p class="note">This is a slow operation, so it should be called sparingly.
2807 */
2808 @Override
Kweku Adamsd1f4b902019-05-07 12:22:47 -07002809 public ParceledListSlice<JobSnapshot> getAllJobSnapshots() {
Serik Beketayev75915d12018-08-01 16:56:59 -07002810 final int uid = Binder.getCallingUid();
2811 if (uid != Process.SYSTEM_UID) {
2812 throw new SecurityException(
2813 "getAllJobSnapshots() is system internal use only.");
2814 }
2815 synchronized (mLock) {
2816 final ArrayList<JobSnapshot> snapshots = new ArrayList<>(mJobs.size());
2817 mJobs.forEachJob((job) -> snapshots.add(
2818 new JobSnapshot(job.getJob(), job.getSatisfiedConstraintFlags(),
2819 isReadyToBeExecutedLocked(job))));
Kweku Adamsd1f4b902019-05-07 12:22:47 -07002820 return new ParceledListSlice<>(snapshots);
Serik Beketayev75915d12018-08-01 16:56:59 -07002821 }
2822 }
Kweku Adams9239a1a2019-11-12 12:06:37 -08002823 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002824
Christopher Tate5d346052016-03-08 12:56:08 -08002825 // Shell command infrastructure: run the given job immediately
Kweku Adamscdc2c992020-03-13 13:24:53 -07002826 int executeRunCommand(String pkgName, int userId, int jobId, boolean satisfied, boolean force) {
2827 Slog.d(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2828 + " " + jobId + " s=" + satisfied + " f=" + force);
Christopher Tate5d346052016-03-08 12:56:08 -08002829
2830 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002831 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2832 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002833 if (uid < 0) {
2834 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2835 }
2836
2837 synchronized (mLock) {
2838 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2839 if (js == null) {
2840 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2841 }
2842
Kweku Adamscdc2c992020-03-13 13:24:53 -07002843 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL
2844 : (satisfied ? JobStatus.OVERRIDE_SORTING : JobStatus.OVERRIDE_SOFT);
Kweku Adams7820b0d2020-03-02 15:28:36 -08002845
2846 // Re-evaluate constraints after the override is set in case one of the overridden
2847 // constraints was preventing another constraint from thinking it needed to update.
2848 for (int c = mControllers.size() - 1; c >= 0; --c) {
2849 mControllers.get(c).reevaluateStateLocked(uid);
2850 }
2851
Christopher Tate5d346052016-03-08 12:56:08 -08002852 if (!js.isConstraintsSatisfied()) {
Kweku Adamscdc2c992020-03-13 13:24:53 -07002853 js.overrideState = JobStatus.OVERRIDE_NONE;
Christopher Tate5d346052016-03-08 12:56:08 -08002854 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2855 }
2856
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002857 queueReadyJobsForExecutionLocked();
2858 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002859 }
2860 } catch (RemoteException e) {
2861 // can't happen
2862 }
2863 return 0;
2864 }
2865
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002866 // Shell command infrastructure: immediately timeout currently executing jobs
2867 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2868 boolean hasJobId, int jobId) {
2869 if (DEBUG) {
2870 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2871 }
2872
2873 synchronized (mLock) {
2874 boolean foundSome = false;
2875 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002876 final JobServiceContext jc = mActiveServices.get(i);
2877 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002878 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002879 foundSome = true;
2880 pw.print("Timing out: ");
2881 js.printUniqueId(pw);
2882 pw.print(" ");
2883 pw.println(js.getServiceComponent().flattenToShortString());
2884 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002885 }
2886 if (!foundSome) {
2887 pw.println("No matching executing jobs found.");
2888 }
2889 }
2890 return 0;
2891 }
2892
Christopher Tate8c67d122017-09-29 16:54:26 -07002893 // Shell command infrastructure: cancel a scheduled job
2894 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2895 boolean hasJobId, int jobId) {
2896 if (DEBUG) {
2897 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2898 }
2899
2900 int pkgUid = -1;
2901 try {
2902 IPackageManager pm = AppGlobals.getPackageManager();
2903 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2904 } catch (RemoteException e) { /* can't happen */ }
2905
2906 if (pkgUid < 0) {
2907 pw.println("Package " + pkgName + " not found.");
2908 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2909 }
2910
2911 if (!hasJobId) {
2912 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2913 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2914 pw.println("No matching jobs found.");
2915 }
2916 } else {
2917 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002918 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002919 pw.println("No matching job found.");
2920 }
2921 }
2922
2923 return 0;
2924 }
2925
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002926 void setMonitorBattery(boolean enabled) {
2927 synchronized (mLock) {
2928 if (mBatteryController != null) {
2929 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2930 }
2931 }
2932 }
2933
2934 int getBatterySeq() {
2935 synchronized (mLock) {
2936 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2937 }
2938 }
2939
2940 boolean getBatteryCharging() {
2941 synchronized (mLock) {
2942 return mBatteryController != null
2943 ? mBatteryController.getTracker().isOnStablePower() : false;
2944 }
2945 }
2946
2947 boolean getBatteryNotLow() {
2948 synchronized (mLock) {
2949 return mBatteryController != null
2950 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2951 }
2952 }
2953
Dianne Hackborn532ea262017-03-17 17:50:55 -07002954 int getStorageSeq() {
2955 synchronized (mLock) {
2956 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2957 }
2958 }
2959
2960 boolean getStorageNotLow() {
2961 synchronized (mLock) {
2962 return mStorageController != null
2963 ? mStorageController.getTracker().isStorageNotLow() : false;
2964 }
2965 }
2966
Christopher Tated1aebb32018-01-31 13:24:14 -08002967 // Shell command infrastructure
Dianne Hackborn6d068262017-05-16 13:14:37 -07002968 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2969 try {
2970 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2971 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2972 if (uid < 0) {
2973 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2974 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2975 }
2976
2977 synchronized (mLock) {
2978 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2979 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2980 if (js == null) {
2981 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2982 pw.print("/jid"); pw.print(jobId); pw.println(")");
2983 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2984 }
2985
2986 boolean printed = false;
2987 if (mPendingJobs.contains(js)) {
2988 pw.print("pending");
2989 printed = true;
2990 }
2991 if (isCurrentlyActiveLocked(js)) {
2992 if (printed) {
2993 pw.print(" ");
2994 }
2995 printed = true;
2996 pw.println("active");
2997 }
2998 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2999 if (printed) {
3000 pw.print(" ");
3001 }
3002 printed = true;
3003 pw.println("user-stopped");
3004 }
Kweku Adams8bd5edc2018-12-07 18:33:39 -08003005 if (!ArrayUtils.contains(mStartedUsers, js.getSourceUserId())) {
3006 if (printed) {
3007 pw.print(" ");
3008 }
3009 printed = true;
3010 pw.println("source-user-stopped");
3011 }
Dianne Hackborn6d068262017-05-16 13:14:37 -07003012 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
3013 if (printed) {
3014 pw.print(" ");
3015 }
3016 printed = true;
3017 pw.println("backing-up");
3018 }
3019 boolean componentPresent = false;
3020 try {
3021 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3022 js.getServiceComponent(),
3023 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3024 js.getUserId()) != null);
3025 } catch (RemoteException e) {
3026 }
3027 if (!componentPresent) {
3028 if (printed) {
3029 pw.print(" ");
3030 }
3031 printed = true;
3032 pw.println("no-component");
3033 }
3034 if (js.isReady()) {
3035 if (printed) {
3036 pw.print(" ");
3037 }
3038 printed = true;
3039 pw.println("ready");
3040 }
3041 if (!printed) {
3042 pw.print("waiting");
3043 }
3044 pw.println();
3045 }
3046 } catch (RemoteException e) {
3047 // can't happen
3048 }
3049 return 0;
3050 }
3051
Kweku Adams87a4cd52020-02-24 17:20:04 -08003052 void resetExecutionQuota(@NonNull String pkgName, int userId) {
Kweku Adams35d05ac2020-02-25 16:44:06 -08003053 mQuotaController.clearAppStats(userId, pkgName);
Kweku Adams87a4cd52020-02-24 17:20:04 -08003054 }
3055
Kweku Adams9239a1a2019-11-12 12:06:37 -08003056 void resetScheduleQuota() {
3057 mQuotaTracker.clear();
3058 }
3059
lpeter318abc92018-05-04 16:13:14 +08003060 void triggerDockState(boolean idleState) {
3061 final Intent dockIntent;
3062 if (idleState) {
3063 dockIntent = new Intent(Intent.ACTION_DOCK_IDLE);
3064 } else {
3065 dockIntent = new Intent(Intent.ACTION_DOCK_ACTIVE);
3066 }
3067 dockIntent.setPackage("android");
3068 dockIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
3069 getContext().sendBroadcastAsUser(dockIntent, UserHandle.ALL);
3070 }
3071
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003072 static void dumpHelp(PrintWriter pw) {
3073 pw.println("Job Scheduler (jobscheduler) dump options:");
3074 pw.println(" [-h] [package] ...");
3075 pw.println(" -h: print this help");
3076 pw.println(" [package] is an optional package name to limit the output to.");
3077 }
3078
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003079 /** Sort jobs by caller UID, then by Job ID. */
3080 private static void sortJobs(List<JobStatus> jobs) {
3081 Collections.sort(jobs, new Comparator<JobStatus>() {
3082 @Override
3083 public int compare(JobStatus o1, JobStatus o2) {
3084 int uid1 = o1.getUid();
3085 int uid2 = o2.getUid();
3086 int id1 = o1.getJobId();
3087 int id2 = o2.getJobId();
3088 if (uid1 != uid2) {
3089 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003090 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003091 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003092 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003093 });
3094 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06003095
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003096 void dumpInternal(final IndentingPrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003097 final int filterUidFinal = UserHandle.getAppId(filterUid);
Makoto Onukif731c422019-01-22 13:23:31 -08003098 final long now = sSystemClock.millis();
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07003099 final long nowElapsed = sElapsedRealtimeClock.millis();
3100 final long nowUptime = sUptimeMillisClock.millis();
Makoto Onukif731c422019-01-22 13:23:31 -08003101
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003102 final Predicate<JobStatus> predicate = (js) -> {
3103 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3104 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3105 };
Dianne Hackborn33d31c52016-02-16 10:30:33 -08003106 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003107 mConstants.dump(pw);
Kweku Adams4e774a32019-04-24 18:01:29 -07003108 for (StateController controller : mControllers) {
3109 pw.increaseIndent();
3110 controller.dumpConstants(pw);
3111 pw.decreaseIndent();
3112 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003113 pw.println();
Makoto Onukib5d5e972018-02-20 14:44:20 -08003114
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02003115 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
3116 pw.print(" ");
3117 mJobRestrictions.get(i).dumpConstants(pw);
3118 pw.println();
3119 }
Makoto Onukib5d5e972018-02-20 14:44:20 -08003120 pw.println();
3121
Kweku Adams9239a1a2019-11-12 12:06:37 -08003122 mQuotaTracker.dump(pw);
3123 pw.println();
3124
Jeff Sharkey822cbd12016-02-25 11:09:55 -07003125 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003126 pw.print("Registered ");
3127 pw.print(mJobs.size());
3128 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07003129 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003130 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003131 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003132 for (JobStatus job : jobs) {
3133 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
3134 pw.println(job.toShortStringExceptUniqueId());
3135
3136 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003137 if (!predicate.test(job)) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003138 continue;
3139 }
3140
Dianne Hackborn6d068262017-05-16 13:14:37 -07003141 job.dump(pw, " ", true, nowElapsed);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003142
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02003143
3144 pw.print(" Restricted due to:");
3145 final boolean isRestricted = checkIfRestricted(job) != null;
3146 if (isRestricted) {
3147 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
3148 final JobRestriction restriction = mJobRestrictions.get(i);
3149 if (restriction.isJobRestricted(job)) {
3150 final int reason = restriction.getReason();
Kweku Adams13289702020-02-19 17:28:55 -08003151 pw.print(" " + JobParameters.getReasonCodeDescription(reason));
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02003152 }
3153 }
3154 } else {
3155 pw.print(" none");
3156 }
3157 pw.println(".");
3158
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003159 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003160 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003161 pw.print(" (job=");
3162 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003163 pw.print(" user=");
Kweku Adams8bd5edc2018-12-07 18:33:39 -08003164 pw.print(areUsersStartedLocked(job));
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02003165 pw.print(" !restricted=");
3166 pw.print(!isRestricted);
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003167 pw.print(" !pending=");
3168 pw.print(!mPendingJobs.contains(job));
3169 pw.print(" !active=");
3170 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003171 pw.print(" !backingup=");
3172 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003173 pw.print(" comp=");
Kweku Adamsc3f9ba62019-08-01 12:14:55 -07003174 pw.print(isComponentUsable(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003175 pw.println(")");
3176 }
Christopher Tate7060b042014-06-09 19:50:00 -07003177 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07003178 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07003179 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003180 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07003181 pw.println();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003182 pw.println(mControllers.get(i).getClass().getSimpleName() + ":");
3183 pw.increaseIndent();
3184 mControllers.get(i).dumpControllerStateLocked(pw, predicate);
3185 pw.decreaseIndent();
Christopher Tate7060b042014-06-09 19:50:00 -07003186 }
3187 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08003188 pw.println("Uid priority overrides:");
3189 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003190 int uid = mUidPriorityOverride.keyAt(i);
3191 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3192 pw.print(" "); pw.print(UserHandle.formatUid(uid));
3193 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
3194 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003195 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003196 if (mBackingUpUids.size() > 0) {
3197 pw.println();
3198 pw.println("Backing up uids:");
3199 boolean first = true;
3200 for (int i = 0; i < mBackingUpUids.size(); i++) {
3201 int uid = mBackingUpUids.keyAt(i);
3202 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3203 if (first) {
3204 pw.print(" ");
3205 first = false;
3206 } else {
3207 pw.print(", ");
3208 }
3209 pw.print(UserHandle.formatUid(uid));
3210 }
3211 }
3212 pw.println();
3213 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003214 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003215 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07003216 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003217 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
3218 pw.println();
3219 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003220 pw.println("Pending queue:");
3221 for (int i=0; i<mPendingJobs.size(); i++) {
3222 JobStatus job = mPendingJobs.get(i);
3223 pw.print(" Pending #"); pw.print(i); pw.print(": ");
3224 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07003225 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003226 int priority = evaluateJobPriorityLocked(job);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003227 pw.print(" Evaluated priority: ");
3228 pw.println(JobInfo.getPriorityString(priority));
3229
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003230 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07003231 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003232 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003233 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003234 }
Christopher Tate7060b042014-06-09 19:50:00 -07003235 pw.println();
3236 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003237 for (int i=0; i<mActiveServices.size(); i++) {
3238 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003239 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003240 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07003241 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07003242 if (jsc.mStoppedReason != null) {
3243 pw.print("inactive since ");
3244 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
3245 pw.print(", stopped because: ");
3246 pw.println(jsc.mStoppedReason);
3247 } else {
3248 pw.println("inactive");
3249 }
Christopher Tate7060b042014-06-09 19:50:00 -07003250 continue;
3251 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07003252 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08003253 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003254 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003255 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003256 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003257 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07003258 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003259 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003260 pw.print(" Evaluated priority: ");
3261 pw.println(JobInfo.getPriorityString(priority));
3262
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003263 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003264 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003265 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07003266 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
3267 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07003268 }
3269 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003270 if (filterUid == -1) {
3271 pw.println();
3272 pw.print("mReadyToRock="); pw.println(mReadyToRock);
3273 pw.print("mReportedActive="); pw.println(mReportedActive);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003274 }
Makoto Onukie7b02982017-08-24 14:23:36 -07003275 pw.println();
Makoto Onukic279f2b2019-01-09 13:11:37 -08003276
Makoto Onukif731c422019-01-22 13:23:31 -08003277 mConcurrencyManager.dumpLocked(pw, now, nowElapsed);
Makoto Onukic279f2b2019-01-09 13:11:37 -08003278
3279 pw.println();
Makoto Onukie7b02982017-08-24 14:23:36 -07003280 pw.print("PersistStats: ");
3281 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07003282 }
3283 pw.println();
3284 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003285
3286 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
3287 ProtoOutputStream proto = new ProtoOutputStream(fd);
3288 final int filterUidFinal = UserHandle.getAppId(filterUid);
Makoto Onukif731c422019-01-22 13:23:31 -08003289 final long now = sSystemClock.millis();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003290 final long nowElapsed = sElapsedRealtimeClock.millis();
3291 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003292 final Predicate<JobStatus> predicate = (js) -> {
3293 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3294 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3295 };
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003296
3297 synchronized (mLock) {
Kweku Adams4e774a32019-04-24 18:01:29 -07003298 final long settingsToken = proto.start(JobSchedulerServiceDumpProto.SETTINGS);
3299 mConstants.dump(proto);
3300 for (StateController controller : mControllers) {
3301 controller.dumpConstants(proto);
3302 }
3303 proto.end(settingsToken);
3304
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02003305 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
3306 mJobRestrictions.get(i).dumpConstants(proto);
3307 }
Makoto Onukib5d5e972018-02-20 14:44:20 -08003308
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003309 for (int u : mStartedUsers) {
3310 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
3311 }
Kweku Adams9239a1a2019-11-12 12:06:37 -08003312
3313 mQuotaTracker.dump(proto, JobSchedulerServiceDumpProto.QUOTA_TRACKER);
3314
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003315 if (mJobs.size() > 0) {
3316 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
3317 sortJobs(jobs);
3318 for (JobStatus job : jobs) {
3319 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
3320 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
3321
3322 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003323 if (!predicate.test(job)) {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003324 continue;
3325 }
3326
3327 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
3328
Kweku Adamsc3f9ba62019-08-01 12:14:55 -07003329 proto.write(
3330 JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY_TO_BE_EXECUTED,
3331 isReadyToBeExecutedLocked(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003332 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
3333 job.isReady());
Kweku Adamsc3f9ba62019-08-01 12:14:55 -07003334 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.ARE_USERS_STARTED,
Kweku Adams8bd5edc2018-12-07 18:33:39 -08003335 areUsersStartedLocked(job));
Kweku Adamsc3f9ba62019-08-01 12:14:55 -07003336 proto.write(
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02003337 JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_RESTRICTED,
3338 checkIfRestricted(job) != null);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003339 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
3340 mPendingJobs.contains(job));
3341 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
3342 isCurrentlyActiveLocked(job));
3343 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
3344 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
Kweku Adamsc3f9ba62019-08-01 12:14:55 -07003345 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_USABLE,
3346 isComponentUsable(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003347
Sergey Nikolaienkov2ad8af12019-08-26 13:13:08 +02003348 for (JobRestriction restriction : mJobRestrictions) {
3349 final long restrictionsToken = proto.start(
3350 JobSchedulerServiceDumpProto.RegisteredJob.RESTRICTIONS);
3351 proto.write(JobSchedulerServiceDumpProto.JobRestriction.REASON,
3352 restriction.getReason());
3353 proto.write(JobSchedulerServiceDumpProto.JobRestriction.IS_RESTRICTING,
3354 restriction.isJobRestricted(job));
3355 proto.end(restrictionsToken);
3356 }
3357
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003358 proto.end(rjToken);
3359 }
3360 }
3361 for (StateController controller : mControllers) {
3362 controller.dumpControllerStateLocked(
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003363 proto, JobSchedulerServiceDumpProto.CONTROLLERS, predicate);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003364 }
3365 for (int i=0; i< mUidPriorityOverride.size(); i++) {
3366 int uid = mUidPriorityOverride.keyAt(i);
3367 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3368 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3369 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3370 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3371 mUidPriorityOverride.valueAt(i));
3372 proto.end(pToken);
3373 }
3374 }
3375 for (int i = 0; i < mBackingUpUids.size(); i++) {
3376 int uid = mBackingUpUids.keyAt(i);
3377 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3378 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3379 }
3380 }
3381
3382 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3383 filterUidFinal);
3384 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3385 filterUidFinal);
3386
3387 for (JobStatus job : mPendingJobs) {
3388 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3389
3390 job.writeToShortProto(proto, PendingJob.INFO);
3391 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003392 proto.write(PendingJob.EVALUATED_PRIORITY, evaluateJobPriorityLocked(job));
Kweku Adamsc3f9ba62019-08-01 12:14:55 -07003393 proto.write(PendingJob.PENDING_DURATION_MS, nowUptime - job.madePending);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003394
3395 proto.end(pjToken);
3396 }
3397 for (JobServiceContext jsc : mActiveServices) {
3398 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
3399 final JobStatus job = jsc.getRunningJobLocked();
3400
3401 if (job == null) {
3402 final long ijToken = proto.start(ActiveJob.INACTIVE);
3403
3404 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
3405 nowElapsed - jsc.mStoppedTime);
3406 if (jsc.mStoppedReason != null) {
3407 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
3408 jsc.mStoppedReason);
3409 }
3410
3411 proto.end(ijToken);
3412 } else {
3413 final long rjToken = proto.start(ActiveJob.RUNNING);
3414
3415 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
3416
3417 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
3418 nowElapsed - jsc.getExecutionStartTimeElapsed());
3419 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
3420 jsc.getTimeoutElapsed() - nowElapsed);
3421
3422 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3423
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003424 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY,
3425 evaluateJobPriorityLocked(jsc.getRunningJobLocked()));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003426
3427 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3428 nowUptime - job.madeActive);
3429 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3430 job.madeActive - job.madePending);
3431
3432 proto.end(rjToken);
3433 }
3434 proto.end(ajToken);
3435 }
3436 if (filterUid == -1) {
3437 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3438 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003439 }
Makoto Onukif731c422019-01-22 13:23:31 -08003440 mConcurrencyManager.dumpProtoLocked(proto,
3441 JobSchedulerServiceDumpProto.CONCURRENCY_MANAGER, now, nowElapsed);
Kweku Adamsc3f9ba62019-08-01 12:14:55 -07003442
Jeffrey Huangcb782852019-12-05 11:28:11 -08003443 mJobs.getPersistStats().dumpDebug(proto, JobSchedulerServiceDumpProto.PERSIST_STATS);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003444 }
3445
3446 proto.flush();
3447 }
Christopher Tate7060b042014-06-09 19:50:00 -07003448}