blob: 05c7f1984616d6a3a07b1fc3a16dc62ec6e3391c [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.job;
18
Christopher Tateb5c07882016-05-26 17:11:09 -070019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21
Christopher Tate435c2f42018-01-18 12:59:15 -080022import android.annotation.UserIdInt;
Christopher Tateee7805b2016-07-15 16:56:56 -070023import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070024import android.app.ActivityManager;
Makoto Onuki15407842018-01-19 14:23:11 -080025import android.app.ActivityManagerInternal;
Christopher Tated1aebb32018-01-31 13:24:14 -080026import android.app.AlarmManager;
Christopher Tate5568f542014-06-18 13:53:31 -070027import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070029import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070030import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000031import android.app.job.JobParameters;
Christopher Tate7060b042014-06-09 19:50:00 -070032import android.app.job.JobScheduler;
33import android.app.job.JobService;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070034import android.app.job.JobWorkItem;
Amith Yamasaniafbccb72017-11-27 10:44:24 -080035import android.app.usage.UsageStatsManager;
Christopher Tatea732f012017-10-26 17:26:53 -070036import android.app.usage.UsageStatsManagerInternal;
37import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
Christopher Tate7060b042014-06-09 19:50:00 -070038import android.content.BroadcastReceiver;
39import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070040import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070044import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070045import android.content.pm.PackageManager;
Christopher Tatea732f012017-10-26 17:26:53 -070046import android.content.pm.PackageManagerInternal;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060047import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070048import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070049import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070050import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070051import android.os.BatteryStats;
Amith Yamasani977e11f2018-02-16 11:29:54 -080052import android.os.BatteryStatsInternal;
Christopher Tate7060b042014-06-09 19:50:00 -070053import android.os.Binder;
54import android.os.Handler;
55import android.os.Looper;
56import android.os.Message;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070057import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070058import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080059import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070060import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070061import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070062import android.os.SystemClock;
63import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070064import android.os.UserManagerInternal;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070065import android.provider.Settings;
Amith Yamasani977e11f2018-02-16 11:29:54 -080066import android.text.format.DateUtils;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070067import android.util.KeyValueListParser;
Christopher Tate7060b042014-06-09 19:50:00 -070068import android.util.Slog;
69import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080070import android.util.SparseIntArray;
Tej Singhd5747a62018-01-08 20:57:35 -080071import android.util.StatsLog;
Dianne Hackborn970510b2016-02-24 16:56:42 -080072import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080073import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080074
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070075import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070076import com.android.internal.app.IBatteryStats;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070077import com.android.internal.app.procstats.ProcessStats;
Christopher Tatea732f012017-10-26 17:26:53 -070078import com.android.internal.os.BackgroundThread;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070079import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060080import com.android.internal.util.DumpUtils;
Makoto Onuki15407842018-01-19 14:23:11 -080081import com.android.internal.util.Preconditions;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080082import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070083import com.android.server.FgThread;
Makoto Onukie4918212018-02-06 11:30:15 -080084import com.android.server.AppStateTracker;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080085import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080086import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
87import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Christopher Tate2f36fd62016-02-18 18:36:08 -080088import com.android.server.job.JobStore.JobStatusFunctor;
Amith Yamasanib0ff3222015-03-04 09:56:14 -080089import com.android.server.job.controllers.AppIdleController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070090import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070091import com.android.server.job.controllers.BatteryController;
92import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080093import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070094import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070095import com.android.server.job.controllers.IdleController;
96import com.android.server.job.controllers.JobStatus;
97import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -070098import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -070099import com.android.server.job.controllers.TimeController;
100
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700101import libcore.util.EmptyArray;
102
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700103import java.io.FileDescriptor;
104import java.io.PrintWriter;
105import java.time.Clock;
106import java.util.ArrayList;
107import java.util.Arrays;
108import java.util.Collections;
109import java.util.Comparator;
110import java.util.Iterator;
111import java.util.List;
Makoto Onuki15407842018-01-19 14:23:11 -0800112import java.util.function.Predicate;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700113
Christopher Tate7060b042014-06-09 19:50:00 -0700114/**
115 * Responsible for taking jobs representing work to be performed by a client app, and determining
116 * based on the criteria specified when that job should be run against the client application's
117 * endpoint.
118 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
119 * about constraints, or the state of active jobs. It receives callbacks from the various
120 * controllers and completed jobs and operates accordingly.
121 *
122 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
123 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
124 * @hide
125 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800126public final class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700127 implements StateChangedListener, JobCompletedListener {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800128 static final String TAG = "JobSchedulerService";
Matthew Williamsaa984312015-10-15 16:08:05 -0700129 public static final boolean DEBUG = false;
Christopher Tatea732f012017-10-26 17:26:53 -0700130 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800131
Dianne Hackborn970510b2016-02-24 16:56:42 -0800132 /** The maximum number of concurrent jobs we run at one time. */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700133 private static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800134 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800135 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800136 /** The maximum number of jobs that we allow an unprivileged app to schedule */
137 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700138
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700139 @VisibleForTesting
140 public static Clock sSystemClock = Clock.systemUTC();
141 @VisibleForTesting
142 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
143 @VisibleForTesting
144 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800145
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800146 /** Global local for all job scheduler state. */
147 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700148 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700149 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700150 /** Tracking the standby bucket state of each app */
151 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700152 /** Tracking amount of time each package runs for. */
153 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Christopher Tate7060b042014-06-09 19:50:00 -0700154
155 static final int MSG_JOB_EXPIRED = 0;
156 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700157 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000158 static final int MSG_CHECK_JOB_GREEDY = 3;
Christopher Tate7060b042014-06-09 19:50:00 -0700159
Christopher Tate7060b042014-06-09 19:50:00 -0700160 /**
161 * Track Services that have currently active or pending jobs. The index is provided by
162 * {@link JobStatus#getServiceToken()}
163 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700164 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700165 /** List of controllers that will notify this service of updates to jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700166 List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800167 /** Need direct access to this for testing. */
168 BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700169 /** Need direct access to this for testing. */
170 StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700171 /** Need directly for sending uid state changes */
172 private BackgroundJobsController mBackgroundJobsController;
Suprabh Shukla106203b2017-11-02 21:23:44 -0700173 private DeviceIdleJobsController mDeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700174 /**
175 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
176 * when ready to execute them.
177 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700178 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700179
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700180 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700181
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700182 final JobHandler mHandler;
183 final JobSchedulerStub mJobSchedulerStub;
184
Christopher Tatea732f012017-10-26 17:26:53 -0700185 PackageManagerInternal mLocalPM;
Makoto Onuki15407842018-01-19 14:23:11 -0800186 ActivityManagerInternal mActivityManagerInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700187 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800188 DeviceIdleController.LocalService mLocalDeviceIdleController;
Makoto Onukie4918212018-02-06 11:30:15 -0800189 AppStateTracker mAppStateTracker;
Christopher Tated1aebb32018-01-31 13:24:14 -0800190 final UsageStatsManagerInternal mUsageStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700191
192 /**
193 * Set to true once we are allowed to run third party apps.
194 */
195 boolean mReadyToRock;
196
Christopher Tate7060b042014-06-09 19:50:00 -0700197 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800198 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800199 */
200 boolean mReportedActive;
201
202 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800203 * Are we currently in device-wide standby parole?
204 */
205 volatile boolean mInParole;
206
207 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800208 * Current limit on the number of concurrent JobServiceContext entries we want to
209 * keep actively running a job.
210 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700211 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800212
213 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800214 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800215 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800216 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
217
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700218 /**
219 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
220 */
221 final SparseIntArray mBackingUpUids = new SparseIntArray();
222
Christopher Tatea732f012017-10-26 17:26:53 -0700223 /**
224 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
225 * next become runnable. Index into this array is by normalized bucket:
226 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
227 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
228 * and NEVER apps don't get them at all.
229 */
230 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
231 long mHeartbeat = 0;
Christopher Tated1aebb32018-01-31 13:24:14 -0800232 long mLastHeartbeatTime = sElapsedRealtimeClock.millis();
233
234 static final String HEARTBEAT_TAG = "*job.heartbeat*";
235 final HeartbeatAlarmListener mHeartbeatAlarm = new HeartbeatAlarmListener();
Christopher Tatea732f012017-10-26 17:26:53 -0700236
Dianne Hackborn970510b2016-02-24 16:56:42 -0800237 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
238
239 /**
240 * This array essentially stores the state of mActiveServices array.
241 * The ith index stores the job present on the ith JobServiceContext.
242 * We manipulate this array until we arrive at what jobs should be running on
243 * what JobServiceContext.
244 */
245 JobStatus[] mTmpAssignContextIdToJobMap = new JobStatus[MAX_JOB_CONTEXTS_COUNT];
246 /**
247 * Indicates whether we need to act on this jobContext id
248 */
249 boolean[] mTmpAssignAct = new boolean[MAX_JOB_CONTEXTS_COUNT];
250 /**
251 * The uid whose jobs we would like to assign to a context.
252 */
253 int[] mTmpAssignPreferredUidForContext = new int[MAX_JOB_CONTEXTS_COUNT];
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800254
255 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700256 * All times are in milliseconds. These constants are kept synchronized with the system
257 * global Settings. Any access to this class or its fields should be done while
258 * holding the JobSchedulerService.mLock lock.
259 */
260 private final class Constants extends ContentObserver {
261 // Key names stored in the settings value.
262 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
263 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800264 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700265 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700266 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
267 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
268 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
269 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
270 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
271 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
272 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
273 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
274 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
275 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700276 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
277 = "max_standard_reschedule_count";
278 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
279 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
280 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700281 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
282 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
283 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
284 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700285
286 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
287 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800288 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700289 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700290 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
291 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
292 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
293 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
294 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
295 private static final int DEFAULT_FG_JOB_COUNT = 4;
296 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
297 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700298 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700299 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700300 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
301 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
302 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
303 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700304 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000305 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
306 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700307 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700308
309 /**
310 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
311 * early.
312 */
313 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
314 /**
315 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
316 * things early.
317 */
318 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
319 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800320 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
321 * schedule things early.
322 */
323 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
324 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700325 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
326 * schedule things early.
327 */
328 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
329 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700330 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
331 * things early. 1 == Run connectivity jobs as soon as ready.
332 */
333 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
334 /**
335 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
336 * schedule things early.
337 */
338 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
339 /**
340 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
341 * running some work early. This (and thus the other min counts) is now set to 1, to
342 * prevent any batching at this level. Since we now do batching through doze, that is
343 * a much better mechanism.
344 */
345 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
346 /**
347 * This is the job execution factor that is considered to be heavy use of the system.
348 */
349 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
350 /**
351 * This is the job execution factor that is considered to be moderate use of the system.
352 */
353 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
354 /**
355 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
356 */
357 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
358 /**
359 * The maximum number of background jobs we allow when the system is in a normal
360 * memory state.
361 */
362 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
363 /**
364 * The maximum number of background jobs we allow when the system is in a moderate
365 * memory state.
366 */
367 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
368 /**
369 * The maximum number of background jobs we allow when the system is in a low
370 * memory state.
371 */
372 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
373 /**
374 * The maximum number of background jobs we allow when the system is in a critical
375 * memory state.
376 */
377 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700378 /**
379 * The maximum number of times we allow a job to have itself rescheduled before
380 * giving up on it, for standard jobs.
381 */
382 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
383 /**
384 * The maximum number of times we allow a job to have itself rescheduled before
385 * giving up on it, for jobs that are executing work.
386 */
387 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
388 /**
389 * The minimum backoff time to allow for linear backoff.
390 */
391 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
392 /**
393 * The minimum backoff time to allow for exponential backoff.
394 */
395 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700396 /**
397 * How often we recalculate runnability based on apps' standby bucket assignment.
398 * This should be prime relative to common time interval lengths such as a quarter-
399 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
400 */
401 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
402
403 /**
404 * Mapping: standby bucket -> number of heartbeats between each sweep of that
405 * bucket's jobs.
406 *
407 * Bucket assignments as recorded in the JobStatus objects are normalized to be
408 * indices into this array, rather than the raw constants used
409 * by AppIdleHistory.
410 */
411 final int[] STANDBY_BEATS = {
412 0,
413 DEFAULT_STANDBY_WORKING_BEATS,
414 DEFAULT_STANDBY_FREQUENT_BEATS,
415 DEFAULT_STANDBY_RARE_BEATS
416 };
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700417
418 private ContentResolver mResolver;
419 private final KeyValueListParser mParser = new KeyValueListParser(',');
420
421 public Constants(Handler handler) {
422 super(handler);
423 }
424
425 public void start(ContentResolver resolver) {
426 mResolver = resolver;
427 mResolver.registerContentObserver(Settings.Global.getUriFor(
428 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
429 updateConstants();
430 }
431
432 @Override
433 public void onChange(boolean selfChange, Uri uri) {
434 updateConstants();
435 }
436
437 private void updateConstants() {
438 synchronized (mLock) {
439 try {
440 mParser.setString(Settings.Global.getString(mResolver,
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000441 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700442 } catch (IllegalArgumentException e) {
443 // Failed to parse the settings string, log this and move on
444 // with defaults.
Suprabh Shukla7a0a5c42017-07-25 21:07:13 +0000445 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700446 }
447
448 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
449 DEFAULT_MIN_IDLE_COUNT);
450 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
451 DEFAULT_MIN_CHARGING_COUNT);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800452 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
453 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
Dianne Hackborn532ea262017-03-17 17:50:55 -0700454 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
455 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700456 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
457 DEFAULT_MIN_CONNECTIVITY_COUNT);
458 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
459 DEFAULT_MIN_CONTENT_COUNT);
460 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
461 DEFAULT_MIN_READY_JOBS_COUNT);
462 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
463 DEFAULT_HEAVY_USE_FACTOR);
464 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
465 DEFAULT_MODERATE_USE_FACTOR);
466 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
467 DEFAULT_FG_JOB_COUNT);
468 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
469 DEFAULT_BG_NORMAL_JOB_COUNT);
470 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
471 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
472 }
473 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
474 DEFAULT_BG_MODERATE_JOB_COUNT);
475 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
476 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
477 }
478 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
479 DEFAULT_BG_LOW_JOB_COUNT);
480 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
481 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
482 }
483 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
484 DEFAULT_BG_CRITICAL_JOB_COUNT);
485 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
486 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
487 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700488 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
489 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
490 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
491 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800492 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700493 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800494 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700495 DEFAULT_MIN_EXP_BACKOFF_TIME);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800496 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
Christopher Tatea732f012017-10-26 17:26:53 -0700497 DEFAULT_STANDBY_HEARTBEAT_TIME);
498 STANDBY_BEATS[1] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
499 DEFAULT_STANDBY_WORKING_BEATS);
500 STANDBY_BEATS[2] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
501 DEFAULT_STANDBY_FREQUENT_BEATS);
502 STANDBY_BEATS[3] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
503 DEFAULT_STANDBY_RARE_BEATS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700504 }
Christopher Tated1aebb32018-01-31 13:24:14 -0800505
506 // Reset the heartbeat alarm based on the new heartbeat duration
507 setNextHeartbeatAlarm();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700508 }
509
510 void dump(PrintWriter pw) {
511 pw.println(" Settings:");
512
513 pw.print(" "); pw.print(KEY_MIN_IDLE_COUNT); pw.print("=");
514 pw.print(MIN_IDLE_COUNT); pw.println();
515
516 pw.print(" "); pw.print(KEY_MIN_CHARGING_COUNT); pw.print("=");
517 pw.print(MIN_CHARGING_COUNT); pw.println();
518
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800519 pw.print(" "); pw.print(KEY_MIN_BATTERY_NOT_LOW_COUNT); pw.print("=");
520 pw.print(MIN_BATTERY_NOT_LOW_COUNT); pw.println();
521
Dianne Hackborn532ea262017-03-17 17:50:55 -0700522 pw.print(" "); pw.print(KEY_MIN_STORAGE_NOT_LOW_COUNT); pw.print("=");
523 pw.print(MIN_STORAGE_NOT_LOW_COUNT); pw.println();
524
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700525 pw.print(" "); pw.print(KEY_MIN_CONNECTIVITY_COUNT); pw.print("=");
526 pw.print(MIN_CONNECTIVITY_COUNT); pw.println();
527
528 pw.print(" "); pw.print(KEY_MIN_CONTENT_COUNT); pw.print("=");
529 pw.print(MIN_CONTENT_COUNT); pw.println();
530
531 pw.print(" "); pw.print(KEY_MIN_READY_JOBS_COUNT); pw.print("=");
532 pw.print(MIN_READY_JOBS_COUNT); pw.println();
533
534 pw.print(" "); pw.print(KEY_HEAVY_USE_FACTOR); pw.print("=");
535 pw.print(HEAVY_USE_FACTOR); pw.println();
536
537 pw.print(" "); pw.print(KEY_MODERATE_USE_FACTOR); pw.print("=");
538 pw.print(MODERATE_USE_FACTOR); pw.println();
539
540 pw.print(" "); pw.print(KEY_FG_JOB_COUNT); pw.print("=");
541 pw.print(FG_JOB_COUNT); pw.println();
542
543 pw.print(" "); pw.print(KEY_BG_NORMAL_JOB_COUNT); pw.print("=");
544 pw.print(BG_NORMAL_JOB_COUNT); pw.println();
545
546 pw.print(" "); pw.print(KEY_BG_MODERATE_JOB_COUNT); pw.print("=");
547 pw.print(BG_MODERATE_JOB_COUNT); pw.println();
548
549 pw.print(" "); pw.print(KEY_BG_LOW_JOB_COUNT); pw.print("=");
550 pw.print(BG_LOW_JOB_COUNT); pw.println();
551
552 pw.print(" "); pw.print(KEY_BG_CRITICAL_JOB_COUNT); pw.print("=");
553 pw.print(BG_CRITICAL_JOB_COUNT); pw.println();
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700554
555 pw.print(" "); pw.print(KEY_MAX_STANDARD_RESCHEDULE_COUNT); pw.print("=");
556 pw.print(MAX_STANDARD_RESCHEDULE_COUNT); pw.println();
557
558 pw.print(" "); pw.print(KEY_MAX_WORK_RESCHEDULE_COUNT); pw.print("=");
559 pw.print(MAX_WORK_RESCHEDULE_COUNT); pw.println();
560
561 pw.print(" "); pw.print(KEY_MIN_LINEAR_BACKOFF_TIME); pw.print("=");
562 pw.print(MIN_LINEAR_BACKOFF_TIME); pw.println();
563
564 pw.print(" "); pw.print(KEY_MIN_EXP_BACKOFF_TIME); pw.print("=");
565 pw.print(MIN_EXP_BACKOFF_TIME); pw.println();
Christopher Tatea732f012017-10-26 17:26:53 -0700566
567 pw.print(" "); pw.print(KEY_STANDBY_HEARTBEAT_TIME); pw.print("=");
568 pw.print(STANDBY_HEARTBEAT_TIME); pw.println();
569
570 pw.print(" standby_beats={");
571 pw.print(STANDBY_BEATS[0]);
572 for (int i = 1; i < STANDBY_BEATS.length; i++) {
573 pw.print(", ");
574 pw.print(STANDBY_BEATS[i]);
575 }
576 pw.println('}');
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700577 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800578
579 void dump(ProtoOutputStream proto, long fieldId) {
580 final long token = proto.start(fieldId);
581
582 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
583 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
584 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
585 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
586 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
587 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
588 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
589 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
590 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
591 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
592 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
593 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
594 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
595 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
596 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
597 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
598 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
599 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
600 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
601
602 for (int period : STANDBY_BEATS) {
603 proto.write(ConstantsProto.STANDBY_BEATS, period);
604 }
605
606 proto.end(token);
607 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700608 }
609
610 final Constants mConstants;
611
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700612 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
613 if (o1.enqueueTime < o2.enqueueTime) {
614 return -1;
615 }
616 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
617 };
618
619 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
620 int where = Collections.binarySearch(array, newItem, comparator);
621 if (where < 0) {
622 where = ~where;
623 }
624 array.add(where, newItem);
625 }
626
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700627 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700628 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
629 * still clean up. On reinstall the package will have a new uid.
630 */
631 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
632 @Override
633 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700634 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700635 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700636 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700637 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700638 final String pkgName = getPackageName(intent);
639 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
640
Christopher Tateee7805b2016-07-15 16:56:56 -0700641 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700642 // Purge the app's jobs if the whole package was just disabled. When this is
643 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700644 if (pkgName != null && pkgUid != -1) {
645 final String[] changedComponents = intent.getStringArrayExtra(
646 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
647 if (changedComponents != null) {
648 for (String component : changedComponents) {
649 if (component.equals(pkgName)) {
650 if (DEBUG) {
651 Slog.d(TAG, "Package state change: " + pkgName);
652 }
653 try {
654 final int userId = UserHandle.getUserId(pkgUid);
655 IPackageManager pm = AppGlobals.getPackageManager();
656 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
657 if (state == COMPONENT_ENABLED_STATE_DISABLED
658 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
659 if (DEBUG) {
660 Slog.d(TAG, "Removing jobs for package " + pkgName
661 + " in user " + userId);
662 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700663 cancelJobsForPackageAndUid(pkgName, pkgUid,
664 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700665 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700666 } catch (RemoteException|IllegalArgumentException e) {
667 /*
668 * IllegalArgumentException means that the package doesn't exist.
669 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
670 * behind outright uninstall, so by the time we try to act it's gone.
671 * We don't need to act on this PACKAGE_CHANGED when this happens;
672 * we'll get a PACKAGE_REMOVED later and clean up then.
673 *
674 * RemoteException can't actually happen; the package manager is
675 * running in this same process.
676 */
677 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700678 break;
679 }
680 }
681 }
682 } else {
683 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
684 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700685 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700686 // If this is an outright uninstall rather than the first half of an
687 // app update sequence, cancel the jobs associated with the app.
688 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
689 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
690 if (DEBUG) {
691 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
692 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700693 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700694 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700695 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700696 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
697 if (DEBUG) {
698 Slog.d(TAG, "Removing jobs for user: " + userId);
699 }
700 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700701 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
702 // Has this package scheduled any jobs, such that we will take action
703 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700704 if (pkgUid != -1) {
705 List<JobStatus> jobsForUid;
706 synchronized (mLock) {
707 jobsForUid = mJobs.getJobsByUid(pkgUid);
708 }
709 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
710 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
711 if (DEBUG) {
712 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
713 + pkgUid + " has jobs");
714 }
715 setResultCode(Activity.RESULT_OK);
716 break;
717 }
718 }
719 }
720 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
721 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700722 if (pkgUid != -1) {
723 if (DEBUG) {
724 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
725 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700726 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700727 }
Christopher Tate7060b042014-06-09 19:50:00 -0700728 }
729 }
730 };
731
Christopher Tateb5c07882016-05-26 17:11:09 -0700732 private String getPackageName(Intent intent) {
733 Uri uri = intent.getData();
734 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
735 return pkg;
736 }
737
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700738 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700739 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800740 updateUidState(uid, procState);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700741 }
742
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700743 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800744 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborne07641d2016-11-09 15:07:23 -0800745 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700746 cancelJobsForUid(uid, "uid gone");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800747 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700748 synchronized (mLock) {
749 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
750 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700751 }
752
753 @Override public void onUidActive(int uid) throws RemoteException {
Suprabh Shukla106203b2017-11-02 21:23:44 -0700754 synchronized (mLock) {
755 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
756 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700757 }
758
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700759 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -0800760 if (disabled) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700761 cancelJobsForUid(uid, "app uid idle");
Dianne Hackborne07641d2016-11-09 15:07:23 -0800762 }
Suprabh Shukla106203b2017-11-02 21:23:44 -0700763 synchronized (mLock) {
764 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
765 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700766 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700767
768 @Override public void onUidCachedChanged(int uid, boolean cached) {
769 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700770 };
771
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800772 public Object getLock() {
773 return mLock;
774 }
775
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700776 public JobStore getJobStore() {
777 return mJobs;
778 }
779
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700780 @Override
781 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700782 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
783 // Let's kick any outstanding jobs for this user.
784 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
785 }
786
787 @Override
788 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700789 // Let's kick any outstanding jobs for this user.
790 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
791 }
792
793 @Override
794 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700795 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700796 }
797
Makoto Onuki15407842018-01-19 14:23:11 -0800798 /**
Makoto Onukie4918212018-02-06 11:30:15 -0800799 * Return whether an UID is active or idle.
Makoto Onuki15407842018-01-19 14:23:11 -0800800 */
Makoto Onukie4918212018-02-06 11:30:15 -0800801 private boolean isUidActive(int uid) {
802 return mAppStateTracker.isUidActiveSynced(uid);
Makoto Onuki15407842018-01-19 14:23:11 -0800803 }
804
Makoto Onukie4918212018-02-06 11:30:15 -0800805 private final Predicate<Integer> mIsUidActivePredicate = this::isUidActive;
Makoto Onuki15407842018-01-19 14:23:11 -0800806
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700807 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
808 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700809 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800810 if (ActivityManager.getService().isAppStartModeDisabled(uId,
811 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700812 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
813 + " -- package not allowed to start");
814 return JobScheduler.RESULT_FAILURE;
815 }
816 } catch (RemoteException e) {
817 }
Christopher Tatea732f012017-10-26 17:26:53 -0700818
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800819 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700820 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
821
822 if (work != null && toCancel != null) {
823 // Fast path: we are adding work to an existing job, and the JobInfo is not
824 // changing. We can just directly enqueue this work in to the job.
825 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -0800826
Dianne Hackborn342e6032017-04-13 18:04:31 -0700827 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Makoto Onuki15407842018-01-19 14:23:11 -0800828
829 // If any of work item is enqueued when the source is in the foreground,
830 // exempt the entire job.
Makoto Onukie4918212018-02-06 11:30:15 -0800831 toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800832
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700833 return JobScheduler.RESULT_SUCCESS;
834 }
835 }
836
837 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -0800838
839 // Give exemption if the source is in the foreground just now.
840 // Note if it's a sync job, this method is called on the handler so it's not exactly
841 // the state when requestSync() was called, but that should be fine because of the
842 // 1 minute foreground grace period.
Makoto Onukie4918212018-02-06 11:30:15 -0800843 jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800844
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700845 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -0800846 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800847 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800848 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
849 Slog.w(TAG, "Too many jobs for uid " + uId);
850 throw new IllegalStateException("Apps may not schedule more than "
851 + MAX_JOBS_PER_APP + " distinct jobs");
852 }
853 }
854
Dianne Hackborna47223f2017-03-30 13:49:13 -0700855 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700856 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -0700857
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700858 if (toCancel != null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -0700859 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
Christopher Tateb1c1f9a2016-03-17 13:29:25 -0700860 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700861 if (work != null) {
862 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -0700863 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700864 }
865 startTrackingJobLocked(jobStatus, toCancel);
Tej Singhd5747a62018-01-08 20:57:35 -0800866 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -0800867 uId, null, jobStatus.getBatteryName(),
868 StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700869
870 // If the job is immediately ready to run, then we can just immediately
871 // put it in the pending list and try to schedule it. This is especially
872 // important for jobs with a 0 deadline constraint, since they will happen a fair
873 // amount, we want to handle them as quickly as possible, and semantically we want to
874 // make sure we have started holding the wake lock for the job before returning to
875 // the caller.
876 // If the job is not yet ready to run, there is nothing more to do -- we are
877 // now just waiting for one of its controllers to change state and schedule
878 // the job appropriately.
879 if (isReadyToBeExecutedLocked(jobStatus)) {
880 // This is a new job, we can just immediately put it on the pending
881 // list and try to run it.
882 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700883 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700884 maybeRunPendingJobsLocked();
885 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -0800886 }
Christopher Tate7060b042014-06-09 19:50:00 -0700887 return JobScheduler.RESULT_SUCCESS;
888 }
889
890 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800891 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800892 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
893 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
894 for (int i = jobs.size() - 1; i >= 0; i--) {
895 JobStatus job = jobs.get(i);
896 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -0700897 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800898 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -0700899 }
Christopher Tate7060b042014-06-09 19:50:00 -0700900 }
901
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600902 public JobInfo getPendingJob(int uid, int jobId) {
903 synchronized (mLock) {
904 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
905 for (int i = jobs.size() - 1; i >= 0; i--) {
906 JobStatus job = jobs.get(i);
907 if (job.getJobId() == jobId) {
908 return job.getJob();
909 }
910 }
911 return null;
912 }
913 }
914
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700915 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800916 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700917 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
918 for (int i=0; i<jobsForUser.size(); i++) {
919 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700920 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700921 }
Christopher Tate7060b042014-06-09 19:50:00 -0700922 }
923 }
924
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700925 private void cancelJobsForNonExistentUsers() {
926 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
927 synchronized (mLock) {
928 mJobs.removeJobsOfNonUsers(umi.getUserIds());
929 }
930 }
931
Makoto Onukie7b96182017-08-30 14:53:16 -0700932 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
933 if ("android".equals(pkgName)) {
934 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
935 return;
936 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700937 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700938 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
939 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
940 final JobStatus job = jobsForUid.get(i);
941 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700942 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700943 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700944 }
945 }
946 }
947
Christopher Tate7060b042014-06-09 19:50:00 -0700948 /**
949 * Entry point from client to cancel all jobs originating from their uid.
950 * This will remove the job from the master list, and cancel the job if it was staged for
951 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -0700952 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -0800953 *
Christopher Tate7060b042014-06-09 19:50:00 -0700954 */
Christopher Tate8c67d122017-09-29 16:54:26 -0700955 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700956 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -0700957 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -0700958 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -0700959 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700960
961 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800962 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700963 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
964 for (int i=0; i<jobsForUid.size(); i++) {
965 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -0700966 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -0700967 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700968 }
Christopher Tate7060b042014-06-09 19:50:00 -0700969 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700970 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -0700971 }
972
973 /**
974 * Entry point from client to cancel the job corresponding to the jobId provided.
975 * This will remove the job from the master list, and cancel the job if it was staged for
976 * execution or being executed.
977 * @param uid Uid of the calling client.
978 * @param jobId Id of the job, provided at schedule-time.
979 */
Makoto Onukid2bfec62018-01-12 13:58:01 -0800980 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -0700981 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800982 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -0700983 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700984 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -0800985 cancelJobImplLocked(toCancel, null,
986 "cancel() called by app, callingUid=" + callingUid
987 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700988 }
Christopher Tate8c67d122017-09-29 16:54:26 -0700989 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -0700990 }
991 }
992
Dianne Hackborn729a3282017-06-09 16:06:01 -0700993 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700994 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
995 cancelled.unprepareLocked(ActivityManager.getService());
996 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
997 // Remove from pending queue.
998 if (mPendingJobs.remove(cancelled)) {
999 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -07001000 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001001 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -07001002 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001003 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001004 }
1005
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001006 void updateUidState(int uid, int procState) {
1007 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001008 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1009 // Only use this if we are exactly the top app. All others can live
1010 // with just the foreground priority. This means that persistent processes
1011 // can never be the top app priority... that is fine.
1012 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001013 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001014 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001015 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001016 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001017 }
1018 }
1019 }
1020
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001021 @Override
1022 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001023 synchronized (mLock) {
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001024 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001025 // When becoming idle, make sure no jobs are actively running,
1026 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001027 for (int i=0; i<mActiveServices.size(); i++) {
1028 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001029 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001030 if (executing != null
1031 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001032 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1033 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001034 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001035 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001036 } else {
1037 // When coming out of idle, allow thing to start back up.
1038 if (mReadyToRock) {
1039 if (mLocalDeviceIdleController != null) {
1040 if (!mReportedActive) {
1041 mReportedActive = true;
1042 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001043 }
1044 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001045 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001046 }
1047 }
1048 }
1049 }
1050
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001051 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001052 // active is true if pending queue contains jobs OR some job is running.
1053 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001054 if (mPendingJobs.size() <= 0) {
1055 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001056 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001057 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001058 if (job != null
1059 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
1060 && !job.dozeWhitelisted) {
1061 // We will report active if we have a job running and it is not an exception
1062 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001063 active = true;
1064 break;
1065 }
1066 }
1067 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001068
1069 if (mReportedActive != active) {
1070 mReportedActive = active;
1071 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001072 mLocalDeviceIdleController.setJobsActive(active);
1073 }
1074 }
1075 }
1076
Christopher Tated117b292018-01-05 17:32:36 -08001077 void reportAppUsage(String packageName, int userId) {
1078 // This app just transitioned into interactive use or near equivalent, so we should
1079 // take a look at its job state for feedback purposes.
1080 }
1081
Christopher Tate7060b042014-06-09 19:50:00 -07001082 /**
1083 * Initializes the system service.
1084 * <p>
1085 * Subclasses must define a single argument constructor that accepts the context
1086 * and passes it to super.
1087 * </p>
1088 *
1089 * @param context The system server context.
1090 */
1091 public JobSchedulerService(Context context) {
1092 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001093
1094 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Makoto Onuki15407842018-01-19 14:23:11 -08001095 mActivityManagerInternal = Preconditions.checkNotNull(
1096 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001097
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001098 mHandler = new JobHandler(context.getMainLooper());
1099 mConstants = new Constants(mHandler);
1100 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001101
1102 // Set up the app standby bucketing tracker
Christopher Tated1aebb32018-01-31 13:24:14 -08001103 mStandbyTracker = new StandbyTracker();
1104 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1105 mUsageStats.addAppIdleStateChangeListener(mStandbyTracker);
Christopher Tatea732f012017-10-26 17:26:53 -07001106
1107 // The job store needs to call back
1108 publishLocalService(JobSchedulerInternal.class, new LocalService());
1109
1110 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001111 mJobs = JobStore.initAndGet(this);
1112
Christopher Tate7060b042014-06-09 19:50:00 -07001113 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001114 mControllers = new ArrayList<StateController>();
Christopher Tate7060b042014-06-09 19:50:00 -07001115 mControllers.add(ConnectivityController.get(this));
1116 mControllers.add(TimeController.get(this));
1117 mControllers.add(IdleController.get(this));
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001118 mBatteryController = BatteryController.get(this);
1119 mControllers.add(mBatteryController);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001120 mStorageController = StorageController.get(this);
1121 mControllers.add(mStorageController);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001122 mControllers.add(BackgroundJobsController.get(this));
Amith Yamasanib0ff3222015-03-04 09:56:14 -08001123 mControllers.add(AppIdleController.get(this));
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001124 mControllers.add(ContentObserverController.get(this));
Suprabh Shukla106203b2017-11-02 21:23:44 -07001125 mDeviceIdleJobsController = DeviceIdleJobsController.get(this);
1126 mControllers.add(mDeviceIdleJobsController);
Christopher Tate616541d2017-07-26 14:27:38 -07001127
1128 // If the job store determined that it can't yet reschedule persisted jobs,
1129 // we need to start watching the clock.
1130 if (!mJobs.jobTimesInflatedValid()) {
1131 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1132 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1133 }
Christopher Tate7060b042014-06-09 19:50:00 -07001134 }
1135
Christopher Tate616541d2017-07-26 14:27:38 -07001136 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1137 @Override
1138 public void onReceive(Context context, Intent intent) {
1139 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1140 // When we reach clock sanity, recalculate the temporal windows
1141 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001142 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001143 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1144
1145 // We've done our job now, so stop watching the time.
1146 context.unregisterReceiver(this);
1147
1148 // And kick off the work to update the affected jobs, using a secondary
1149 // thread instead of chugging away here on the main looper thread.
1150 FgThread.getHandler().post(mJobTimeUpdater);
1151 }
1152 }
1153 }
1154 };
1155
1156 private final Runnable mJobTimeUpdater = () -> {
1157 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1158 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1159 synchronized (mLock) {
1160 // Note: we intentionally both look up the existing affected jobs and replace them
1161 // with recalculated ones inside the same lock lifetime.
1162 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1163
1164 // Now, at each position [i], we have both the existing JobStatus
1165 // and the one that replaces it.
1166 final int N = toAdd.size();
1167 for (int i = 0; i < N; i++) {
1168 final JobStatus oldJob = toRemove.get(i);
1169 final JobStatus newJob = toAdd.get(i);
1170 if (DEBUG) {
1171 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1172 }
1173 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1174 }
1175 }
1176 };
1177
Christopher Tate7060b042014-06-09 19:50:00 -07001178 @Override
1179 public void onStart() {
1180 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1181 }
1182
1183 @Override
1184 public void onBootPhase(int phase) {
1185 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001186 mConstants.start(getContext().getContentResolver());
Makoto Onuki15407842018-01-19 14:23:11 -08001187
Makoto Onukie4918212018-02-06 11:30:15 -08001188 mAppStateTracker = Preconditions.checkNotNull(
1189 LocalServices.getService(AppStateTracker.class));
Christopher Tated1aebb32018-01-31 13:24:14 -08001190 setNextHeartbeatAlarm();
Makoto Onuki15407842018-01-19 14:23:11 -08001191
Shreyas Basarge5db09082016-01-07 13:38:29 +00001192 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001193 final IntentFilter filter = new IntentFilter();
1194 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1195 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001196 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1197 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001198 filter.addDataScheme("package");
1199 getContext().registerReceiverAsUser(
1200 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1201 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1202 getContext().registerReceiverAsUser(
1203 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001204 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001205 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001206 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001207 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1208 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001209 } catch (RemoteException e) {
1210 // ignored; both services live in system_server
1211 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001212 // Remove any jobs that are not associated with any of the current users.
1213 cancelJobsForNonExistentUsers();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001214 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001215 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001216 // Let's go!
1217 mReadyToRock = true;
1218 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1219 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001220 mLocalDeviceIdleController
1221 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001222 // Create the "runners".
1223 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1224 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001225 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001226 getContext().getMainLooper()));
1227 }
1228 // Attach jobs to their controllers.
Christopher Tate2f36fd62016-02-18 18:36:08 -08001229 mJobs.forEachJob(new JobStatusFunctor() {
1230 @Override
1231 public void process(JobStatus job) {
1232 for (int controller = 0; controller < mControllers.size(); controller++) {
1233 final StateController sc = mControllers.get(controller);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001234 sc.maybeStartTrackingJobLocked(job, null);
1235 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001236 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001237 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001238 // GO GO GO!
1239 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1240 }
Christopher Tate7060b042014-06-09 19:50:00 -07001241 }
1242 }
1243
1244 /**
1245 * Called when we have a job status object that we need to insert in our
1246 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1247 * about.
1248 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001249 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1250 if (!jobStatus.isPreparedLocked()) {
1251 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1252 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001253 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001254 final boolean update = mJobs.add(jobStatus);
1255 if (mReadyToRock) {
1256 for (int i = 0; i < mControllers.size(); i++) {
1257 StateController controller = mControllers.get(i);
1258 if (update) {
1259 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001260 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001261 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001262 }
Christopher Tate7060b042014-06-09 19:50:00 -07001263 }
1264 }
1265
1266 /**
1267 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1268 * object removed.
1269 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001270 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001271 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001272 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001273 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001274
1275 // Remove from store as well as controllers.
1276 final boolean removed = mJobs.remove(jobStatus, writeBack);
1277 if (removed && mReadyToRock) {
1278 for (int i=0; i<mControllers.size(); i++) {
1279 StateController controller = mControllers.get(i);
1280 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001281 }
1282 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001283 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001284 }
1285
Dianne Hackborn729a3282017-06-09 16:06:01 -07001286 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001287 for (int i=0; i<mActiveServices.size(); i++) {
1288 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001289 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001290 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001291 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001292 return true;
1293 }
1294 }
1295 return false;
1296 }
1297
1298 /**
1299 * @param job JobStatus we are querying against.
1300 * @return Whether or not the job represented by the status object is currently being run or
1301 * is pending.
1302 */
1303 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001304 for (int i=0; i<mActiveServices.size(); i++) {
1305 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001306 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001307 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1308 return true;
1309 }
1310 }
1311 return false;
1312 }
1313
Dianne Hackborn807de782016-04-07 17:54:41 -07001314 void noteJobsPending(List<JobStatus> jobs) {
1315 for (int i = jobs.size() - 1; i >= 0; i--) {
1316 JobStatus job = jobs.get(i);
1317 mJobPackageTracker.notePending(job);
1318 }
1319 }
1320
1321 void noteJobsNonpending(List<JobStatus> jobs) {
1322 for (int i = jobs.size() - 1; i >= 0; i--) {
1323 JobStatus job = jobs.get(i);
1324 mJobPackageTracker.noteNonpending(job);
1325 }
1326 }
1327
Christopher Tate7060b042014-06-09 19:50:00 -07001328 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001329 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1330 * specify an override deadline on a failed job (the failed job will run even though it's not
1331 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1332 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1333 *
Christopher Tate7060b042014-06-09 19:50:00 -07001334 * @param failureToReschedule Provided job status that we will reschedule.
1335 * @return A newly instantiated JobStatus with the same constraints as the last job except
1336 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001337 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001338 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001339 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001340 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001341 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001342 final JobInfo job = failureToReschedule.getJob();
1343
1344 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001345 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1346 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001347
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001348 if (failureToReschedule.hasWorkLocked()) {
1349 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1350 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1351 + backoffAttempts + " > work limit "
1352 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1353 return null;
1354 }
1355 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1356 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1357 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1358 return null;
1359 }
1360
Christopher Tate7060b042014-06-09 19:50:00 -07001361 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001362 case JobInfo.BACKOFF_POLICY_LINEAR: {
1363 long backoff = initialBackoffMillis;
1364 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1365 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1366 }
1367 delayMillis = backoff * backoffAttempts;
1368 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001369 default:
1370 if (DEBUG) {
1371 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1372 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001373 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1374 long backoff = initialBackoffMillis;
1375 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1376 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1377 }
1378 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1379 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001380 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001381 delayMillis =
1382 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001383 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1384 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001385 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001386 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001387 for (int ic=0; ic<mControllers.size(); ic++) {
1388 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001389 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001390 }
1391 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001392 }
1393
1394 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001395 * Called after a periodic has executed so we can reschedule it. We take the last execution
1396 * time of the job to be the time of completion (i.e. the time at which this function is
1397 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001398 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001399 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1400 * to underscheduling at least, rather than if we had taken the last execution time to be the
1401 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001402 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1403 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001404 * @return A new job representing the execution criteria for this instantiation of the
1405 * recurring job.
1406 */
1407 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001408 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001409 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001410 long runEarly = 0L;
1411
1412 // If this periodic was rescheduled it won't have a deadline.
1413 if (periodicToReschedule.hasDeadlineConstraint()) {
1414 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1415 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001416 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001417 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001418 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1419 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001420
1421 if (DEBUG) {
1422 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1423 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1424 }
Christopher Tatea732f012017-10-26 17:26:53 -07001425 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1426 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1427 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001428 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001429 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001430 }
1431
Christopher Tated1aebb32018-01-31 13:24:14 -08001432 long heartbeatWhenJobsLastRun(String packageName, final @UserIdInt int userId) {
1433 final long heartbeat;
1434 final long timeSinceLastJob = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
1435 synchronized (mLock) {
1436 heartbeat = mHeartbeat - (timeSinceLastJob / mConstants.STANDBY_HEARTBEAT_TIME);
1437 }
1438 if (DEBUG_STANDBY) {
1439 Slog.v(TAG, "Last job heartbeat " + heartbeat + " for " + packageName + "/" + userId
1440 + " delta=" + timeSinceLastJob);
1441 }
1442 return heartbeat;
1443 }
1444
1445 long heartbeatWhenJobsLastRun(JobStatus job) {
1446 return heartbeatWhenJobsLastRun(job.getSourcePackageName(), job.getSourceUserId());
1447 }
1448
Christopher Tate7060b042014-06-09 19:50:00 -07001449 // JobCompletedListener implementations.
1450
1451 /**
1452 * A job just finished executing. We fetch the
1453 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1454 * whether we want to reschedule we readd it to the controllers.
1455 * @param jobStatus Completed job.
1456 * @param needsReschedule Whether the implementing class should reschedule this job.
1457 */
1458 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001459 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001460 if (DEBUG) {
1461 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1462 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001463
1464 // If the job wants to be rescheduled, we first need to make the next upcoming
1465 // job so we can transfer any appropriate state over from the previous job when
1466 // we stop it.
1467 final JobStatus rescheduledJob = needsReschedule
1468 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1469
Shreyas Basarge73f10252016-02-11 17:06:13 +00001470 // Do not write back immediately if this is a periodic job. The job may get lost if system
1471 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001472 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001473 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001474 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001475 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001476 // We still want to check for jobs to execute, because this job may have
1477 // scheduled a new job under the same job id, and now we can run it.
1478 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001479 return;
1480 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001481
1482 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001483 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001484 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001485 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001486 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001487 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001488 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001489 } else if (jobStatus.getJob().isPeriodic()) {
1490 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001491 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001492 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001493 } catch (SecurityException e) {
1494 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1495 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001496 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001497 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001498 jobStatus.unprepareLocked(ActivityManager.getService());
1499 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001500 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001501 }
1502
1503 // StateChangedListener implementations.
1504
1505 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001506 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1507 * some controller's state has changed, so as to run through the list of jobs and start/stop
1508 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001509 */
1510 @Override
1511 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001512 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001513 }
1514
1515 @Override
1516 public void onRunJobNow(JobStatus jobStatus) {
1517 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1518 }
1519
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001520 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001521
1522 public JobHandler(Looper looper) {
1523 super(looper);
1524 }
1525
1526 @Override
1527 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001528 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001529 if (!mReadyToRock) {
1530 return;
1531 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001532 switch (message.what) {
1533 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001534 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001535 // runNow can be null, which is a controller's way of indicating that its
1536 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001537 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001538 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001539 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001540 } else {
1541 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001542 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001543 } break;
1544 case MSG_CHECK_JOB:
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001545 if (mReportedActive) {
1546 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001547 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001548 } else {
1549 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001550 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001551 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001552 break;
1553 case MSG_CHECK_JOB_GREEDY:
1554 queueReadyJobsForExecutionLocked();
1555 break;
1556 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001557 cancelJobImplLocked((JobStatus) message.obj, null,
1558 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001559 break;
Matthew Williams75fc5252014-09-02 16:17:53 -07001560 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001561 maybeRunPendingJobsLocked();
1562 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1563 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001564 }
1565 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001566 }
Christopher Tate7060b042014-06-09 19:50:00 -07001567
Dianne Hackborn6d068262017-05-16 13:14:37 -07001568 private void stopNonReadyActiveJobsLocked() {
1569 for (int i=0; i<mActiveServices.size(); i++) {
1570 JobServiceContext serviceContext = mActiveServices.get(i);
1571 final JobStatus running = serviceContext.getRunningJobLocked();
1572 if (running != null && !running.isReady()) {
1573 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001574 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1575 "cancelled due to unsatisfied constraints");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001576 }
1577 }
1578 }
1579
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001580 /**
1581 * Run through list of jobs and execute all possible - at least one is expired so we do
1582 * as many as we can.
1583 */
1584 private void queueReadyJobsForExecutionLocked() {
1585 if (DEBUG) {
1586 Slog.d(TAG, "queuing all ready jobs for execution:");
1587 }
1588 noteJobsNonpending(mPendingJobs);
1589 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001590 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001591 mJobs.forEachJob(mReadyQueueFunctor);
1592 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001593
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001594 if (DEBUG) {
1595 final int queuedJobs = mPendingJobs.size();
1596 if (queuedJobs == 0) {
1597 Slog.d(TAG, "No jobs pending.");
1598 } else {
1599 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001600 }
1601 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001602 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001603
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001604 final class ReadyJobQueueFunctor implements JobStatusFunctor {
1605 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001606
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001607 @Override
1608 public void process(JobStatus job) {
1609 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001610 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001611 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001612 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001613 if (newReadyJobs == null) {
1614 newReadyJobs = new ArrayList<JobStatus>();
1615 }
1616 newReadyJobs.add(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001617 }
1618 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001619
1620 public void postProcess() {
1621 if (newReadyJobs != null) {
1622 noteJobsPending(newReadyJobs);
1623 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001624 if (mPendingJobs.size() > 1) {
1625 mPendingJobs.sort(mEnqueueTimeComparator);
1626 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001627 }
1628 newReadyJobs = null;
1629 }
1630 }
1631 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1632
1633 /**
1634 * The state of at least one job has changed. Here is where we could enforce various
1635 * policies on when we want to execute jobs.
1636 * Right now the policy is such:
1637 * If >1 of the ready jobs is idle mode we send all of them off
1638 * if more than 2 network connectivity jobs are ready we send them all off.
1639 * If more than 4 jobs total are ready we send them all off.
1640 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
1641 */
1642 final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
1643 int chargingCount;
1644 int batteryNotLowCount;
1645 int storageNotLowCount;
1646 int idleCount;
1647 int backoffCount;
1648 int connectivityCount;
1649 int contentCount;
1650 List<JobStatus> runnableJobs;
1651
1652 public MaybeReadyJobQueueFunctor() {
1653 reset();
1654 }
1655
1656 // Functor method invoked for each job via JobStore.forEachJob()
1657 @Override
1658 public void process(JobStatus job) {
1659 if (isReadyToBeExecutedLocked(job)) {
1660 try {
1661 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1662 job.getJob().getService().getPackageName())) {
1663 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1664 + job.getJob().toString() + " -- package not allowed to start");
1665 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1666 return;
1667 }
1668 } catch (RemoteException e) {
1669 }
1670 if (job.getNumFailures() > 0) {
1671 backoffCount++;
1672 }
1673 if (job.hasIdleConstraint()) {
1674 idleCount++;
1675 }
1676 if (job.hasConnectivityConstraint()) {
1677 connectivityCount++;
1678 }
1679 if (job.hasChargingConstraint()) {
1680 chargingCount++;
1681 }
1682 if (job.hasBatteryNotLowConstraint()) {
1683 batteryNotLowCount++;
1684 }
1685 if (job.hasStorageNotLowConstraint()) {
1686 storageNotLowCount++;
1687 }
1688 if (job.hasContentTriggerConstraint()) {
1689 contentCount++;
1690 }
1691 if (runnableJobs == null) {
1692 runnableJobs = new ArrayList<>();
1693 }
1694 runnableJobs.add(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001695 }
1696 }
1697
1698 public void postProcess() {
1699 if (backoffCount > 0 ||
1700 idleCount >= mConstants.MIN_IDLE_COUNT ||
1701 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1702 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1703 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1704 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1705 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1706 (runnableJobs != null
1707 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1708 if (DEBUG) {
1709 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1710 }
1711 noteJobsPending(runnableJobs);
1712 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001713 if (mPendingJobs.size() > 1) {
1714 mPendingJobs.sort(mEnqueueTimeComparator);
1715 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001716 } else {
1717 if (DEBUG) {
1718 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
1719 }
1720 }
1721
1722 // Be ready for next time
1723 reset();
1724 }
1725
1726 private void reset() {
1727 chargingCount = 0;
1728 idleCount = 0;
1729 backoffCount = 0;
1730 connectivityCount = 0;
1731 batteryNotLowCount = 0;
1732 storageNotLowCount = 0;
1733 contentCount = 0;
1734 runnableJobs = null;
1735 }
1736 }
1737 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
1738
1739 private void maybeQueueReadyJobsForExecutionLocked() {
1740 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
1741
1742 noteJobsNonpending(mPendingJobs);
1743 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001744 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001745 mJobs.forEachJob(mMaybeQueueFunctor);
1746 mMaybeQueueFunctor.postProcess();
1747 }
1748
Christopher Tated1aebb32018-01-31 13:24:14 -08001749 /**
1750 * Heartbeat tracking. The heartbeat alarm is intentionally non-wakeup.
1751 */
1752 class HeartbeatAlarmListener implements AlarmManager.OnAlarmListener {
1753
1754 @Override
1755 public void onAlarm() {
1756 synchronized (mLock) {
1757 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
1758 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
1759 if (beatsElapsed > 0) {
1760 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
1761 advanceHeartbeatLocked(beatsElapsed);
1762 }
Christopher Tatea732f012017-10-26 17:26:53 -07001763 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001764 setNextHeartbeatAlarm();
Christopher Tatea732f012017-10-26 17:26:53 -07001765 }
Christopher Tatea732f012017-10-26 17:26:53 -07001766 }
1767
Christopher Tated1aebb32018-01-31 13:24:14 -08001768 // Intentionally does not touch the alarm timing
1769 void advanceHeartbeatLocked(long beatsElapsed) {
1770 mHeartbeat += beatsElapsed;
1771 if (DEBUG_STANDBY) {
1772 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed
1773 + " to " + mHeartbeat);
1774 }
1775 // Don't update ACTIVE or NEVER bucket milestones. Note that mHeartbeat
1776 // will be equal to mNextBucketHeartbeat[bucket] for one beat, during which
1777 // new jobs scheduled by apps in that bucket will be permitted to run
1778 // immediately.
1779 boolean didAdvanceBucket = false;
Christopher Tatea732f012017-10-26 17:26:53 -07001780 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
Christopher Tated1aebb32018-01-31 13:24:14 -08001781 // Did we reach or cross a bucket boundary?
1782 if (mHeartbeat >= mNextBucketHeartbeat[i]) {
1783 didAdvanceBucket = true;
1784 }
1785 while (mHeartbeat > mNextBucketHeartbeat[i]) {
Christopher Tatea732f012017-10-26 17:26:53 -07001786 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
1787 }
1788 if (DEBUG_STANDBY) {
Christopher Tated1aebb32018-01-31 13:24:14 -08001789 Slog.v(TAG, " Bucket " + i + " next heartbeat "
1790 + mNextBucketHeartbeat[i]);
Christopher Tatea732f012017-10-26 17:26:53 -07001791 }
1792 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001793
1794 if (didAdvanceBucket) {
1795 if (DEBUG_STANDBY) {
1796 Slog.v(TAG, "Hit bucket boundary; reevaluating job runnability");
1797 }
1798 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1799 }
1800 }
1801
1802 void setNextHeartbeatAlarm() {
1803 final long heartbeatLength;
1804 synchronized (mLock) {
1805 heartbeatLength = mConstants.STANDBY_HEARTBEAT_TIME;
1806 }
1807 final long now = sElapsedRealtimeClock.millis();
1808 final long nextBeatOrdinal = (now + heartbeatLength) / heartbeatLength;
1809 final long nextHeartbeat = nextBeatOrdinal * heartbeatLength;
1810 if (DEBUG_STANDBY) {
1811 Slog.i(TAG, "Setting heartbeat alarm for " + nextHeartbeat
1812 + " = " + TimeUtils.formatDuration(nextHeartbeat - now));
1813 }
1814 AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1815 am.setExact(AlarmManager.ELAPSED_REALTIME, nextHeartbeat,
1816 HEARTBEAT_TAG, mHeartbeatAlarm, mHandler);
Christopher Tatea732f012017-10-26 17:26:53 -07001817 }
1818
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001819 /**
1820 * Criteria for moving a job into the pending queue:
1821 * - It's ready.
1822 * - It's not pending.
1823 * - It's not already running on a JSC.
1824 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07001825 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001826 * - The component is enabled and runnable.
1827 */
1828 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001829 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001830
1831 if (DEBUG) {
1832 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1833 + " ready=" + jobReady);
1834 }
1835
1836 // This is a condition that is very likely to be false (most jobs that are
1837 // scheduled are sitting there, not ready yet) and very cheap to check (just
1838 // a few conditions on data in JobStatus).
1839 if (!jobReady) {
1840 return false;
1841 }
1842
1843 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001844
1845 final int userId = job.getUserId();
1846 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
1847
1848 if (DEBUG) {
1849 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001850 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001851 }
1852
Dianne Hackborn28d1b662017-04-21 14:17:23 -07001853 // These are also fairly cheap to check, though they typically will not
1854 // be conditions we fail.
1855 if (!jobExists || !userStarted) {
1856 return false;
1857 }
1858
1859 final boolean jobPending = mPendingJobs.contains(job);
1860 final boolean jobActive = isCurrentlyActiveLocked(job);
1861
1862 if (DEBUG) {
1863 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1864 + " pending=" + jobPending + " active=" + jobActive);
1865 }
1866
1867 // These can be a little more expensive (especially jobActive, since we need to
1868 // go through the array of all potentially active jobs), so we are doing them
1869 // later... but still before checking with the package manager!
1870 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001871 return false;
1872 }
1873
Christopher Tatea732f012017-10-26 17:26:53 -07001874 // If the app is in a non-active standby bucket, make sure we've waited
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001875 // an appropriate amount of time since the last invocation. During device-
1876 // wide parole, standby bucketing is ignored.
Makoto Onuki959acb52018-01-26 14:10:03 -08001877 //
1878 // But if a job has FLAG_EXEMPT_FROM_APP_STANDBY, don't check it.
1879 if (!mInParole && !job.getJob().isExemptedFromAppStandby()) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001880 final int bucket = job.getStandbyBucket();
1881 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
Christopher Tated1aebb32018-01-31 13:24:14 -08001882 // Only skip this job if the app is still waiting for the end of its nominal
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001883 // bucket interval. Once it's waited that long, we let it go ahead and clear.
1884 // The final (NEVER) bucket is special; we never age those apps' jobs into
1885 // runnability.
Christopher Tated1aebb32018-01-31 13:24:14 -08001886 final long appLastRan = heartbeatWhenJobsLastRun(job);
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001887 if (bucket >= mConstants.STANDBY_BEATS.length
Christopher Tated1aebb32018-01-31 13:24:14 -08001888 || (mHeartbeat > appLastRan
1889 && mHeartbeat < appLastRan + mConstants.STANDBY_BEATS[bucket])) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001890 // TODO: log/trace that we're deferring the job due to bucketing if we hit this
1891 if (job.getWhenStandbyDeferred() == 0) {
1892 if (DEBUG_STANDBY) {
1893 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
Christopher Tated1aebb32018-01-31 13:24:14 -08001894 + (appLastRan + mConstants.STANDBY_BEATS[bucket])
1895 + " for " + job);
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001896 }
1897 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tate0c4d7682017-12-06 15:10:22 -08001898 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08001899 return false;
1900 } else {
1901 if (DEBUG_STANDBY) {
1902 Slog.v(TAG, "Bucket deferred job aged into runnability at "
1903 + mHeartbeat + " : " + job);
1904 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08001905 }
Christopher Tatea732f012017-10-26 17:26:53 -07001906 }
Christopher Tatea732f012017-10-26 17:26:53 -07001907 }
1908
1909 // The expensive check last: validate that the defined package+service is
1910 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001911 final boolean componentPresent;
1912 try {
1913 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
1914 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1915 userId) != null);
1916 } catch (RemoteException e) {
1917 throw e.rethrowAsRuntimeException();
1918 }
1919
1920 if (DEBUG) {
1921 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
1922 + " componentPresent=" + componentPresent);
1923 }
1924
1925 // Everything else checked out so far, so this is the final yes/no check
1926 return componentPresent;
1927 }
1928
1929 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001930 * Reconcile jobs in the pending queue against available execution contexts.
1931 * A controller can force a job into the pending queue even if it's already running, but
1932 * here is where we decide whether to actually execute it.
1933 */
1934 private void maybeRunPendingJobsLocked() {
1935 if (DEBUG) {
1936 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
1937 }
1938 assignJobsToContextsLocked();
1939 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001940 }
1941
Dianne Hackborn807de782016-04-07 17:54:41 -07001942 private int adjustJobPriority(int curPriority, JobStatus job) {
1943 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
1944 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001945 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001946 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001947 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001948 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
1949 }
1950 }
1951 return curPriority;
1952 }
1953
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001954 private int evaluateJobPriorityLocked(JobStatus job) {
1955 int priority = job.getPriority();
1956 if (priority >= JobInfo.PRIORITY_FOREGROUND_APP) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001957 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001958 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08001959 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
1960 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001961 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001962 }
Dianne Hackborn807de782016-04-07 17:54:41 -07001963 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001964 }
1965
Christopher Tate7060b042014-06-09 19:50:00 -07001966 /**
Shreyas Basarge5db09082016-01-07 13:38:29 +00001967 * Takes jobs from pending queue and runs them on available contexts.
1968 * If no contexts are available, preempts lower priority jobs to
1969 * run higher priority ones.
1970 * Lock on mJobs before calling this function.
1971 */
Dianne Hackbornb0001f62016-02-16 10:30:33 -08001972 private void assignJobsToContextsLocked() {
Shreyas Basarge5db09082016-01-07 13:38:29 +00001973 if (DEBUG) {
1974 Slog.d(TAG, printPendingQueue());
1975 }
1976
Dianne Hackborn970510b2016-02-24 16:56:42 -08001977 int memLevel;
1978 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001979 memLevel = ActivityManager.getService().getMemoryTrimLevel();
Dianne Hackborn970510b2016-02-24 16:56:42 -08001980 } catch (RemoteException e) {
1981 memLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1982 }
1983 switch (memLevel) {
1984 case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001985 mMaxActiveJobs = mConstants.BG_MODERATE_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001986 break;
1987 case ProcessStats.ADJ_MEM_FACTOR_LOW:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001988 mMaxActiveJobs = mConstants.BG_LOW_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001989 break;
1990 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001991 mMaxActiveJobs = mConstants.BG_CRITICAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001992 break;
1993 default:
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001994 mMaxActiveJobs = mConstants.BG_NORMAL_JOB_COUNT;
Dianne Hackborn970510b2016-02-24 16:56:42 -08001995 break;
1996 }
1997
1998 JobStatus[] contextIdToJobMap = mTmpAssignContextIdToJobMap;
1999 boolean[] act = mTmpAssignAct;
2000 int[] preferredUidForContext = mTmpAssignPreferredUidForContext;
2001 int numActive = 0;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002002 int numForeground = 0;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002003 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
2004 final JobServiceContext js = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002005 final JobStatus status = js.getRunningJobLocked();
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002006 if ((contextIdToJobMap[i] = status) != null) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08002007 numActive++;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002008 if (status.lastEvaluatedPriority >= JobInfo.PRIORITY_TOP_APP) {
2009 numForeground++;
2010 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002011 }
2012 act[i] = false;
2013 preferredUidForContext[i] = js.getPreferredUid();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002014 }
2015 if (DEBUG) {
2016 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs initial"));
2017 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002018 for (int i=0; i<mPendingJobs.size(); i++) {
2019 JobStatus nextPending = mPendingJobs.get(i);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002020
2021 // If job is already running, go to next job.
2022 int jobRunningContext = findJobContextIdFromMap(nextPending, contextIdToJobMap);
2023 if (jobRunningContext != -1) {
2024 continue;
2025 }
2026
Dianne Hackborn970510b2016-02-24 16:56:42 -08002027 final int priority = evaluateJobPriorityLocked(nextPending);
2028 nextPending.lastEvaluatedPriority = priority;
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002029
Shreyas Basarge5db09082016-01-07 13:38:29 +00002030 // Find a context for nextPending. The context should be available OR
2031 // it should have lowest priority among all running jobs
2032 // (sharing the same Uid as nextPending)
2033 int minPriority = Integer.MAX_VALUE;
2034 int minPriorityContextId = -1;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002035 for (int j=0; j<MAX_JOB_CONTEXTS_COUNT; j++) {
2036 JobStatus job = contextIdToJobMap[j];
2037 int preferredUid = preferredUidForContext[j];
Shreyas Basarge347c2782016-01-15 18:24:36 +00002038 if (job == null) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002039 if ((numActive < mMaxActiveJobs ||
2040 (priority >= JobInfo.PRIORITY_TOP_APP &&
2041 numForeground < mConstants.FG_JOB_COUNT)) &&
Dianne Hackborn970510b2016-02-24 16:56:42 -08002042 (preferredUid == nextPending.getUid() ||
2043 preferredUid == JobServiceContext.NO_PREFERRED_UID)) {
2044 // This slot is free, and we haven't yet hit the limit on
2045 // concurrent jobs... we can just throw the job in to here.
2046 minPriorityContextId = j;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002047 break;
2048 }
Shreyas Basarge347c2782016-01-15 18:24:36 +00002049 // No job on this context, but nextPending can't run here because
Dianne Hackborn970510b2016-02-24 16:56:42 -08002050 // the context has a preferred Uid or we have reached the limit on
2051 // concurrent jobs.
Shreyas Basarge347c2782016-01-15 18:24:36 +00002052 continue;
2053 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002054 if (job.getUid() != nextPending.getUid()) {
2055 continue;
2056 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002057 if (evaluateJobPriorityLocked(job) >= nextPending.lastEvaluatedPriority) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002058 continue;
2059 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002060 if (minPriority > nextPending.lastEvaluatedPriority) {
2061 minPriority = nextPending.lastEvaluatedPriority;
Dianne Hackborn970510b2016-02-24 16:56:42 -08002062 minPriorityContextId = j;
Shreyas Basarge5db09082016-01-07 13:38:29 +00002063 }
2064 }
2065 if (minPriorityContextId != -1) {
2066 contextIdToJobMap[minPriorityContextId] = nextPending;
2067 act[minPriorityContextId] = true;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002068 numActive++;
2069 if (priority >= JobInfo.PRIORITY_TOP_APP) {
2070 numForeground++;
2071 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002072 }
2073 }
2074 if (DEBUG) {
2075 Slog.d(TAG, printContextIdToJobMap(contextIdToJobMap, "running jobs final"));
2076 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002077 mJobPackageTracker.noteConcurrency(numActive, numForeground);
Dianne Hackborn970510b2016-02-24 16:56:42 -08002078 for (int i=0; i<MAX_JOB_CONTEXTS_COUNT; i++) {
Shreyas Basarge5db09082016-01-07 13:38:29 +00002079 boolean preservePreferredUid = false;
2080 if (act[i]) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002081 JobStatus js = mActiveServices.get(i).getRunningJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002082 if (js != null) {
2083 if (DEBUG) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002084 Slog.d(TAG, "preempting job: " + mActiveServices.get(i).getRunningJobLocked());
Shreyas Basarge5db09082016-01-07 13:38:29 +00002085 }
2086 // preferredUid will be set to uid of currently running job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07002087 mActiveServices.get(i).preemptExecutingJobLocked();
Shreyas Basarge5db09082016-01-07 13:38:29 +00002088 preservePreferredUid = true;
2089 } else {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002090 final JobStatus pendingJob = contextIdToJobMap[i];
Shreyas Basarge5db09082016-01-07 13:38:29 +00002091 if (DEBUG) {
2092 Slog.d(TAG, "About to run job on context "
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002093 + String.valueOf(i) + ", job: " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002094 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002095 for (int ic=0; ic<mControllers.size(); ic++) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002096 mControllers.get(ic).prepareForExecutionLocked(pendingJob);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08002097 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002098 if (!mActiveServices.get(i).executeRunnableJob(pendingJob)) {
2099 Slog.d(TAG, "Error executing " + pendingJob);
Shreyas Basarge5db09082016-01-07 13:38:29 +00002100 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002101 if (mPendingJobs.remove(pendingJob)) {
2102 mJobPackageTracker.noteNonpending(pendingJob);
2103 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002104 }
2105 }
2106 if (!preservePreferredUid) {
2107 mActiveServices.get(i).clearPreferredUid();
2108 }
2109 }
2110 }
2111
2112 int findJobContextIdFromMap(JobStatus jobStatus, JobStatus[] map) {
2113 for (int i=0; i<map.length; i++) {
2114 if (map[i] != null && map[i].matches(jobStatus.getUid(), jobStatus.getJobId())) {
2115 return i;
2116 }
2117 }
2118 return -1;
2119 }
2120
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002121 final class LocalService implements JobSchedulerInternal {
2122
2123 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002124 * The current bucket heartbeat ordinal
2125 */
2126 public long currentHeartbeat() {
2127 return getCurrentHeartbeat();
2128 }
2129
2130 /**
2131 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2132 */
2133 public long nextHeartbeatForBucket(int bucket) {
2134 synchronized (mLock) {
2135 return mNextBucketHeartbeat[bucket];
2136 }
2137 }
2138
2139 /**
Christopher Tate435c2f42018-01-18 12:59:15 -08002140 * Heartbeat ordinal for the given app. This is typically the heartbeat at which
2141 * the app last ran jobs, so that a newly-scheduled job in an app that hasn't run
2142 * jobs in a long time is immediately runnable even if the app is bucketed into
2143 * an infrequent time allocation.
2144 */
2145 public long baseHeartbeatForApp(String packageName, @UserIdInt int userId,
2146 final int appStandbyBucket) {
2147 if (appStandbyBucket == 0 ||
2148 appStandbyBucket >= mConstants.STANDBY_BEATS.length) {
2149 // ACTIVE => everything can be run right away
2150 // NEVER => we won't run them anyway, so let them go in the future
2151 // as soon as the app enters normal use
Christopher Tated1aebb32018-01-31 13:24:14 -08002152 if (DEBUG_STANDBY) {
2153 Slog.v(TAG, "Base heartbeat forced ZERO for new job in "
2154 + packageName + "/" + userId);
2155 }
Christopher Tate435c2f42018-01-18 12:59:15 -08002156 return 0;
2157 }
2158
Christopher Tated1aebb32018-01-31 13:24:14 -08002159 final long baseHeartbeat = heartbeatWhenJobsLastRun(packageName, userId);
2160 if (DEBUG_STANDBY) {
2161 Slog.v(TAG, "Base heartbeat " + baseHeartbeat + " for new job in "
2162 + packageName + "/" + userId);
2163 }
2164 return baseHeartbeat;
Christopher Tate435c2f42018-01-18 12:59:15 -08002165 }
2166
2167 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002168 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2169 * jobs are always considered pending.
2170 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002171 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002172 public List<JobInfo> getSystemScheduledPendingJobs() {
2173 synchronized (mLock) {
2174 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
2175 mJobs.forEachJob(Process.SYSTEM_UID, new JobStatusFunctor() {
2176 @Override
2177 public void process(JobStatus job) {
2178 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2179 pendingJobs.add(job.getJob());
2180 }
2181 }
2182 });
2183 return pendingJobs;
2184 }
2185 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002186
2187 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002188 public void cancelJobsForUid(int uid, String reason) {
2189 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2190 }
2191
2192 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002193 public void addBackingUpUid(int uid) {
2194 synchronized (mLock) {
2195 // No need to actually do anything here, since for a full backup the
2196 // activity manager will kill the process which will kill the job (and
2197 // cause it to restart, but now it can't run).
2198 mBackingUpUids.put(uid, uid);
2199 }
2200 }
2201
2202 @Override
2203 public void removeBackingUpUid(int uid) {
2204 synchronized (mLock) {
2205 mBackingUpUids.delete(uid);
2206 // If there are any jobs for this uid, we need to rebuild the pending list
2207 // in case they are now ready to run.
2208 if (mJobs.countJobsForUid(uid) > 0) {
2209 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2210 }
2211 }
2212 }
2213
2214 @Override
2215 public void clearAllBackingUpUids() {
2216 synchronized (mLock) {
2217 if (mBackingUpUids.size() > 0) {
2218 mBackingUpUids.clear();
2219 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2220 }
2221 }
2222 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002223
2224 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002225 public void reportAppUsage(String packageName, int userId) {
2226 JobSchedulerService.this.reportAppUsage(packageName, userId);
2227 }
2228
2229 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002230 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002231 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002232 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002233 }
2234 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002235 }
2236
Shreyas Basarge5db09082016-01-07 13:38:29 +00002237 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002238 * Tracking of app assignments to standby buckets
2239 */
2240 final class StandbyTracker extends AppIdleStateChangeListener {
Christopher Tate435c2f42018-01-18 12:59:15 -08002241
Christopher Tatea732f012017-10-26 17:26:53 -07002242 // AppIdleStateChangeListener interface for live updates
2243
2244 @Override
Christopher Tate435c2f42018-01-18 12:59:15 -08002245 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Christopher Tatea732f012017-10-26 17:26:53 -07002246 boolean idle, int bucket) {
2247 final int uid = mLocalPM.getPackageUid(packageName,
2248 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2249 if (uid < 0) {
2250 if (DEBUG_STANDBY) {
2251 Slog.i(TAG, "App idle state change for unknown app "
2252 + packageName + "/" + userId);
2253 }
2254 return;
2255 }
2256
2257 final int bucketIndex = standbyBucketToBucketIndex(bucket);
2258 // update job bookkeeping out of band
2259 BackgroundThread.getHandler().post(() -> {
2260 if (DEBUG_STANDBY) {
2261 Slog.i(TAG, "Moving uid " + uid + " to bucketIndex " + bucketIndex);
2262 }
2263 synchronized (mLock) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08002264 mJobs.forEachJobForSourceUid(uid, job -> job.setStandbyBucket(bucketIndex));
Christopher Tatea732f012017-10-26 17:26:53 -07002265 onControllerStateChanged();
2266 }
2267 });
2268 }
2269
2270 @Override
2271 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002272 if (DEBUG_STANDBY) {
2273 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2274 }
2275 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002276 }
Christopher Tated117b292018-01-05 17:32:36 -08002277
2278 @Override
2279 public void onUserInteractionStarted(String packageName, int userId) {
2280 final int uid = mLocalPM.getPackageUid(packageName,
2281 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2282 if (uid < 0) {
2283 // Quietly ignore; the case is already logged elsewhere
2284 return;
2285 }
2286
Amith Yamasani977e11f2018-02-16 11:29:54 -08002287 long sinceLast = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2288 if (sinceLast > 2 * DateUtils.DAY_IN_MILLIS) {
2289 // Too long ago, not worth logging
2290 sinceLast = 0L;
2291 }
Christopher Tated117b292018-01-05 17:32:36 -08002292 final DeferredJobCounter counter = new DeferredJobCounter();
2293 synchronized (mLock) {
2294 mJobs.forEachJobForSourceUid(uid, counter);
2295 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08002296 if (counter.numDeferred() > 0 || sinceLast > 0) {
2297 BatteryStatsInternal mBatteryStatsInternal = LocalServices.getService
2298 (BatteryStatsInternal.class);
2299 mBatteryStatsInternal.noteJobsDeferred(uid, counter.numDeferred(), sinceLast);
2300 }
Christopher Tated117b292018-01-05 17:32:36 -08002301 }
2302 }
2303
2304 static class DeferredJobCounter implements JobStatusFunctor {
2305 private int mDeferred = 0;
2306
2307 public int numDeferred() {
2308 return mDeferred;
2309 }
2310
2311 @Override
2312 public void process(JobStatus job) {
2313 if (job.getWhenStandbyDeferred() > 0) {
2314 mDeferred++;
2315 }
2316 }
Christopher Tatea732f012017-10-26 17:26:53 -07002317 }
2318
2319 public static int standbyBucketToBucketIndex(int bucket) {
2320 // Normalize AppStandby constants to indices into our bookkeeping
Amith Yamasaniafbccb72017-11-27 10:44:24 -08002321 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return 4;
2322 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) return 3;
2323 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) return 2;
2324 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return 1;
Christopher Tatea732f012017-10-26 17:26:53 -07002325 else return 0;
2326 }
2327
Christopher Tated1aebb32018-01-31 13:24:14 -08002328 // Static to support external callers
Christopher Tatea732f012017-10-26 17:26:53 -07002329 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2330 UsageStatsManagerInternal usageStats = LocalServices.getService(
2331 UsageStatsManagerInternal.class);
2332 int bucket = usageStats != null
2333 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2334 : 0;
2335
2336 bucket = standbyBucketToBucketIndex(bucket);
2337
2338 if (DEBUG_STANDBY) {
2339 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2340 }
2341 return bucket;
2342 }
2343
2344 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002345 * Binder stub trampoline implementation
2346 */
2347 final class JobSchedulerStub extends IJobScheduler.Stub {
2348 /** Cache determination of whether a given app can persist jobs
2349 * key is uid of the calling app; value is undetermined/true/false
2350 */
2351 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2352
2353 // Enforce that only the app itself (or shared uid participant) can schedule a
2354 // job that runs one of the app's services, as well as verifying that the
2355 // named service properly requires the BIND_JOB_SERVICE permission
2356 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002357 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002358 final ComponentName service = job.getService();
2359 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002360 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002361 PackageManager.MATCH_DIRECT_BOOT_AWARE
2362 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002363 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002364 if (si == null) {
2365 throw new IllegalArgumentException("No such service " + service);
2366 }
Christopher Tate7060b042014-06-09 19:50:00 -07002367 if (si.applicationInfo.uid != uid) {
2368 throw new IllegalArgumentException("uid " + uid +
2369 " cannot schedule job in " + service.getPackageName());
2370 }
2371 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2372 throw new IllegalArgumentException("Scheduled service " + service
2373 + " does not require android.permission.BIND_JOB_SERVICE permission");
2374 }
Christopher Tate5568f542014-06-18 13:53:31 -07002375 } catch (RemoteException e) {
2376 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002377 }
2378 }
2379
2380 private boolean canPersistJobs(int pid, int uid) {
2381 // If we get this far we're good to go; all we need to do now is check
2382 // whether the app is allowed to persist its scheduled work.
2383 final boolean canPersist;
2384 synchronized (mPersistCache) {
2385 Boolean cached = mPersistCache.get(uid);
2386 if (cached != null) {
2387 canPersist = cached.booleanValue();
2388 } else {
2389 // Persisting jobs is tantamount to running at boot, so we permit
2390 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2391 // permission
2392 int result = getContext().checkPermission(
2393 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2394 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2395 mPersistCache.put(uid, canPersist);
2396 }
2397 }
2398 return canPersist;
2399 }
2400
Makoto Onuki959acb52018-01-26 14:10:03 -08002401 private void validateJobFlags(JobInfo job, int callingUid) {
2402 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2403 getContext().enforceCallingOrSelfPermission(
2404 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2405 }
2406 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
2407 if (callingUid != Process.SYSTEM_UID) {
2408 throw new SecurityException("Job has invalid flags");
2409 }
Makoto Onuki2b5811a2018-02-08 11:09:42 -08002410 if (job.isPeriodic()) {
2411 Slog.wtf(TAG, "Periodic jobs mustn't have"
2412 + " FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
Makoto Onuki959acb52018-01-26 14:10:03 -08002413 }
2414 }
2415 }
2416
Christopher Tate7060b042014-06-09 19:50:00 -07002417 // IJobScheduler implementation
2418 @Override
2419 public int schedule(JobInfo job) throws RemoteException {
2420 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002421 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002422 }
2423 final int pid = Binder.getCallingPid();
2424 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002425 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002426
2427 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002428 if (job.isPersisted()) {
2429 if (!canPersistJobs(pid, uid)) {
2430 throw new IllegalArgumentException("Error: requested job be persisted without"
2431 + " holding RECEIVE_BOOT_COMPLETED permission.");
2432 }
2433 }
Christopher Tate7060b042014-06-09 19:50:00 -07002434
Makoto Onuki959acb52018-01-26 14:10:03 -08002435 validateJobFlags(job, uid);
Jeff Sharkey785f4942016-07-14 10:31:15 -06002436
Christopher Tate7060b042014-06-09 19:50:00 -07002437 long ident = Binder.clearCallingIdentity();
2438 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002439 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2440 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002441 } finally {
2442 Binder.restoreCallingIdentity(ident);
2443 }
2444 }
2445
2446 // IJobScheduler implementation
2447 @Override
2448 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2449 if (DEBUG) {
2450 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2451 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002452 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002453 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002454
2455 enforceValidJobRequest(uid, job);
2456 if (job.isPersisted()) {
2457 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2458 }
2459 if (work == null) {
2460 throw new NullPointerException("work is null");
2461 }
2462
Makoto Onuki959acb52018-01-26 14:10:03 -08002463 validateJobFlags(job, uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002464
2465 long ident = Binder.clearCallingIdentity();
2466 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002467 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2468 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002469 } finally {
2470 Binder.restoreCallingIdentity(ident);
2471 }
2472 }
2473
2474 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002475 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002476 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002477 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002478 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002479 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002480 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002481 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002482
2483 if (packageName == null) {
2484 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002485 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002486
2487 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2488 android.Manifest.permission.UPDATE_DEVICE_STATS);
2489 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2490 throw new SecurityException("Caller uid " + callerUid
2491 + " not permitted to schedule jobs for other apps");
2492 }
2493
Makoto Onuki959acb52018-01-26 14:10:03 -08002494 validateJobFlags(job, callerUid);
Jeff Sharkey4f100402016-05-03 17:44:23 -06002495
Shreyas Basarge968ac752016-01-11 23:09:26 +00002496 long ident = Binder.clearCallingIdentity();
2497 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002498 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002499 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002500 } finally {
2501 Binder.restoreCallingIdentity(ident);
2502 }
2503 }
2504
2505 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002506 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2507 final int uid = Binder.getCallingUid();
2508
2509 long ident = Binder.clearCallingIdentity();
2510 try {
2511 return JobSchedulerService.this.getPendingJobs(uid);
2512 } finally {
2513 Binder.restoreCallingIdentity(ident);
2514 }
2515 }
2516
2517 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002518 public JobInfo getPendingJob(int jobId) throws RemoteException {
2519 final int uid = Binder.getCallingUid();
2520
2521 long ident = Binder.clearCallingIdentity();
2522 try {
2523 return JobSchedulerService.this.getPendingJob(uid, jobId);
2524 } finally {
2525 Binder.restoreCallingIdentity(ident);
2526 }
2527 }
2528
2529 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002530 public void cancelAll() throws RemoteException {
2531 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002532 long ident = Binder.clearCallingIdentity();
2533 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002534 JobSchedulerService.this.cancelJobsForUid(uid,
2535 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002536 } finally {
2537 Binder.restoreCallingIdentity(ident);
2538 }
2539 }
2540
2541 @Override
2542 public void cancel(int jobId) throws RemoteException {
2543 final int uid = Binder.getCallingUid();
2544
2545 long ident = Binder.clearCallingIdentity();
2546 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002547 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002548 } finally {
2549 Binder.restoreCallingIdentity(ident);
2550 }
2551 }
2552
2553 /**
2554 * "dumpsys" infrastructure
2555 */
2556 @Override
2557 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002558 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002559
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002560 int filterUid = -1;
2561 boolean proto = false;
2562 if (!ArrayUtils.isEmpty(args)) {
2563 int opti = 0;
2564 while (opti < args.length) {
2565 String arg = args[opti];
2566 if ("-h".equals(arg)) {
2567 dumpHelp(pw);
2568 return;
2569 } else if ("-a".equals(arg)) {
2570 // Ignore, we always dump all.
2571 } else if ("--proto".equals(arg)) {
2572 proto = true;
2573 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2574 pw.println("Unknown option: " + arg);
2575 return;
2576 } else {
2577 break;
2578 }
2579 opti++;
2580 }
2581 if (opti < args.length) {
2582 String pkg = args[opti];
2583 try {
2584 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2585 PackageManager.MATCH_ANY_USER);
2586 } catch (NameNotFoundException ignored) {
2587 pw.println("Invalid package: " + pkg);
2588 return;
2589 }
2590 }
2591 }
2592
Christopher Tate7060b042014-06-09 19:50:00 -07002593 long identityToken = Binder.clearCallingIdentity();
2594 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002595 if (proto) {
2596 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2597 } else {
2598 JobSchedulerService.this.dumpInternal(pw, filterUid);
2599 }
Christopher Tate7060b042014-06-09 19:50:00 -07002600 } finally {
2601 Binder.restoreCallingIdentity(identityToken);
2602 }
2603 }
Christopher Tate5d346052016-03-08 12:56:08 -08002604
2605 @Override
2606 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002607 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002608 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002609 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002610 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002611 };
2612
Christopher Tate5d346052016-03-08 12:56:08 -08002613 // Shell command infrastructure: run the given job immediately
2614 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2615 if (DEBUG) {
2616 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2617 + " " + jobId + " f=" + force);
2618 }
2619
2620 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002621 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2622 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002623 if (uid < 0) {
2624 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2625 }
2626
2627 synchronized (mLock) {
2628 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2629 if (js == null) {
2630 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2631 }
2632
2633 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2634 if (!js.isConstraintsSatisfied()) {
2635 js.overrideState = 0;
2636 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2637 }
2638
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002639 queueReadyJobsForExecutionLocked();
2640 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002641 }
2642 } catch (RemoteException e) {
2643 // can't happen
2644 }
2645 return 0;
2646 }
2647
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002648 // Shell command infrastructure: immediately timeout currently executing jobs
2649 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2650 boolean hasJobId, int jobId) {
2651 if (DEBUG) {
2652 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2653 }
2654
2655 synchronized (mLock) {
2656 boolean foundSome = false;
2657 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002658 final JobServiceContext jc = mActiveServices.get(i);
2659 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002660 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002661 foundSome = true;
2662 pw.print("Timing out: ");
2663 js.printUniqueId(pw);
2664 pw.print(" ");
2665 pw.println(js.getServiceComponent().flattenToShortString());
2666 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002667 }
2668 if (!foundSome) {
2669 pw.println("No matching executing jobs found.");
2670 }
2671 }
2672 return 0;
2673 }
2674
Christopher Tate8c67d122017-09-29 16:54:26 -07002675 // Shell command infrastructure: cancel a scheduled job
2676 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2677 boolean hasJobId, int jobId) {
2678 if (DEBUG) {
2679 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2680 }
2681
2682 int pkgUid = -1;
2683 try {
2684 IPackageManager pm = AppGlobals.getPackageManager();
2685 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2686 } catch (RemoteException e) { /* can't happen */ }
2687
2688 if (pkgUid < 0) {
2689 pw.println("Package " + pkgName + " not found.");
2690 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2691 }
2692
2693 if (!hasJobId) {
2694 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2695 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2696 pw.println("No matching jobs found.");
2697 }
2698 } else {
2699 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002700 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002701 pw.println("No matching job found.");
2702 }
2703 }
2704
2705 return 0;
2706 }
2707
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002708 void setMonitorBattery(boolean enabled) {
2709 synchronized (mLock) {
2710 if (mBatteryController != null) {
2711 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2712 }
2713 }
2714 }
2715
2716 int getBatterySeq() {
2717 synchronized (mLock) {
2718 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2719 }
2720 }
2721
2722 boolean getBatteryCharging() {
2723 synchronized (mLock) {
2724 return mBatteryController != null
2725 ? mBatteryController.getTracker().isOnStablePower() : false;
2726 }
2727 }
2728
2729 boolean getBatteryNotLow() {
2730 synchronized (mLock) {
2731 return mBatteryController != null
2732 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2733 }
2734 }
2735
Dianne Hackborn532ea262017-03-17 17:50:55 -07002736 int getStorageSeq() {
2737 synchronized (mLock) {
2738 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
2739 }
2740 }
2741
2742 boolean getStorageNotLow() {
2743 synchronized (mLock) {
2744 return mStorageController != null
2745 ? mStorageController.getTracker().isStorageNotLow() : false;
2746 }
2747 }
2748
Christopher Tatea732f012017-10-26 17:26:53 -07002749 long getCurrentHeartbeat() {
2750 synchronized (mLock) {
2751 return mHeartbeat;
2752 }
2753 }
2754
Christopher Tated1aebb32018-01-31 13:24:14 -08002755 // Shell command infrastructure
Dianne Hackborn6d068262017-05-16 13:14:37 -07002756 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
2757 try {
2758 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2759 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
2760 if (uid < 0) {
2761 pw.print("unknown("); pw.print(pkgName); pw.println(")");
2762 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2763 }
2764
2765 synchronized (mLock) {
2766 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2767 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
2768 if (js == null) {
2769 pw.print("unknown("); UserHandle.formatUid(pw, uid);
2770 pw.print("/jid"); pw.print(jobId); pw.println(")");
2771 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2772 }
2773
2774 boolean printed = false;
2775 if (mPendingJobs.contains(js)) {
2776 pw.print("pending");
2777 printed = true;
2778 }
2779 if (isCurrentlyActiveLocked(js)) {
2780 if (printed) {
2781 pw.print(" ");
2782 }
2783 printed = true;
2784 pw.println("active");
2785 }
2786 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
2787 if (printed) {
2788 pw.print(" ");
2789 }
2790 printed = true;
2791 pw.println("user-stopped");
2792 }
2793 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
2794 if (printed) {
2795 pw.print(" ");
2796 }
2797 printed = true;
2798 pw.println("backing-up");
2799 }
2800 boolean componentPresent = false;
2801 try {
2802 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2803 js.getServiceComponent(),
2804 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2805 js.getUserId()) != null);
2806 } catch (RemoteException e) {
2807 }
2808 if (!componentPresent) {
2809 if (printed) {
2810 pw.print(" ");
2811 }
2812 printed = true;
2813 pw.println("no-component");
2814 }
2815 if (js.isReady()) {
2816 if (printed) {
2817 pw.print(" ");
2818 }
2819 printed = true;
2820 pw.println("ready");
2821 }
2822 if (!printed) {
2823 pw.print("waiting");
2824 }
2825 pw.println();
2826 }
2827 } catch (RemoteException e) {
2828 // can't happen
2829 }
2830 return 0;
2831 }
2832
Christopher Tated1aebb32018-01-31 13:24:14 -08002833 // Shell command infrastructure
2834 int executeHeartbeatCommand(PrintWriter pw, int numBeats) {
2835 if (numBeats < 1) {
2836 pw.println(getCurrentHeartbeat());
2837 return 0;
2838 }
2839
2840 pw.print("Advancing standby heartbeat by ");
2841 pw.println(numBeats);
2842 synchronized (mLock) {
2843 advanceHeartbeatLocked(numBeats);
2844 }
2845 return 0;
2846 }
2847
Shreyas Basarge5db09082016-01-07 13:38:29 +00002848 private String printContextIdToJobMap(JobStatus[] map, String initial) {
2849 StringBuilder s = new StringBuilder(initial + ": ");
2850 for (int i=0; i<map.length; i++) {
2851 s.append("(")
2852 .append(map[i] == null? -1: map[i].getJobId())
2853 .append(map[i] == null? -1: map[i].getUid())
2854 .append(")" );
2855 }
2856 return s.toString();
2857 }
2858
2859 private String printPendingQueue() {
2860 StringBuilder s = new StringBuilder("Pending queue: ");
2861 Iterator<JobStatus> it = mPendingJobs.iterator();
2862 while (it.hasNext()) {
2863 JobStatus js = it.next();
2864 s.append("(")
2865 .append(js.getJob().getId())
2866 .append(", ")
2867 .append(js.getUid())
2868 .append(") ");
2869 }
2870 return s.toString();
Jeff Sharkey5217cac2015-12-20 15:34:01 -07002871 }
Christopher Tate7060b042014-06-09 19:50:00 -07002872
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002873 static void dumpHelp(PrintWriter pw) {
2874 pw.println("Job Scheduler (jobscheduler) dump options:");
2875 pw.println(" [-h] [package] ...");
2876 pw.println(" -h: print this help");
2877 pw.println(" [package] is an optional package name to limit the output to.");
2878 }
2879
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002880 /** Sort jobs by caller UID, then by Job ID. */
2881 private static void sortJobs(List<JobStatus> jobs) {
2882 Collections.sort(jobs, new Comparator<JobStatus>() {
2883 @Override
2884 public int compare(JobStatus o1, JobStatus o2) {
2885 int uid1 = o1.getUid();
2886 int uid2 = o2.getUid();
2887 int id1 = o1.getJobId();
2888 int id2 = o2.getJobId();
2889 if (uid1 != uid2) {
2890 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002891 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002892 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002893 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002894 });
2895 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002896
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002897 void dumpInternal(final PrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002898 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07002899 final long nowElapsed = sElapsedRealtimeClock.millis();
2900 final long nowUptime = sUptimeMillisClock.millis();
Dianne Hackborn33d31c52016-02-16 10:30:33 -08002901 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002902 mConstants.dump(pw);
2903 pw.println();
Jeff Sharkey822cbd12016-02-25 11:09:55 -07002904 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002905 pw.print("Registered ");
2906 pw.print(mJobs.size());
2907 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07002908 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002909 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002910 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002911 for (JobStatus job : jobs) {
2912 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
2913 pw.println(job.toShortStringExceptUniqueId());
2914
2915 // Skip printing details if the caller requested a filter
2916 if (!job.shouldDump(filterUidFinal)) {
2917 continue;
2918 }
2919
Dianne Hackborn6d068262017-05-16 13:14:37 -07002920 job.dump(pw, " ", true, nowElapsed);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002921 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002922 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002923 pw.print(" (job=");
2924 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002925 pw.print(" user=");
2926 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002927 pw.print(" !pending=");
2928 pw.print(!mPendingJobs.contains(job));
2929 pw.print(" !active=");
2930 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002931 pw.print(" !backingup=");
2932 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07002933 pw.print(" comp=");
2934 boolean componentPresent = false;
2935 try {
2936 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2937 job.getServiceComponent(),
2938 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2939 job.getUserId()) != null);
2940 } catch (RemoteException e) {
2941 }
2942 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002943 pw.println(")");
2944 }
Christopher Tate7060b042014-06-09 19:50:00 -07002945 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07002946 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07002947 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07002948 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07002949 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002950 mControllers.get(i).dumpControllerStateLocked(pw, filterUidFinal);
Christopher Tate7060b042014-06-09 19:50:00 -07002951 }
2952 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08002953 pw.println("Uid priority overrides:");
2954 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002955 int uid = mUidPriorityOverride.keyAt(i);
2956 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2957 pw.print(" "); pw.print(UserHandle.formatUid(uid));
2958 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
2959 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002960 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002961 if (mBackingUpUids.size() > 0) {
2962 pw.println();
2963 pw.println("Backing up uids:");
2964 boolean first = true;
2965 for (int i = 0; i < mBackingUpUids.size(); i++) {
2966 int uid = mBackingUpUids.keyAt(i);
2967 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
2968 if (first) {
2969 pw.print(" ");
2970 first = false;
2971 } else {
2972 pw.print(", ");
2973 }
2974 pw.print(UserHandle.formatUid(uid));
2975 }
2976 }
2977 pw.println();
2978 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002979 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002980 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07002981 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07002982 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
2983 pw.println();
2984 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002985 pw.println("Pending queue:");
2986 for (int i=0; i<mPendingJobs.size(); i++) {
2987 JobStatus job = mPendingJobs.get(i);
2988 pw.print(" Pending #"); pw.print(i); pw.print(": ");
2989 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07002990 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002991 int priority = evaluateJobPriorityLocked(job);
2992 if (priority != JobInfo.PRIORITY_DEFAULT) {
2993 pw.print(" Evaluated priority: "); pw.println(priority);
2994 }
2995 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07002996 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002997 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002998 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002999 }
Christopher Tate7060b042014-06-09 19:50:00 -07003000 pw.println();
3001 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003002 for (int i=0; i<mActiveServices.size(); i++) {
3003 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003004 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003005 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07003006 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07003007 if (jsc.mStoppedReason != null) {
3008 pw.print("inactive since ");
3009 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
3010 pw.print(", stopped because: ");
3011 pw.println(jsc.mStoppedReason);
3012 } else {
3013 pw.println("inactive");
3014 }
Christopher Tate7060b042014-06-09 19:50:00 -07003015 continue;
3016 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07003017 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08003018 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003019 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003020 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003021 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003022 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07003023 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003024 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003025 if (priority != JobInfo.PRIORITY_DEFAULT) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08003026 pw.print(" Evaluated priority: "); pw.println(priority);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003027 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003028 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003029 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003030 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07003031 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
3032 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07003033 }
3034 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003035 if (filterUid == -1) {
3036 pw.println();
3037 pw.print("mReadyToRock="); pw.println(mReadyToRock);
3038 pw.print("mReportedActive="); pw.println(mReportedActive);
3039 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
3040 }
Makoto Onukie7b02982017-08-24 14:23:36 -07003041 pw.println();
3042 pw.print("PersistStats: ");
3043 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07003044 }
3045 pw.println();
3046 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003047
3048 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
3049 ProtoOutputStream proto = new ProtoOutputStream(fd);
3050 final int filterUidFinal = UserHandle.getAppId(filterUid);
3051 final long nowElapsed = sElapsedRealtimeClock.millis();
3052 final long nowUptime = sUptimeMillisClock.millis();
3053
3054 synchronized (mLock) {
3055 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
3056 for (int u : mStartedUsers) {
3057 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
3058 }
3059 if (mJobs.size() > 0) {
3060 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
3061 sortJobs(jobs);
3062 for (JobStatus job : jobs) {
3063 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
3064 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
3065
3066 // Skip printing details if the caller requested a filter
3067 if (!job.shouldDump(filterUidFinal)) {
3068 continue;
3069 }
3070
3071 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
3072
3073 // isReadyToBeExecuted
3074 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
3075 job.isReady());
3076 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
3077 ArrayUtils.contains(mStartedUsers, job.getUserId()));
3078 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
3079 mPendingJobs.contains(job));
3080 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
3081 isCurrentlyActiveLocked(job));
3082 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
3083 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
3084 boolean componentPresent = false;
3085 try {
3086 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3087 job.getServiceComponent(),
3088 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3089 job.getUserId()) != null);
3090 } catch (RemoteException e) {
3091 }
3092 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
3093 componentPresent);
3094
3095 proto.end(rjToken);
3096 }
3097 }
3098 for (StateController controller : mControllers) {
3099 controller.dumpControllerStateLocked(
3100 proto, JobSchedulerServiceDumpProto.CONTROLLERS, filterUidFinal);
3101 }
3102 for (int i=0; i< mUidPriorityOverride.size(); i++) {
3103 int uid = mUidPriorityOverride.keyAt(i);
3104 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3105 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3106 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3107 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3108 mUidPriorityOverride.valueAt(i));
3109 proto.end(pToken);
3110 }
3111 }
3112 for (int i = 0; i < mBackingUpUids.size(); i++) {
3113 int uid = mBackingUpUids.keyAt(i);
3114 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3115 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3116 }
3117 }
3118
3119 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3120 filterUidFinal);
3121 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3122 filterUidFinal);
3123
3124 for (JobStatus job : mPendingJobs) {
3125 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3126
3127 job.writeToShortProto(proto, PendingJob.INFO);
3128 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
3129 int priority = evaluateJobPriorityLocked(job);
3130 if (priority != JobInfo.PRIORITY_DEFAULT) {
3131 proto.write(PendingJob.EVALUATED_PRIORITY, priority);
3132 }
3133 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
3134
3135 proto.end(pjToken);
3136 }
3137 for (JobServiceContext jsc : mActiveServices) {
3138 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
3139 final JobStatus job = jsc.getRunningJobLocked();
3140
3141 if (job == null) {
3142 final long ijToken = proto.start(ActiveJob.INACTIVE);
3143
3144 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
3145 nowElapsed - jsc.mStoppedTime);
3146 if (jsc.mStoppedReason != null) {
3147 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
3148 jsc.mStoppedReason);
3149 }
3150
3151 proto.end(ijToken);
3152 } else {
3153 final long rjToken = proto.start(ActiveJob.RUNNING);
3154
3155 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
3156
3157 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
3158 nowElapsed - jsc.getExecutionStartTimeElapsed());
3159 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
3160 jsc.getTimeoutElapsed() - nowElapsed);
3161
3162 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3163
3164 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
3165 if (priority != JobInfo.PRIORITY_DEFAULT) {
3166 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY, priority);
3167 }
3168
3169 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3170 nowUptime - job.madeActive);
3171 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3172 job.madeActive - job.madePending);
3173
3174 proto.end(rjToken);
3175 }
3176 proto.end(ajToken);
3177 }
3178 if (filterUid == -1) {
3179 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3180 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3181 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
3182 }
3183 }
3184
3185 proto.flush();
3186 }
Christopher Tate7060b042014-06-09 19:50:00 -07003187}