Debian Codegraph @

apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java

raw symbols SCIP
1 /*
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
17 package com.android.server.job;
18
19 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21 import static android.text.format.DateUtils.HOUR_IN_MILLIS;
22 import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
23
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.annotation.UserIdInt;
27 import android.app.Activity;
28 import android.app.ActivityManager;
29 import android.app.ActivityManagerInternal;
30 import android.app.AppGlobals;
31 import android.app.IUidObserver;
32 import android.app.compat.CompatChanges;
33 import android.app.job.IJobScheduler;
34 import android.app.job.JobInfo;
35 import android.app.job.JobParameters;
36 import android.app.job.JobProtoEnums;
37 import android.app.job.JobScheduler;
38 import android.app.job.JobService;
39 import android.app.job.JobSnapshot;
40 import android.app.job.JobWorkItem;
41 import android.app.usage.UsageStatsManager;
42 import android.app.usage.UsageStatsManagerInternal;
43 import android.content.BroadcastReceiver;
44 import android.content.ComponentName;
45 import android.content.Context;
46 import android.content.Intent;
47 import android.content.IntentFilter;
48 import android.content.pm.ApplicationInfo;
49 import android.content.pm.IPackageManager;
50 import android.content.pm.PackageManager;
51 import android.content.pm.PackageManager.NameNotFoundException;
52 import android.content.pm.PackageManagerInternal;
53 import android.content.pm.ParceledListSlice;
54 import android.content.pm.ProviderInfo;
55 import android.content.pm.ServiceInfo;
56 import android.net.Uri;
57 import android.os.BatteryManager;
58 import android.os.BatteryManagerInternal;
59 import android.os.BatteryStatsInternal;
60 import android.os.Binder;
61 import android.os.Handler;
62 import android.os.LimitExceededException;
63 import android.os.Looper;
64 import android.os.Message;
65 import android.os.ParcelFileDescriptor;
66 import android.os.Process;
67 import android.os.RemoteException;
68 import android.os.SystemClock;
69 import android.os.UserHandle;
70 import android.os.WorkSource;
71 import android.os.storage.StorageManagerInternal;
72 import android.provider.DeviceConfig;
73 import android.provider.Settings;
74 import android.text.format.DateUtils;
75 import android.util.ArrayMap;
76 import android.util.ArraySet;
77 import android.util.IndentingPrintWriter;
78 import android.util.Log;
79 import android.util.Slog;
80 import android.util.SparseArray;
81 import android.util.SparseBooleanArray;
82 import android.util.SparseIntArray;
83 import android.util.SparseSetArray;
84 import android.util.TimeUtils;
85 import android.util.proto.ProtoOutputStream;
86
87 import com.android.internal.annotations.GuardedBy;
88 import com.android.internal.annotations.VisibleForTesting;
89 import com.android.internal.os.SomeArgs;
90 import com.android.internal.util.ArrayUtils;
91 import com.android.internal.util.DumpUtils;
92 import com.android.internal.util.FrameworkStatsLog;
93 import com.android.server.AppStateTracker;
94 import com.android.server.AppStateTrackerImpl;
95 import com.android.server.DeviceIdleInternal;
96 import com.android.server.JobSchedulerBackgroundThread;
97 import com.android.server.LocalServices;
98 import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
99 import com.android.server.job.controllers.BackgroundJobsController;
100 import com.android.server.job.controllers.BatteryController;
101 import com.android.server.job.controllers.ComponentController;
102 import com.android.server.job.controllers.ConnectivityController;
103 import com.android.server.job.controllers.ContentObserverController;
104 import com.android.server.job.controllers.DeviceIdleJobsController;
105 import com.android.server.job.controllers.IdleController;
106 import com.android.server.job.controllers.JobStatus;
107 import com.android.server.job.controllers.PrefetchController;
108 import com.android.server.job.controllers.QuotaController;
109 import com.android.server.job.controllers.RestrictingController;
110 import com.android.server.job.controllers.StateController;
111 import com.android.server.job.controllers.StorageController;
112 import com.android.server.job.controllers.TareController;
113 import com.android.server.job.controllers.TimeController;
114 import com.android.server.job.restrictions.JobRestriction;
115 import com.android.server.job.restrictions.ThermalStatusRestriction;
116 import com.android.server.pm.UserManagerInternal;
117 import com.android.server.tare.EconomyManagerInternal;
118 import com.android.server.usage.AppStandbyInternal;
119 import com.android.server.usage.AppStandbyInternal.AppIdleStateChangeListener;
120 import com.android.server.utils.quota.Categorizer;
121 import com.android.server.utils.quota.Category;
122 import com.android.server.utils.quota.CountQuotaTracker;
123
124 import dalvik.annotation.optimization.NeverCompile;
125
126 import libcore.util.EmptyArray;
127
128 import java.io.FileDescriptor;
129 import java.io.PrintWriter;
130 import java.time.Clock;
131 import java.time.Instant;
132 import java.time.ZoneId;
133 import java.time.ZoneOffset;
134 import java.util.ArrayList;
135 import java.util.Arrays;
136 import java.util.Collections;
137 import java.util.Comparator;
138 import java.util.List;
139 import java.util.Objects;
140 import java.util.function.Consumer;
141 import java.util.function.Predicate;
142
143 /**
144 * Responsible for taking jobs representing work to be performed by a client app, and determining
145 * based on the criteria specified when that job should be run against the client application's
146 * endpoint.
147 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
148 * about constraints, or the state of active jobs. It receives callbacks from the various
149 * controllers and completed jobs and operates accordingly.
150 *
151 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
152 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
153 *
154 * @hide
155 */
156 public class JobSchedulerService extends com.android.server.SystemService
157 implements StateChangedListener, JobCompletedListener {
158 public static final String TAG = "JobScheduler";
159 public static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
160 public static final boolean DEBUG_STANDBY = DEBUG || false;
161
162 /** The maximum number of jobs that we allow an app to schedule */
163 private static final int MAX_JOBS_PER_APP = 150;
164 /** The number of the most recently completed jobs to keep track of for debugging purposes. */
165 private static final int NUM_COMPLETED_JOB_HISTORY = 20;
166
167 @VisibleForTesting
168 public static Clock sSystemClock = Clock.systemUTC();
169
170 private abstract static class MySimpleClock extends Clock {
171 private final ZoneId mZoneId;
172
173 MySimpleClock(ZoneId zoneId) {
174 this.mZoneId = zoneId;
175 }
176
177 @Override
178 public ZoneId getZone() {
179 return mZoneId;
180 }
181
182 @Override
183 public Clock withZone(ZoneId zone) {
184 return new MySimpleClock(zone) {
185 @Override
186 public long millis() {
187 return MySimpleClock.this.millis();
188 }
189 };
190 }
191
192 @Override
193 public abstract long millis();
194
195 @Override
196 public Instant instant() {
197 return Instant.ofEpochMilli(millis());
198 }
199 }
200
201 @VisibleForTesting
202 public static Clock sUptimeMillisClock = new MySimpleClock(ZoneOffset.UTC) {
203 @Override
204 public long millis() {
205 return SystemClock.uptimeMillis();
206 }
207 };
208
209 @VisibleForTesting
210 public static Clock sElapsedRealtimeClock = new MySimpleClock(ZoneOffset.UTC) {
211 @Override
212 public long millis() {
213 return SystemClock.elapsedRealtime();
214 }
215 };
216
217 /** Global local for all job scheduler state. */
218 final Object mLock = new Object();
219 /** Master list of jobs. */
220 final JobStore mJobs;
221 /** Tracking the standby bucket state of each app */
222 final StandbyTracker mStandbyTracker;
223 /** Tracking amount of time each package runs for. */
224 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
225 final JobConcurrencyManager mConcurrencyManager;
226
227 static final int MSG_CHECK_INDIVIDUAL_JOB = 0;
228 static final int MSG_CHECK_JOB = 1;
229 static final int MSG_STOP_JOB = 2;
230 static final int MSG_CHECK_JOB_GREEDY = 3;
231 static final int MSG_UID_STATE_CHANGED = 4;
232 static final int MSG_UID_GONE = 5;
233 static final int MSG_UID_ACTIVE = 6;
234 static final int MSG_UID_IDLE = 7;
235 static final int MSG_CHECK_CHANGED_JOB_LIST = 8;
236 static final int MSG_CHECK_MEDIA_EXEMPTION = 9;
237
238 /** List of controllers that will notify this service of updates to jobs. */
239 final List<StateController> mControllers;
240 /**
241 * List of controllers that will apply to all jobs in the RESTRICTED bucket. This is a subset of
242 * {@link #mControllers}.
243 */
244 private final List<RestrictingController> mRestrictiveControllers;
245 /** Need direct access to this for testing. */
246 private final StorageController mStorageController;
247 /** Need directly for sending uid state changes */
248 private final DeviceIdleJobsController mDeviceIdleJobsController;
249 /** Needed to get next estimated launch time. */
250 private final PrefetchController mPrefetchController;
251 /** Needed to get remaining quota time. */
252 private final QuotaController mQuotaController;
253 /** Needed to get max execution time and expedited-job allowance. */
254 private final TareController mTareController;
255 /**
256 * List of restrictions.
257 * Note: do not add to or remove from this list at runtime except in the constructor, because we
258 * do not synchronize access to this list.
259 */
260 private final List<JobRestriction> mJobRestrictions;
261
262 @GuardedBy("mLock")
263 private final BatteryStateTracker mBatteryStateTracker;
264
265 @GuardedBy("mLock")
266 private final SparseArray<String> mCloudMediaProviderPackages = new SparseArray<>();
267
268 private final CountQuotaTracker mQuotaTracker;
269 private static final String QUOTA_TRACKER_SCHEDULE_PERSISTED_TAG = ".schedulePersisted()";
270 private static final String QUOTA_TRACKER_SCHEDULE_LOGGED =
271 ".schedulePersisted out-of-quota logged";
272 private static final Category QUOTA_TRACKER_CATEGORY_SCHEDULE_PERSISTED = new Category(
273 ".schedulePersisted()");
274 private static final Category QUOTA_TRACKER_CATEGORY_SCHEDULE_LOGGED = new Category(
275 ".schedulePersisted out-of-quota logged");
276 private static final Categorizer QUOTA_CATEGORIZER = (userId, packageName, tag) -> {
277 if (QUOTA_TRACKER_SCHEDULE_PERSISTED_TAG.equals(tag)) {
278 return QUOTA_TRACKER_CATEGORY_SCHEDULE_PERSISTED;
279 }
280 return QUOTA_TRACKER_CATEGORY_SCHEDULE_LOGGED;
281 };
282
283 /**
284 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
285 * when ready to execute them.
286 */
287 private final PendingJobQueue mPendingJobQueue = new PendingJobQueue();
288
289 int[] mStartedUsers = EmptyArray.INT;
290
291 final JobHandler mHandler;
292 final JobSchedulerStub mJobSchedulerStub;
293
294 PackageManagerInternal mLocalPM;
295 ActivityManagerInternal mActivityManagerInternal;
296 DeviceIdleInternal mLocalDeviceIdleController;
297 @VisibleForTesting
298 AppStateTrackerImpl mAppStateTracker;
299 final UsageStatsManagerInternal mUsageStats;
300 private final AppStandbyInternal mAppStandbyInternal;
301
302 /**
303 * Set to true once we are allowed to run third party apps.
304 */
305 boolean mReadyToRock;
306
307 /**
308 * What we last reported to DeviceIdleController about whether we are active.
309 */
310 boolean mReportedActive;
311
312 private int mLastCompletedJobIndex = 0;
313 private final JobStatus[] mLastCompletedJobs = new JobStatus[NUM_COMPLETED_JOB_HISTORY];
314 private final long[] mLastCompletedJobTimeElapsed = new long[NUM_COMPLETED_JOB_HISTORY];
315
316 /**
317 * A mapping of which uids are currently in the foreground to their effective bias.
318 */
319 final SparseIntArray mUidBiasOverride = new SparseIntArray();
320
321 /**
322 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
323 */
324 private final SparseBooleanArray mBackingUpUids = new SparseBooleanArray();
325
326 /**
327 * Cache of debuggable app status.
328 */
329 final ArrayMap<String, Boolean> mDebuggableApps = new ArrayMap<>();
330
331 /** Cached mapping of UIDs (for all users) to a list of packages in the UID. */
332 private final SparseSetArray<String> mUidToPackageCache = new SparseSetArray<>();
333
334 /** List of jobs whose controller state has changed since the last time we evaluated the job. */
335 @GuardedBy("mLock")
336 private final ArraySet<JobStatus> mChangedJobList = new ArraySet<>();
337
338 /**
339 * Named indices into standby bucket arrays, for clarity in referring to
340 * specific buckets' bookkeeping.
341 */
342 public static final int ACTIVE_INDEX = 0;
343 public static final int WORKING_INDEX = 1;
344 public static final int FREQUENT_INDEX = 2;
345 public static final int RARE_INDEX = 3;
346 public static final int NEVER_INDEX = 4;
347 // Putting RESTRICTED_INDEX after NEVER_INDEX to make it easier for proto dumping
348 // (ScheduledJobStateChanged and JobStatusDumpProto).
349 public static final int RESTRICTED_INDEX = 5;
350 // Putting EXEMPTED_INDEX after RESTRICTED_INDEX to make it easier for proto dumping
351 // (ScheduledJobStateChanged and JobStatusDumpProto).
352 public static final int EXEMPTED_INDEX = 6;
353
354 private class ConstantsObserver implements DeviceConfig.OnPropertiesChangedListener,
355 EconomyManagerInternal.TareStateChangeListener {
356 public void start() {
357 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
358 JobSchedulerBackgroundThread.getExecutor(), this);
359 final EconomyManagerInternal economyManagerInternal =
360 LocalServices.getService(EconomyManagerInternal.class);
361 economyManagerInternal.registerTareStateChangeListener(this);
362 // Load all the constants.
363 synchronized (mLock) {
364 mConstants.updateTareSettingsLocked(economyManagerInternal.isEnabled());
365 }
366 onPropertiesChanged(DeviceConfig.getProperties(DeviceConfig.NAMESPACE_JOB_SCHEDULER));
367 }
368
369 @Override
370 public void onPropertiesChanged(DeviceConfig.Properties properties) {
371 boolean apiQuotaScheduleUpdated = false;
372 boolean concurrencyUpdated = false;
373 boolean runtimeUpdated = false;
374 for (int controller = 0; controller < mControllers.size(); controller++) {
375 final StateController sc = mControllers.get(controller);
376 sc.prepareForUpdatedConstantsLocked();
377 }
378
379 synchronized (mLock) {
380 for (String name : properties.getKeyset()) {
381 if (name == null) {
382 continue;
383 }
384 switch (name) {
385 case Constants.KEY_ENABLE_API_QUOTAS:
386 case Constants.KEY_API_QUOTA_SCHEDULE_COUNT:
387 case Constants.KEY_API_QUOTA_SCHEDULE_WINDOW_MS:
388 case Constants.KEY_API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT:
389 case Constants.KEY_API_QUOTA_SCHEDULE_THROW_EXCEPTION:
390 if (!apiQuotaScheduleUpdated) {
391 mConstants.updateApiQuotaConstantsLocked();
392 updateQuotaTracker();
393 apiQuotaScheduleUpdated = true;
394 }
395 break;
396 case Constants.KEY_MIN_READY_NON_ACTIVE_JOBS_COUNT:
397 case Constants.KEY_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS:
398 mConstants.updateBatchingConstantsLocked();
399 break;
400 case Constants.KEY_HEAVY_USE_FACTOR:
401 case Constants.KEY_MODERATE_USE_FACTOR:
402 mConstants.updateUseFactorConstantsLocked();
403 break;
404 case Constants.KEY_MIN_LINEAR_BACKOFF_TIME_MS:
405 case Constants.KEY_MIN_EXP_BACKOFF_TIME_MS:
406 mConstants.updateBackoffConstantsLocked();
407 break;
408 case Constants.KEY_CONN_CONGESTION_DELAY_FRAC:
409 case Constants.KEY_CONN_PREFETCH_RELAX_FRAC:
410 case Constants.KEY_CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC:
411 case Constants.KEY_CONN_USE_CELL_SIGNAL_STRENGTH:
412 case Constants.KEY_CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS:
413 mConstants.updateConnectivityConstantsLocked();
414 break;
415 case Constants.KEY_PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS:
416 mConstants.updatePrefetchConstantsLocked();
417 break;
418 case Constants.KEY_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS:
419 case Constants.KEY_RUNTIME_MIN_GUARANTEE_MS:
420 case Constants.KEY_RUNTIME_MIN_EJ_GUARANTEE_MS:
421 case Constants.KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS:
422 if (!runtimeUpdated) {
423 mConstants.updateRuntimeConstantsLocked();
424 runtimeUpdated = true;
425 }
426 break;
427 default:
428 if (name.startsWith(JobConcurrencyManager.CONFIG_KEY_PREFIX_CONCURRENCY)
429 && !concurrencyUpdated) {
430 mConcurrencyManager.updateConfigLocked();
431 concurrencyUpdated = true;
432 } else {
433 for (int ctrlr = 0; ctrlr < mControllers.size(); ctrlr++) {
434 final StateController sc = mControllers.get(ctrlr);
435 sc.processConstantLocked(properties, name);
436 }
437 }
438 break;
439 }
440 }
441 for (int controller = 0; controller < mControllers.size(); controller++) {
442 final StateController sc = mControllers.get(controller);
443 sc.onConstantsUpdatedLocked();
444 }
445 }
446 }
447
448 @Override
449 public void onTareEnabledStateChanged(boolean isTareEnabled) {
450 if (mConstants.updateTareSettingsLocked(isTareEnabled)) {
451 for (int controller = 0; controller < mControllers.size(); controller++) {
452 final StateController sc = mControllers.get(controller);
453 sc.onConstantsUpdatedLocked();
454 }
455 onControllerStateChanged(null);
456 }
457 }
458 }
459
460 @VisibleForTesting
461 void updateQuotaTracker() {
462 mQuotaTracker.setEnabled(mConstants.ENABLE_API_QUOTAS);
463 mQuotaTracker.setCountLimit(QUOTA_TRACKER_CATEGORY_SCHEDULE_PERSISTED,
464 mConstants.API_QUOTA_SCHEDULE_COUNT,
465 mConstants.API_QUOTA_SCHEDULE_WINDOW_MS);
466 }
467
468 /**
469 * All times are in milliseconds. Any access to this class or its fields should be done while
470 * holding the JobSchedulerService.mLock lock.
471 */
472 public static class Constants {
473 // Key names stored in the settings value.
474 private static final String KEY_MIN_READY_NON_ACTIVE_JOBS_COUNT =
475 "min_ready_non_active_jobs_count";
476 private static final String KEY_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS =
477 "max_non_active_job_batch_delay_ms";
478 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
479 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
480
481 private static final String KEY_MIN_LINEAR_BACKOFF_TIME_MS = "min_linear_backoff_time_ms";
482 private static final String KEY_MIN_EXP_BACKOFF_TIME_MS = "min_exp_backoff_time_ms";
483 private static final String KEY_CONN_CONGESTION_DELAY_FRAC = "conn_congestion_delay_frac";
484 private static final String KEY_CONN_PREFETCH_RELAX_FRAC = "conn_prefetch_relax_frac";
485 private static final String KEY_CONN_USE_CELL_SIGNAL_STRENGTH =
486 "conn_use_cell_signal_strength";
487 private static final String KEY_CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS =
488 "conn_update_all_jobs_min_interval_ms";
489 private static final String KEY_CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC =
490 "conn_low_signal_strength_relax_frac";
491 private static final String KEY_PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS =
492 "prefetch_force_batch_relax_threshold_ms";
493 private static final String KEY_ENABLE_API_QUOTAS = "enable_api_quotas";
494 private static final String KEY_API_QUOTA_SCHEDULE_COUNT = "aq_schedule_count";
495 private static final String KEY_API_QUOTA_SCHEDULE_WINDOW_MS = "aq_schedule_window_ms";
496 private static final String KEY_API_QUOTA_SCHEDULE_THROW_EXCEPTION =
497 "aq_schedule_throw_exception";
498 private static final String KEY_API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT =
499 "aq_schedule_return_failure";
500
501 private static final String KEY_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS =
502 "runtime_free_quota_max_limit_ms";
503 private static final String KEY_RUNTIME_MIN_GUARANTEE_MS = "runtime_min_guarantee_ms";
504 private static final String KEY_RUNTIME_MIN_EJ_GUARANTEE_MS = "runtime_min_ej_guarantee_ms";
505 private static final String KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS =
506 "runtime_min_high_priority_guarantee_ms";
507
508 private static final int DEFAULT_MIN_READY_NON_ACTIVE_JOBS_COUNT = 5;
509 private static final long DEFAULT_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS = 31 * MINUTE_IN_MILLIS;
510 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
511 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
512 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME_MS = JobInfo.MIN_BACKOFF_MILLIS;
513 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME_MS = JobInfo.MIN_BACKOFF_MILLIS;
514 private static final float DEFAULT_CONN_CONGESTION_DELAY_FRAC = 0.5f;
515 private static final float DEFAULT_CONN_PREFETCH_RELAX_FRAC = 0.5f;
516 private static final boolean DEFAULT_CONN_USE_CELL_SIGNAL_STRENGTH = true;
517 private static final long DEFAULT_CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS = MINUTE_IN_MILLIS;
518 private static final float DEFAULT_CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC = 0.5f;
519 private static final long DEFAULT_PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS = HOUR_IN_MILLIS;
520 private static final boolean DEFAULT_ENABLE_API_QUOTAS = true;
521 private static final int DEFAULT_API_QUOTA_SCHEDULE_COUNT = 250;
522 private static final long DEFAULT_API_QUOTA_SCHEDULE_WINDOW_MS = MINUTE_IN_MILLIS;
523 private static final boolean DEFAULT_API_QUOTA_SCHEDULE_THROW_EXCEPTION = true;
524 private static final boolean DEFAULT_API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT = false;
525 @VisibleForTesting
526 public static final long DEFAULT_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS = 30 * MINUTE_IN_MILLIS;
527 @VisibleForTesting
528 public static final long DEFAULT_RUNTIME_MIN_GUARANTEE_MS = 10 * MINUTE_IN_MILLIS;
529 @VisibleForTesting
530 public static final long DEFAULT_RUNTIME_MIN_EJ_GUARANTEE_MS = 3 * MINUTE_IN_MILLIS;
531 @VisibleForTesting
532 static final long DEFAULT_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS = 5 * MINUTE_IN_MILLIS;
533 private static final boolean DEFAULT_USE_TARE_POLICY = false;
534
535 /**
536 * Minimum # of non-ACTIVE jobs for which the JMS will be happy running some work early.
537 */
538 int MIN_READY_NON_ACTIVE_JOBS_COUNT = DEFAULT_MIN_READY_NON_ACTIVE_JOBS_COUNT;
539
540 /**
541 * Don't batch a non-ACTIVE job if it's been delayed due to force batching attempts for
542 * at least this amount of time.
543 */
544 long MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS = DEFAULT_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS;
545
546 /**
547 * This is the job execution factor that is considered to be heavy use of the system.
548 */
549 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
550 /**
551 * This is the job execution factor that is considered to be moderate use of the system.
552 */
553 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
554
555 /**
556 * The minimum backoff time to allow for linear backoff.
557 */
558 long MIN_LINEAR_BACKOFF_TIME_MS = DEFAULT_MIN_LINEAR_BACKOFF_TIME_MS;
559 /**
560 * The minimum backoff time to allow for exponential backoff.
561 */
562 long MIN_EXP_BACKOFF_TIME_MS = DEFAULT_MIN_EXP_BACKOFF_TIME_MS;
563
564 /**
565 * The fraction of a job's running window that must pass before we
566 * consider running it when the network is congested.
567 */
568 public float CONN_CONGESTION_DELAY_FRAC = DEFAULT_CONN_CONGESTION_DELAY_FRAC;
569 /**
570 * The fraction of a prefetch job's running window that must pass before
571 * we consider matching it against a metered network.
572 */
573 public float CONN_PREFETCH_RELAX_FRAC = DEFAULT_CONN_PREFETCH_RELAX_FRAC;
574 /**
575 * Whether to use the cell signal strength to determine if a particular job is eligible to
576 * run.
577 */
578 public boolean CONN_USE_CELL_SIGNAL_STRENGTH = DEFAULT_CONN_USE_CELL_SIGNAL_STRENGTH;
579 /**
580 * When throttling updating all tracked jobs, make sure not to update them more frequently
581 * than this value.
582 */
583 public long CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS =
584 DEFAULT_CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS;
585 /**
586 * The fraction of a job's running window that must pass before we consider running it on
587 * low signal strength networks.
588 */
589 public float CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC =
590 DEFAULT_CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC;
591
592 /**
593 * The amount of time within which we would consider the app to be launching relatively soon
594 * and will relax the force batching policy on prefetch jobs. If the app is not going to be
595 * launched within this amount of time from now, then we will force batch the prefetch job.
596 */
597 public long PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS =
598 DEFAULT_PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS;
599
600 /**
601 * Whether to enable quota limits on APIs.
602 */
603 public boolean ENABLE_API_QUOTAS = DEFAULT_ENABLE_API_QUOTAS;
604 /**
605 * The maximum number of schedule() calls an app can make in a set amount of time.
606 */
607 public int API_QUOTA_SCHEDULE_COUNT = DEFAULT_API_QUOTA_SCHEDULE_COUNT;
608 /**
609 * The time window that {@link #API_QUOTA_SCHEDULE_COUNT} should be evaluated over.
610 */
611 public long API_QUOTA_SCHEDULE_WINDOW_MS = DEFAULT_API_QUOTA_SCHEDULE_WINDOW_MS;
612 /**
613 * Whether to throw an exception when an app hits its schedule quota limit.
614 */
615 public boolean API_QUOTA_SCHEDULE_THROW_EXCEPTION =
616 DEFAULT_API_QUOTA_SCHEDULE_THROW_EXCEPTION;
617 /**
618 * Whether or not to return a failure result when an app hits its schedule quota limit.
619 */
620 public boolean API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT =
621 DEFAULT_API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT;
622
623 /** The maximum amount of time we will let a job run for when quota is "free". */
624 public long RUNTIME_FREE_QUOTA_MAX_LIMIT_MS = DEFAULT_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS;
625
626 /**
627 * The minimum amount of time we try to guarantee regular jobs will run for.
628 */
629 public long RUNTIME_MIN_GUARANTEE_MS = DEFAULT_RUNTIME_MIN_GUARANTEE_MS;
630
631 /**
632 * The minimum amount of time we try to guarantee EJs will run for.
633 */
634 public long RUNTIME_MIN_EJ_GUARANTEE_MS = DEFAULT_RUNTIME_MIN_EJ_GUARANTEE_MS;
635
636 /**
637 * The minimum amount of time we try to guarantee high priority jobs will run for.
638 */
639 public long RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS =
640 DEFAULT_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS;
641
642 /**
643 * If true, use TARE policy for job limiting. If false, use quotas.
644 */
645 public boolean USE_TARE_POLICY = DEFAULT_USE_TARE_POLICY;
646
647 private void updateBatchingConstantsLocked() {
648 MIN_READY_NON_ACTIVE_JOBS_COUNT = DeviceConfig.getInt(
649 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
650 KEY_MIN_READY_NON_ACTIVE_JOBS_COUNT,
651 DEFAULT_MIN_READY_NON_ACTIVE_JOBS_COUNT);
652 MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS = DeviceConfig.getLong(
653 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
654 KEY_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS,
655 DEFAULT_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS);
656 }
657
658 private void updateUseFactorConstantsLocked() {
659 HEAVY_USE_FACTOR = DeviceConfig.getFloat(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
660 KEY_HEAVY_USE_FACTOR,
661 DEFAULT_HEAVY_USE_FACTOR);
662 MODERATE_USE_FACTOR = DeviceConfig.getFloat(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
663 KEY_MODERATE_USE_FACTOR,
664 DEFAULT_MODERATE_USE_FACTOR);
665 }
666
667 private void updateBackoffConstantsLocked() {
668 MIN_LINEAR_BACKOFF_TIME_MS = DeviceConfig.getLong(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
669 KEY_MIN_LINEAR_BACKOFF_TIME_MS,
670 DEFAULT_MIN_LINEAR_BACKOFF_TIME_MS);
671 MIN_EXP_BACKOFF_TIME_MS = DeviceConfig.getLong(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
672 KEY_MIN_EXP_BACKOFF_TIME_MS,
673 DEFAULT_MIN_EXP_BACKOFF_TIME_MS);
674 }
675
676 private void updateConnectivityConstantsLocked() {
677 CONN_CONGESTION_DELAY_FRAC = DeviceConfig.getFloat(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
678 KEY_CONN_CONGESTION_DELAY_FRAC,
679 DEFAULT_CONN_CONGESTION_DELAY_FRAC);
680 CONN_PREFETCH_RELAX_FRAC = DeviceConfig.getFloat(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
681 KEY_CONN_PREFETCH_RELAX_FRAC,
682 DEFAULT_CONN_PREFETCH_RELAX_FRAC);
683 CONN_USE_CELL_SIGNAL_STRENGTH = DeviceConfig.getBoolean(
684 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
685 KEY_CONN_USE_CELL_SIGNAL_STRENGTH,
686 DEFAULT_CONN_USE_CELL_SIGNAL_STRENGTH);
687 CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS = DeviceConfig.getLong(
688 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
689 KEY_CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS,
690 DEFAULT_CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS);
691 CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC = DeviceConfig.getFloat(
692 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
693 KEY_CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC,
694 DEFAULT_CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC);
695 }
696
697 private void updatePrefetchConstantsLocked() {
698 PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS = DeviceConfig.getLong(
699 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
700 KEY_PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS,
701 DEFAULT_PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS);
702 }
703
704 private void updateApiQuotaConstantsLocked() {
705 ENABLE_API_QUOTAS = DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
706 KEY_ENABLE_API_QUOTAS, DEFAULT_ENABLE_API_QUOTAS);
707 // Set a minimum value on the quota limit so it's not so low that it interferes with
708 // legitimate use cases.
709 API_QUOTA_SCHEDULE_COUNT = Math.max(250,
710 DeviceConfig.getInt(DeviceConfig.NAMESPACE_JOB_SCHEDULER,
711 KEY_API_QUOTA_SCHEDULE_COUNT, DEFAULT_API_QUOTA_SCHEDULE_COUNT));
712 API_QUOTA_SCHEDULE_WINDOW_MS = DeviceConfig.getLong(
713 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
714 KEY_API_QUOTA_SCHEDULE_WINDOW_MS, DEFAULT_API_QUOTA_SCHEDULE_WINDOW_MS);
715 API_QUOTA_SCHEDULE_THROW_EXCEPTION = DeviceConfig.getBoolean(
716 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
717 KEY_API_QUOTA_SCHEDULE_THROW_EXCEPTION,
718 DEFAULT_API_QUOTA_SCHEDULE_THROW_EXCEPTION);
719 API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT = DeviceConfig.getBoolean(
720 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
721 KEY_API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT,
722 DEFAULT_API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT);
723 }
724
725 private void updateRuntimeConstantsLocked() {
726 DeviceConfig.Properties properties = DeviceConfig.getProperties(
727 DeviceConfig.NAMESPACE_JOB_SCHEDULER,
728 KEY_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS,
729 KEY_RUNTIME_MIN_GUARANTEE_MS, KEY_RUNTIME_MIN_EJ_GUARANTEE_MS,
730 KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS);
731
732 // Make sure min runtime for regular jobs is at least 10 minutes.
733 RUNTIME_MIN_GUARANTEE_MS = Math.max(10 * MINUTE_IN_MILLIS,
734 properties.getLong(
735 KEY_RUNTIME_MIN_GUARANTEE_MS, DEFAULT_RUNTIME_MIN_GUARANTEE_MS));
736 // Make sure min runtime for high priority jobs is at least 4 minutes.
737 RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS = Math.max(4 * MINUTE_IN_MILLIS,
738 properties.getLong(
739 KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS,
740 DEFAULT_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS));
741 // Make sure min runtime for expedited jobs is at least one minute.
742 RUNTIME_MIN_EJ_GUARANTEE_MS = Math.max(MINUTE_IN_MILLIS,
743 properties.getLong(
744 KEY_RUNTIME_MIN_EJ_GUARANTEE_MS, DEFAULT_RUNTIME_MIN_EJ_GUARANTEE_MS));
745 RUNTIME_FREE_QUOTA_MAX_LIMIT_MS = Math.max(RUNTIME_MIN_GUARANTEE_MS,
746 properties.getLong(KEY_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS,
747 DEFAULT_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS));
748 }
749
750 private boolean updateTareSettingsLocked(boolean isTareEnabled) {
751 boolean changed = false;
752 if (USE_TARE_POLICY != isTareEnabled) {
753 USE_TARE_POLICY = isTareEnabled;
754 changed = true;
755 }
756 return changed;
757 }
758
759 void dump(IndentingPrintWriter pw) {
760 pw.println("Settings:");
761 pw.increaseIndent();
762 pw.print(KEY_MIN_READY_NON_ACTIVE_JOBS_COUNT,
763 MIN_READY_NON_ACTIVE_JOBS_COUNT).println();
764 pw.print(KEY_MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS,
765 MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS).println();
766 pw.print(KEY_HEAVY_USE_FACTOR, HEAVY_USE_FACTOR).println();
767 pw.print(KEY_MODERATE_USE_FACTOR, MODERATE_USE_FACTOR).println();
768
769 pw.print(KEY_MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME_MS).println();
770 pw.print(KEY_MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME_MS).println();
771 pw.print(KEY_CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC).println();
772 pw.print(KEY_CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC).println();
773 pw.print(KEY_CONN_USE_CELL_SIGNAL_STRENGTH, CONN_USE_CELL_SIGNAL_STRENGTH).println();
774 pw.print(KEY_CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS, CONN_UPDATE_ALL_JOBS_MIN_INTERVAL_MS)
775 .println();
776 pw.print(KEY_CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC, CONN_LOW_SIGNAL_STRENGTH_RELAX_FRAC)
777 .println();
778 pw.print(KEY_PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS,
779 PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS).println();
780
781 pw.print(KEY_ENABLE_API_QUOTAS, ENABLE_API_QUOTAS).println();
782 pw.print(KEY_API_QUOTA_SCHEDULE_COUNT, API_QUOTA_SCHEDULE_COUNT).println();
783 pw.print(KEY_API_QUOTA_SCHEDULE_WINDOW_MS, API_QUOTA_SCHEDULE_WINDOW_MS).println();
784 pw.print(KEY_API_QUOTA_SCHEDULE_THROW_EXCEPTION,
785 API_QUOTA_SCHEDULE_THROW_EXCEPTION).println();
786 pw.print(KEY_API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT,
787 API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT).println();
788
789 pw.print(KEY_RUNTIME_MIN_GUARANTEE_MS, RUNTIME_MIN_GUARANTEE_MS).println();
790 pw.print(KEY_RUNTIME_MIN_EJ_GUARANTEE_MS, RUNTIME_MIN_EJ_GUARANTEE_MS).println();
791 pw.print(KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS,
792 RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS).println();
793 pw.print(KEY_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS, RUNTIME_FREE_QUOTA_MAX_LIMIT_MS)
794 .println();
795
796 pw.print(Settings.Global.ENABLE_TARE, USE_TARE_POLICY).println();
797
798 pw.decreaseIndent();
799 }
800
801 void dump(ProtoOutputStream proto) {
802 proto.write(ConstantsProto.MIN_READY_NON_ACTIVE_JOBS_COUNT,
803 MIN_READY_NON_ACTIVE_JOBS_COUNT);
804 proto.write(ConstantsProto.MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS,
805 MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS);
806 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
807 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
808
809 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME_MS);
810 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME_MS);
811 proto.write(ConstantsProto.CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC);
812 proto.write(ConstantsProto.CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC);
813
814 proto.write(ConstantsProto.ENABLE_API_QUOTAS, ENABLE_API_QUOTAS);
815 proto.write(ConstantsProto.API_QUOTA_SCHEDULE_COUNT, API_QUOTA_SCHEDULE_COUNT);
816 proto.write(ConstantsProto.API_QUOTA_SCHEDULE_WINDOW_MS, API_QUOTA_SCHEDULE_WINDOW_MS);
817 proto.write(ConstantsProto.API_QUOTA_SCHEDULE_THROW_EXCEPTION,
818 API_QUOTA_SCHEDULE_THROW_EXCEPTION);
819 proto.write(ConstantsProto.API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT,
820 API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT);
821 }
822 }
823
824 final Constants mConstants;
825 final ConstantsObserver mConstantsObserver;
826
827 /**
828 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
829 * still clean up. On reinstall the package will have a new uid.
830 */
831 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
832 @Override
833 public void onReceive(Context context, Intent intent) {
834 final String action = intent.getAction();
835 if (DEBUG) {
836 Slog.d(TAG, "Receieved: " + action);
837 }
838 final String pkgName = getPackageName(intent);
839 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
840
841 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
842 // Purge the app's jobs if the whole package was just disabled. When this is
843 // the case the component name will be a bare package name.
844 if (pkgName != null && pkgUid != -1) {
845 final String[] changedComponents = intent.getStringArrayExtra(
846 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
847 if (changedComponents != null) {
848 for (String component : changedComponents) {
849 if (component.equals(pkgName)) {
850 if (DEBUG) {
851 Slog.d(TAG, "Package state change: " + pkgName);
852 }
853 try {
854 final int userId = UserHandle.getUserId(pkgUid);
855 IPackageManager pm = AppGlobals.getPackageManager();
856 final int state =
857 pm.getApplicationEnabledSetting(pkgName, userId);
858 if (state == COMPONENT_ENABLED_STATE_DISABLED
859 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
860 if (DEBUG) {
861 Slog.d(TAG, "Removing jobs for package " + pkgName
862 + " in user " + userId);
863 }
864 synchronized (mLock) {
865 // There's no guarantee that the process has been
866 // stopped by the time we get here, but since this is
867 // a user-initiated action, it should be fine to just
868 // put USER instead of UNINSTALL or DISABLED.
869 cancelJobsForPackageAndUidLocked(pkgName, pkgUid,
870 JobParameters.STOP_REASON_USER,
871 JobParameters.INTERNAL_STOP_REASON_UNINSTALL,
872 "app disabled");
873 }
874 }
875 } catch (RemoteException | IllegalArgumentException e) {
876 /*
877 * IllegalArgumentException means that the package doesn't exist.
878 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
879 * behind outright uninstall, so by the time we try to act it's gone.
880 * We don't need to act on this PACKAGE_CHANGED when this happens;
881 * we'll get a PACKAGE_REMOVED later and clean up then.
882 *
883 * RemoteException can't actually happen; the package manager is
884 * running in this same process.
885 */
886 }
887 break;
888 }
889 }
890 if (DEBUG) {
891 Slog.d(TAG, "Something in " + pkgName
892 + " changed. Reevaluating controller states.");
893 }
894 synchronized (mLock) {
895 for (int c = mControllers.size() - 1; c >= 0; --c) {
896 mControllers.get(c).reevaluateStateLocked(pkgUid);
897 }
898 }
899 }
900 } else {
901 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
902 }
903 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
904 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
905 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
906 synchronized (mLock) {
907 mUidToPackageCache.remove(uid);
908 }
909 } else {
910 synchronized (mJobSchedulerStub.mPersistCache) {
911 mJobSchedulerStub.mPersistCache.remove(pkgUid);
912 }
913 }
914 } else if (Intent.ACTION_PACKAGE_FULLY_REMOVED.equals(action)) {
915 if (DEBUG) {
916 Slog.d(TAG, "Removing jobs for " + pkgName + " (uid=" + pkgUid + ")");
917 }
918 synchronized (mLock) {
919 mUidToPackageCache.remove(pkgUid);
920 // There's no guarantee that the process has been stopped by the time we
921 // get here, but since this is generally a user-initiated action, it should
922 // be fine to just put USER instead of UNINSTALL or DISABLED.
923 cancelJobsForPackageAndUidLocked(pkgName, pkgUid,
924 JobParameters.STOP_REASON_USER,
925 JobParameters.INTERNAL_STOP_REASON_UNINSTALL, "app uninstalled");
926 for (int c = 0; c < mControllers.size(); ++c) {
927 mControllers.get(c).onAppRemovedLocked(pkgName, pkgUid);
928 }
929 mDebuggableApps.remove(pkgName);
930 mConcurrencyManager.onAppRemovedLocked(pkgName, pkgUid);
931 }
932 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
933 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
934 synchronized (mLock) {
935 for (int c = 0; c < mControllers.size(); ++c) {
936 mControllers.get(c).onUserAddedLocked(userId);
937 }
938 }
939 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
940 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
941 if (DEBUG) {
942 Slog.d(TAG, "Removing jobs for user: " + userId);
943 }
944 synchronized (mLock) {
945 mUidToPackageCache.clear();
946 cancelJobsForUserLocked(userId);
947 for (int c = 0; c < mControllers.size(); ++c) {
948 mControllers.get(c).onUserRemovedLocked(userId);
949 }
950 }
951 mConcurrencyManager.onUserRemoved(userId);
952 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
953 // Has this package scheduled any jobs, such that we will take action
954 // if it were to be force-stopped?
955 if (pkgUid != -1) {
956 List<JobStatus> jobsForUid;
957 synchronized (mLock) {
958 jobsForUid = mJobs.getJobsByUid(pkgUid);
959 }
960 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
961 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
962 if (DEBUG) {
963 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
964 + pkgUid + " has jobs");
965 }
966 setResultCode(Activity.RESULT_OK);
967 break;
968 }
969 }
970 }
971 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
972 // possible force-stop
973 if (pkgUid != -1) {
974 if (DEBUG) {
975 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
976 }
977 synchronized (mLock) {
978 cancelJobsForPackageAndUidLocked(pkgName, pkgUid,
979 JobParameters.STOP_REASON_USER,
980 JobParameters.INTERNAL_STOP_REASON_CANCELED,
981 "app force stopped");
982 }
983 }
984 }
985 }
986 };
987
988 private String getPackageName(Intent intent) {
989 Uri uri = intent.getData();
990 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
991 return pkg;
992 }
993
994 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
995 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq,
996 int capability) {
997 mHandler.obtainMessage(MSG_UID_STATE_CHANGED, uid, procState).sendToTarget();
998 }
999
1000 @Override public void onUidGone(int uid, boolean disabled) {
1001 mHandler.obtainMessage(MSG_UID_GONE, uid, disabled ? 1 : 0).sendToTarget();
1002 }
1003
1004 @Override public void onUidActive(int uid) throws RemoteException {
1005 mHandler.obtainMessage(MSG_UID_ACTIVE, uid, 0).sendToTarget();
1006 }
1007
1008 @Override public void onUidIdle(int uid, boolean disabled) {
1009 mHandler.obtainMessage(MSG_UID_IDLE, uid, disabled ? 1 : 0).sendToTarget();
1010 }
1011
1012 @Override public void onUidCachedChanged(int uid, boolean cached) {
1013 }
1014
1015 @Override public void onUidProcAdjChanged(int uid) {
1016 }
1017 };
1018
1019 public Context getTestableContext() {
1020 return getContext();
1021 }
1022
1023 public Object getLock() {
1024 return mLock;
1025 }
1026
1027 public JobStore getJobStore() {
1028 return mJobs;
1029 }
1030
1031 public Constants getConstants() {
1032 return mConstants;
1033 }
1034
1035 @NonNull
1036 PendingJobQueue getPendingJobQueue() {
1037 return mPendingJobQueue;
1038 }
1039
1040 @NonNull
1041 public WorkSource deriveWorkSource(int sourceUid, @Nullable String sourcePackageName) {
1042 if (WorkSource.isChainedBatteryAttributionEnabled(getContext())) {
1043 WorkSource ws = new WorkSource();
1044 ws.createWorkChain()
1045 .addNode(sourceUid, sourcePackageName)
1046 .addNode(Process.SYSTEM_UID, "JobScheduler");
1047 return ws;
1048 } else {
1049 return sourcePackageName == null
1050 ? new WorkSource(sourceUid) : new WorkSource(sourceUid, sourcePackageName);
1051 }
1052 }
1053
1054 @Nullable
1055 @GuardedBy("mLock")
1056 public ArraySet<String> getPackagesForUidLocked(final int uid) {
1057 ArraySet<String> packages = mUidToPackageCache.get(uid);
1058 if (packages == null) {
1059 try {
1060 String[] pkgs = AppGlobals.getPackageManager()
1061 .getPackagesForUid(uid);
1062 if (pkgs != null) {
1063 for (String pkg : pkgs) {
1064 mUidToPackageCache.add(uid, pkg);
1065 }
1066 packages = mUidToPackageCache.get(uid);
1067 }
1068 } catch (RemoteException e) {
1069 // Shouldn't happen.
1070 }
1071 }
1072 return packages;
1073 }
1074
1075 @Override
1076 public void onUserStarting(@NonNull TargetUser user) {
1077 synchronized (mLock) {
1078 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, user.getUserIdentifier());
1079 }
1080 }
1081
1082 /** Start jobs after user is available, delayed by a few seconds since non-urgent. */
1083 @Override
1084 public void onUserCompletedEvent(@NonNull TargetUser user, UserCompletedEventType eventType) {
1085 if (eventType.includesOnUserStarting() || eventType.includesOnUserUnlocked()) {
1086 // onUserStarting: direct-boot-aware jobs can safely run
1087 // onUserUnlocked: direct-boot-UNaware jobs can safely run.
1088 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1089 }
1090 }
1091
1092 @Override
1093 public void onUserStopping(@NonNull TargetUser user) {
1094 synchronized (mLock) {
1095 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, user.getUserIdentifier());
1096 }
1097 }
1098
1099 /**
1100 * Return whether an UID is active or idle.
1101 */
1102 private boolean isUidActive(int uid) {
1103 return mAppStateTracker.isUidActiveSynced(uid);
1104 }
1105
1106 private final Predicate<Integer> mIsUidActivePredicate = this::isUidActive;
1107
1108 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
1109 int userId, String tag) {
1110 // Rate limit excessive schedule() calls.
1111 final String servicePkg = job.getService().getPackageName();
1112 if (job.isPersisted() && (packageName == null || packageName.equals(servicePkg))) {
1113 // Only limit schedule calls for persisted jobs scheduled by the app itself.
1114 final String pkg = packageName == null ? servicePkg : packageName;
1115 if (!mQuotaTracker.isWithinQuota(userId, pkg, QUOTA_TRACKER_SCHEDULE_PERSISTED_TAG)) {
1116 if (mQuotaTracker.isWithinQuota(userId, pkg, QUOTA_TRACKER_SCHEDULE_LOGGED)) {
1117 // Don't log too frequently
1118 Slog.wtf(TAG, userId + "-" + pkg + " has called schedule() too many times");
1119 mQuotaTracker.noteEvent(userId, pkg, QUOTA_TRACKER_SCHEDULE_LOGGED);
1120 }
1121 mAppStandbyInternal.restrictApp(
1122 pkg, userId, UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY);
1123 if (mConstants.API_QUOTA_SCHEDULE_THROW_EXCEPTION) {
1124 final boolean isDebuggable;
1125 synchronized (mLock) {
1126 if (!mDebuggableApps.containsKey(packageName)) {
1127 try {
1128 final ApplicationInfo appInfo = AppGlobals.getPackageManager()
1129 .getApplicationInfo(pkg, 0, userId);
1130 if (appInfo != null) {
1131 mDebuggableApps.put(packageName,
1132 (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
1133 } else {
1134 return JobScheduler.RESULT_FAILURE;
1135 }
1136 } catch (RemoteException e) {
1137 throw new RuntimeException(e);
1138 }
1139 }
1140 isDebuggable = mDebuggableApps.get(packageName);
1141 }
1142 if (isDebuggable) {
1143 // Only throw the exception for debuggable apps.
1144 throw new LimitExceededException(
1145 "schedule()/enqueue() called more than "
1146 + mQuotaTracker.getLimit(
1147 QUOTA_TRACKER_CATEGORY_SCHEDULE_PERSISTED)
1148 + " times in the past "
1149 + mQuotaTracker.getWindowSizeMs(
1150 QUOTA_TRACKER_CATEGORY_SCHEDULE_PERSISTED)
1151 + "ms. See the documentation for more information.");
1152 }
1153 }
1154 if (mConstants.API_QUOTA_SCHEDULE_RETURN_FAILURE_RESULT) {
1155 return JobScheduler.RESULT_FAILURE;
1156 }
1157 }
1158 mQuotaTracker.noteEvent(userId, pkg, QUOTA_TRACKER_SCHEDULE_PERSISTED_TAG);
1159 }
1160
1161 if (mActivityManagerInternal.isAppStartModeDisabled(uId, servicePkg)) {
1162 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
1163 + " -- package not allowed to start");
1164 return JobScheduler.RESULT_FAILURE;
1165 }
1166
1167 synchronized (mLock) {
1168 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
1169
1170 if (work != null && toCancel != null) {
1171 // Fast path: we are adding work to an existing job, and the JobInfo is not
1172 // changing. We can just directly enqueue this work in to the job.
1173 if (toCancel.getJob().equals(job)) {
1174
1175 toCancel.enqueueWorkLocked(work);
1176
1177 // If any of work item is enqueued when the source is in the foreground,
1178 // exempt the entire job.
1179 toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
1180
1181 return JobScheduler.RESULT_SUCCESS;
1182 }
1183 }
1184
1185 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
1186
1187 // Return failure early if expedited job quota used up.
1188 if (jobStatus.isRequestedExpeditedJob()) {
1189 if ((mConstants.USE_TARE_POLICY && !mTareController.canScheduleEJ(jobStatus))
1190 || (!mConstants.USE_TARE_POLICY
1191 && !mQuotaController.isWithinEJQuotaLocked(jobStatus))) {
1192 return JobScheduler.RESULT_FAILURE;
1193 }
1194 }
1195
1196 // Give exemption if the source is in the foreground just now.
1197 // Note if it's a sync job, this method is called on the handler so it's not exactly
1198 // the state when requestSync() was called, but that should be fine because of the
1199 // 1 minute foreground grace period.
1200 jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
1201
1202 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
1203 // Jobs on behalf of others don't apply to the per-app job cap
1204 if (packageName == null) {
1205 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
1206 Slog.w(TAG, "Too many jobs for uid " + uId);
1207 throw new IllegalStateException("Apps may not schedule more than "
1208 + MAX_JOBS_PER_APP + " distinct jobs");
1209 }
1210 }
1211
1212 // This may throw a SecurityException.
1213 jobStatus.prepareLocked();
1214
1215 if (toCancel != null) {
1216 // Implicitly replaces the existing job record with the new instance
1217 cancelJobImplLocked(toCancel, jobStatus, JobParameters.STOP_REASON_CANCELLED_BY_APP,
1218 JobParameters.INTERNAL_STOP_REASON_CANCELED, "job rescheduled by app");
1219 } else {
1220 startTrackingJobLocked(jobStatus, null);
1221 }
1222
1223 if (work != null) {
1224 // If work has been supplied, enqueue it into the new job.
1225 jobStatus.enqueueWorkLocked(work);
1226 }
1227
1228 FrameworkStatsLog.write_non_chained(FrameworkStatsLog.SCHEDULED_JOB_STATE_CHANGED,
1229 uId, null, jobStatus.getBatteryName(),
1230 FrameworkStatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
1231 JobProtoEnums.INTERNAL_STOP_REASON_UNKNOWN, jobStatus.getStandbyBucket(),
1232 jobStatus.getJobId(),
1233 jobStatus.hasChargingConstraint(),
1234 jobStatus.hasBatteryNotLowConstraint(),
1235 jobStatus.hasStorageNotLowConstraint(),
1236 jobStatus.hasTimingDelayConstraint(),
1237 jobStatus.hasDeadlineConstraint(),
1238 jobStatus.hasIdleConstraint(),
1239 jobStatus.hasConnectivityConstraint(),
1240 jobStatus.hasContentTriggerConstraint(),
1241 jobStatus.isRequestedExpeditedJob(),
1242 /* isRunningAsExpeditedJob */ false,
1243 JobProtoEnums.STOP_REASON_UNDEFINED,
1244 jobStatus.getJob().isPrefetch(),
1245 jobStatus.getJob().getPriority(),
1246 jobStatus.getEffectivePriority(),
1247 jobStatus.getNumFailures());
1248
1249 // If the job is immediately ready to run, then we can just immediately
1250 // put it in the pending list and try to schedule it. This is especially
1251 // important for jobs with a 0 deadline constraint, since they will happen a fair
1252 // amount, we want to handle them as quickly as possible, and semantically we want to
1253 // make sure we have started holding the wake lock for the job before returning to
1254 // the caller.
1255 // If the job is not yet ready to run, there is nothing more to do -- we are
1256 // now just waiting for one of its controllers to change state and schedule
1257 // the job appropriately.
1258 if (isReadyToBeExecutedLocked(jobStatus)) {
1259 // This is a new job, we can just immediately put it on the pending
1260 // list and try to run it.
1261 mJobPackageTracker.notePending(jobStatus);
1262 mPendingJobQueue.add(jobStatus);
1263 maybeRunPendingJobsLocked();
1264 } else {
1265 evaluateControllerStatesLocked(jobStatus);
1266 }
1267 }
1268 return JobScheduler.RESULT_SUCCESS;
1269 }
1270
1271 public List<JobInfo> getPendingJobs(int uid) {
1272 synchronized (mLock) {
1273 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
1274 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
1275 for (int i = jobs.size() - 1; i >= 0; i--) {
1276 JobStatus job = jobs.get(i);
1277 outList.add(job.getJob());
1278 }
1279 return outList;
1280 }
1281 }
1282
1283 public JobInfo getPendingJob(int uid, int jobId) {
1284 synchronized (mLock) {
1285 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
1286 for (int i = jobs.size() - 1; i >= 0; i--) {
1287 JobStatus job = jobs.get(i);
1288 if (job.getJobId() == jobId) {
1289 return job.getJob();
1290 }
1291 }
1292 return null;
1293 }
1294 }
1295
1296 private void cancelJobsForUserLocked(int userHandle) {
1297 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
1298 for (int i = 0; i < jobsForUser.size(); i++) {
1299 JobStatus toRemove = jobsForUser.get(i);
1300 // There's no guarantee that the process has been stopped by the time we get here,
1301 // but since this is a user-initiated action, it should be fine to just put USER
1302 // instead of UNINSTALL or DISABLED.
1303 cancelJobImplLocked(toRemove, null, JobParameters.STOP_REASON_USER,
1304 JobParameters.INTERNAL_STOP_REASON_UNINSTALL, "user removed");
1305 }
1306 }
1307
1308 private void cancelJobsForNonExistentUsers() {
1309 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
1310 synchronized (mLock) {
1311 mJobs.removeJobsOfUnlistedUsers(umi.getUserIds());
1312 }
1313 }
1314
1315 private void cancelJobsForPackageAndUidLocked(String pkgName, int uid,
1316 @JobParameters.StopReason int reason, int internalReasonCode, String debugReason) {
1317 if ("android".equals(pkgName)) {
1318 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
1319 return;
1320 }
1321 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
1322 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
1323 final JobStatus job = jobsForUid.get(i);
1324 if (job.getSourcePackageName().equals(pkgName)) {
1325 cancelJobImplLocked(job, null, reason, internalReasonCode, debugReason);
1326 }
1327 }
1328 }
1329
1330 /**
1331 * Entry point from client to cancel all jobs originating from their uid.
1332 * This will remove the job from the master list, and cancel the job if it was staged for
1333 * execution or being executed.
1334 *
1335 * @param uid Uid to check against for removal of a job.
1336 */
1337 public boolean cancelJobsForUid(int uid, @JobParameters.StopReason int reason,
1338 int internalReasonCode, String debugReason) {
1339 if (uid == Process.SYSTEM_UID) {
1340 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
1341 return false;
1342 }
1343
1344 boolean jobsCanceled = false;
1345 synchronized (mLock) {
1346 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
1347 for (int i = 0; i < jobsForUid.size(); i++) {
1348 JobStatus toRemove = jobsForUid.get(i);
1349 cancelJobImplLocked(toRemove, null, reason, internalReasonCode, debugReason);
1350 jobsCanceled = true;
1351 }
1352 }
1353 return jobsCanceled;
1354 }
1355
1356 /**
1357 * Entry point from client to cancel the job corresponding to the jobId provided.
1358 * This will remove the job from the master list, and cancel the job if it was staged for
1359 * execution or being executed.
1360 *
1361 * @param uid Uid of the calling client.
1362 * @param jobId Id of the job, provided at schedule-time.
1363 */
1364 private boolean cancelJob(int uid, int jobId, int callingUid,
1365 @JobParameters.StopReason int reason) {
1366 JobStatus toCancel;
1367 synchronized (mLock) {
1368 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
1369 if (toCancel != null) {
1370 cancelJobImplLocked(toCancel, null, reason,
1371 JobParameters.INTERNAL_STOP_REASON_CANCELED,
1372 "cancel() called by app, callingUid=" + callingUid
1373 + " uid=" + uid + " jobId=" + jobId);
1374 }
1375 return (toCancel != null);
1376 }
1377 }
1378
1379 /**
1380 * Cancel the given job, stopping it if it's currently executing. If {@code incomingJob}
1381 * is null, the cancelled job is removed outright from the system. If
1382 * {@code incomingJob} is non-null, it replaces {@code cancelled} in the store of
1383 * currently scheduled jobs.
1384 */
1385 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob,
1386 @JobParameters.StopReason int reason, int internalReasonCode, String debugReason) {
1387 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
1388 cancelled.unprepareLocked();
1389 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
1390 // Remove from pending queue.
1391 if (mPendingJobQueue.remove(cancelled)) {
1392 mJobPackageTracker.noteNonpending(cancelled);
1393 }
1394 mChangedJobList.remove(cancelled);
1395 // Cancel if running.
1396 mConcurrencyManager.stopJobOnServiceContextLocked(
1397 cancelled, reason, internalReasonCode, debugReason);
1398 // If this is a replacement, bring in the new version of the job
1399 if (incomingJob != null) {
1400 if (DEBUG) Slog.i(TAG, "Tracking replacement job " + incomingJob.toShortString());
1401 startTrackingJobLocked(incomingJob, cancelled);
1402 }
1403 reportActiveLocked();
1404 }
1405
1406 void updateUidState(int uid, int procState) {
1407 synchronized (mLock) {
1408 final int prevBias = mUidBiasOverride.get(uid, JobInfo.BIAS_DEFAULT);
1409 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1410 // Only use this if we are exactly the top app. All others can live
1411 // with just the foreground bias. This means that persistent processes
1412 // can never have the top app bias... that is fine.
1413 mUidBiasOverride.put(uid, JobInfo.BIAS_TOP_APP);
1414 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
1415 mUidBiasOverride.put(uid, JobInfo.BIAS_FOREGROUND_SERVICE);
1416 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
1417 mUidBiasOverride.put(uid, JobInfo.BIAS_BOUND_FOREGROUND_SERVICE);
1418 } else {
1419 mUidBiasOverride.delete(uid);
1420 }
1421 final int newBias = mUidBiasOverride.get(uid, JobInfo.BIAS_DEFAULT);
1422 if (prevBias != newBias) {
1423 if (DEBUG) {
1424 Slog.d(TAG, "UID " + uid + " bias changed from " + prevBias + " to " + newBias);
1425 }
1426 for (int c = 0; c < mControllers.size(); ++c) {
1427 mControllers.get(c).onUidBiasChangedLocked(uid, prevBias, newBias);
1428 }
1429 mConcurrencyManager.onUidBiasChangedLocked(prevBias, newBias);
1430 }
1431 }
1432 }
1433
1434 /** Return the current bias of the given UID. */
1435 public int getUidBias(int uid) {
1436 synchronized (mLock) {
1437 return mUidBiasOverride.get(uid, JobInfo.BIAS_DEFAULT);
1438 }
1439 }
1440
1441 @Override
1442 public void onDeviceIdleStateChanged(boolean deviceIdle) {
1443 synchronized (mLock) {
1444 if (DEBUG) {
1445 Slog.d(TAG, "Doze state changed: " + deviceIdle);
1446 }
1447 if (!deviceIdle) {
1448 // When coming out of idle, allow thing to start back up.
1449 if (mReadyToRock) {
1450 if (mLocalDeviceIdleController != null) {
1451 if (!mReportedActive) {
1452 mReportedActive = true;
1453 mLocalDeviceIdleController.setJobsActive(true);
1454 }
1455 }
1456 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1457 }
1458 }
1459 }
1460 }
1461
1462 @Override
1463 public void onRestrictedBucketChanged(List<JobStatus> jobs) {
1464 final int len = jobs.size();
1465 if (len == 0) {
1466 Slog.wtf(TAG, "onRestrictedBucketChanged called with no jobs");
1467 return;
1468 }
1469 synchronized (mLock) {
1470 for (int i = 0; i < len; ++i) {
1471 JobStatus js = jobs.get(i);
1472 for (int j = mRestrictiveControllers.size() - 1; j >= 0; --j) {
1473 // Effective standby bucket can change after this in some situations so use
1474 // the real bucket so that the job is tracked by the controllers.
1475 if (js.getStandbyBucket() == RESTRICTED_INDEX) {
1476 mRestrictiveControllers.get(j).startTrackingRestrictedJobLocked(js);
1477 } else {
1478 mRestrictiveControllers.get(j).stopTrackingRestrictedJobLocked(js);
1479 }
1480 }
1481 }
1482 }
1483 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1484 }
1485
1486 void reportActiveLocked() {
1487 // active is true if pending queue contains jobs OR some job is running.
1488 boolean active = mPendingJobQueue.size() > 0;
1489 if (!active) {
1490 final ArraySet<JobStatus> runningJobs = mConcurrencyManager.getRunningJobsLocked();
1491 for (int i = runningJobs.size() - 1; i >= 0; --i) {
1492 final JobStatus job = runningJobs.valueAt(i);
1493 if (!job.canRunInDoze()) {
1494 // We will report active if we have a job running and it does not have an
1495 // exception that allows it to run in Doze.
1496 active = true;
1497 break;
1498 }
1499 }
1500 }
1501
1502 if (mReportedActive != active) {
1503 mReportedActive = active;
1504 if (mLocalDeviceIdleController != null) {
1505 mLocalDeviceIdleController.setJobsActive(active);
1506 }
1507 }
1508 }
1509
1510 void reportAppUsage(String packageName, int userId) {
1511 // This app just transitioned into interactive use or near equivalent, so we should
1512 // take a look at its job state for feedback purposes.
1513 }
1514
1515 /**
1516 * Initializes the system service.
1517 * <p>
1518 * Subclasses must define a single argument constructor that accepts the context
1519 * and passes it to super.
1520 * </p>
1521 *
1522 * @param context The system server context.
1523 */
1524 public JobSchedulerService(Context context) {
1525 super(context);
1526
1527 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
1528 mActivityManagerInternal = Objects.requireNonNull(
1529 LocalServices.getService(ActivityManagerInternal.class));
1530
1531 mHandler = new JobHandler(context.getMainLooper());
1532 mConstants = new Constants();
1533 mConstantsObserver = new ConstantsObserver();
1534 mJobSchedulerStub = new JobSchedulerStub();
1535
1536 mConcurrencyManager = new JobConcurrencyManager(this);
1537
1538 // Set up the app standby bucketing tracker
1539 mStandbyTracker = new StandbyTracker();
1540 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1541 mQuotaTracker = new CountQuotaTracker(context, QUOTA_CATEGORIZER);
1542 mQuotaTracker.setCountLimit(QUOTA_TRACKER_CATEGORY_SCHEDULE_PERSISTED,
1543 mConstants.API_QUOTA_SCHEDULE_COUNT,
1544 mConstants.API_QUOTA_SCHEDULE_WINDOW_MS);
1545 // Log at most once per minute.
1546 mQuotaTracker.setCountLimit(QUOTA_TRACKER_CATEGORY_SCHEDULE_LOGGED, 1, 60_000);
1547
1548 mAppStandbyInternal = LocalServices.getService(AppStandbyInternal.class);
1549 mAppStandbyInternal.addListener(mStandbyTracker);
1550
1551 // The job store needs to call back
1552 publishLocalService(JobSchedulerInternal.class, new LocalService());
1553
1554 // Initialize the job store and set up any persisted jobs
1555 mJobs = JobStore.initAndGet(this);
1556
1557 mBatteryStateTracker = new BatteryStateTracker();
1558 mBatteryStateTracker.startTracking();
1559
1560 // Create the controllers.
1561 mControllers = new ArrayList<StateController>();
1562 final ConnectivityController connectivityController = new ConnectivityController(this);
1563 mControllers.add(connectivityController);
1564 mControllers.add(new TimeController(this));
1565 final IdleController idleController = new IdleController(this);
1566 mControllers.add(idleController);
1567 final BatteryController batteryController = new BatteryController(this);
1568 mControllers.add(batteryController);
1569 mStorageController = new StorageController(this);
1570 mControllers.add(mStorageController);
1571 final BackgroundJobsController backgroundJobsController =
1572 new BackgroundJobsController(this);
1573 mControllers.add(backgroundJobsController);
1574 mControllers.add(new ContentObserverController(this));
1575 mDeviceIdleJobsController = new DeviceIdleJobsController(this);
1576 mControllers.add(mDeviceIdleJobsController);
1577 mPrefetchController = new PrefetchController(this);
1578 mControllers.add(mPrefetchController);
1579 mQuotaController =
1580 new QuotaController(this, backgroundJobsController, connectivityController);
1581 mControllers.add(mQuotaController);
1582 mControllers.add(new ComponentController(this));
1583 mTareController =
1584 new TareController(this, backgroundJobsController, connectivityController);
1585 mControllers.add(mTareController);
1586
1587 mRestrictiveControllers = new ArrayList<>();
1588 mRestrictiveControllers.add(batteryController);
1589 mRestrictiveControllers.add(connectivityController);
1590 mRestrictiveControllers.add(idleController);
1591
1592 // Create restrictions
1593 mJobRestrictions = new ArrayList<>();
1594 mJobRestrictions.add(new ThermalStatusRestriction(this));
1595
1596 // If the job store determined that it can't yet reschedule persisted jobs,
1597 // we need to start watching the clock.
1598 if (!mJobs.jobTimesInflatedValid()) {
1599 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1600 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1601 }
1602 }
1603
1604 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1605 @Override
1606 public void onReceive(Context context, Intent intent) {
1607 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1608 // When we reach clock sanity, recalculate the temporal windows
1609 // of all affected jobs.
1610 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
1611 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1612
1613 // We've done our job now, so stop watching the time.
1614 context.unregisterReceiver(this);
1615
1616 // And kick off the work to update the affected jobs, using a secondary
1617 // thread instead of chugging away here on the main looper thread.
1618 new Thread(mJobTimeUpdater, "JobSchedulerTimeSetReceiver").start();
1619 }
1620 }
1621 }
1622 };
1623
1624 private final Runnable mJobTimeUpdater = () -> {
1625 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
1626
1627 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1628 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1629 synchronized (mLock) {
1630 // Note: we intentionally both look up the existing affected jobs and replace them
1631 // with recalculated ones inside the same lock lifetime.
1632 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1633
1634 // Now, at each position [i], we have both the existing JobStatus
1635 // and the one that replaces it.
1636 final int N = toAdd.size();
1637 for (int i = 0; i < N; i++) {
1638 final JobStatus oldJob = toRemove.get(i);
1639 final JobStatus newJob = toAdd.get(i);
1640 if (DEBUG) {
1641 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1642 }
1643 cancelJobImplLocked(oldJob, newJob, JobParameters.STOP_REASON_SYSTEM_PROCESSING,
1644 JobParameters.INTERNAL_STOP_REASON_RTC_UPDATED, "deferred rtc calculation");
1645 }
1646 }
1647 };
1648
1649 @Override
1650 public void onStart() {
1651 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1652 }
1653
1654 @Override
1655 public void onBootPhase(int phase) {
1656 if (PHASE_SYSTEM_SERVICES_READY == phase) {
1657 mConstantsObserver.start();
1658 for (StateController controller : mControllers) {
1659 controller.onSystemServicesReady();
1660 }
1661
1662 mAppStateTracker = (AppStateTrackerImpl) Objects.requireNonNull(
1663 LocalServices.getService(AppStateTracker.class));
1664
1665 LocalServices.getService(StorageManagerInternal.class)
1666 .registerCloudProviderChangeListener(new CloudProviderChangeListener());
1667
1668 // Register br for package removals and user removals.
1669 final IntentFilter filter = new IntentFilter();
1670 filter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
1671 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1672 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1673 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1674 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
1675 filter.addDataScheme("package");
1676 getContext().registerReceiverAsUser(
1677 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1678 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1679 userFilter.addAction(Intent.ACTION_USER_ADDED);
1680 getContext().registerReceiverAsUser(
1681 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
1682 try {
1683 ActivityManager.getService().registerUidObserver(mUidObserver,
1684 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
1685 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1686 ActivityManager.PROCESS_STATE_UNKNOWN, null);
1687 } catch (RemoteException e) {
1688 // ignored; both services live in system_server
1689 }
1690
1691 mConcurrencyManager.onSystemReady();
1692
1693 // Remove any jobs that are not associated with any of the current users.
1694 cancelJobsForNonExistentUsers();
1695
1696 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
1697 mJobRestrictions.get(i).onSystemServicesReady();
1698 }
1699 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
1700 synchronized (mLock) {
1701 // Let's go!
1702 mReadyToRock = true;
1703 mLocalDeviceIdleController =
1704 LocalServices.getService(DeviceIdleInternal.class);
1705 mConcurrencyManager.onThirdPartyAppsCanStart();
1706 // Attach jobs to their controllers.
1707 mJobs.forEachJob((job) -> {
1708 for (int controller = 0; controller < mControllers.size(); controller++) {
1709 final StateController sc = mControllers.get(controller);
1710 sc.maybeStartTrackingJobLocked(job, null);
1711 }
1712 });
1713 // GO GO GO!
1714 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1715 }
1716 }
1717 }
1718
1719 /**
1720 * Called when we have a job status object that we need to insert in our
1721 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1722 * about.
1723 */
1724 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1725 if (!jobStatus.isPreparedLocked()) {
1726 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1727 }
1728 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
1729 final boolean update = mJobs.add(jobStatus);
1730 if (mReadyToRock) {
1731 for (int i = 0; i < mControllers.size(); i++) {
1732 StateController controller = mControllers.get(i);
1733 if (update) {
1734 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
1735 }
1736 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
1737 }
1738 }
1739 }
1740
1741 /**
1742 * Called when we want to remove a JobStatus object that we've finished executing.
1743 *
1744 * @return true if the job was removed.
1745 */
1746 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
1747 boolean removeFromPersisted) {
1748 // Deal with any remaining work items in the old job.
1749 jobStatus.stopTrackingJobLocked(incomingJob);
1750
1751 // Remove from store as well as controllers.
1752 final boolean removed = mJobs.remove(jobStatus, removeFromPersisted);
1753 if (!removed) {
1754 // We never create JobStatus objects for the express purpose of removing them, and this
1755 // method is only ever called for jobs that were saved in the JobStore at some point,
1756 // so if we can't find it, something may be wrong. As of Android T, there is a
1757 // legitimate code path where removed is false --- when an actively running job is
1758 // cancelled (eg. via JobScheduler.cancel() or the app scheduling a new job with the
1759 // same job ID), we remove it from the JobStore and tell the JobServiceContext to stop
1760 // running the job. Once the job stops running, we then call this method again.
1761 // TODO: rework code so we don't intentionally call this method twice for the same job
1762 Slog.w(TAG, "Job didn't exist in JobStore: " + jobStatus.toShortString());
1763 }
1764 if (mReadyToRock) {
1765 for (int i = 0; i < mControllers.size(); i++) {
1766 StateController controller = mControllers.get(i);
1767 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
1768 }
1769 }
1770 return removed;
1771 }
1772
1773 /** Return {@code true} if the specified job is currently executing. */
1774 @GuardedBy("mLock")
1775 public boolean isCurrentlyRunningLocked(JobStatus job) {
1776 return mConcurrencyManager.isJobRunningLocked(job);
1777 }
1778
1779 private void noteJobPending(JobStatus job) {
1780 mJobPackageTracker.notePending(job);
1781 }
1782
1783 void noteJobsPending(List<JobStatus> jobs) {
1784 for (int i = jobs.size() - 1; i >= 0; i--) {
1785 noteJobPending(jobs.get(i));
1786 }
1787 }
1788
1789 private void noteJobNonPending(JobStatus job) {
1790 mJobPackageTracker.noteNonpending(job);
1791 }
1792
1793 private void clearPendingJobQueue() {
1794 JobStatus job;
1795 mPendingJobQueue.resetIterator();
1796 while ((job = mPendingJobQueue.next()) != null) {
1797 noteJobNonPending(job);
1798 }
1799 mPendingJobQueue.clear();
1800 }
1801
1802 /**
1803 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1804 * specify an override deadline on a failed job (the failed job will run even though it's not
1805 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1806 * ready job with {@link JobStatus#getNumFailures()} > 0 will be executed.
1807 *
1808 * @param failureToReschedule Provided job status that we will reschedule.
1809 * @return A newly instantiated JobStatus with the same constraints as the last job except
1810 * with adjusted timing constraints.
1811 * @see #maybeQueueReadyJobsForExecutionLocked
1812 */
1813 @VisibleForTesting
1814 JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
1815 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
1816 final JobInfo job = failureToReschedule.getJob();
1817
1818 final long initialBackoffMillis = job.getInitialBackoffMillis();
1819 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1820 long delayMillis;
1821
1822 switch (job.getBackoffPolicy()) {
1823 case JobInfo.BACKOFF_POLICY_LINEAR: {
1824 long backoff = initialBackoffMillis;
1825 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME_MS) {
1826 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME_MS;
1827 }
1828 delayMillis = backoff * backoffAttempts;
1829 } break;
1830 default:
1831 if (DEBUG) {
1832 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1833 }
1834 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1835 long backoff = initialBackoffMillis;
1836 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME_MS) {
1837 backoff = mConstants.MIN_EXP_BACKOFF_TIME_MS;
1838 }
1839 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1840 } break;
1841 }
1842 delayMillis =
1843 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
1844 JobStatus newJob = new JobStatus(failureToReschedule,
1845 elapsedNowMillis + delayMillis,
1846 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
1847 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
1848 if (job.isPeriodic()) {
1849 newJob.setOriginalLatestRunTimeElapsed(
1850 failureToReschedule.getOriginalLatestRunTimeElapsed());
1851 }
1852 for (int ic = 0; ic < mControllers.size(); ic++) {
1853 StateController controller = mControllers.get(ic);
1854 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
1855 }
1856 return newJob;
1857 }
1858
1859 /**
1860 * Maximum time buffer in which JobScheduler will try to optimize periodic job scheduling. This
1861 * does not cause a job's period to be larger than requested (eg: if the requested period is
1862 * shorter than this buffer). This is used to put a limit on when JobScheduler will intervene
1863 * and try to optimize scheduling if the current job finished less than this amount of time to
1864 * the start of the next period
1865 */
1866 private static final long PERIODIC_JOB_WINDOW_BUFFER = 30 * MINUTE_IN_MILLIS;
1867
1868 /** The maximum period a periodic job can have. Anything higher will be clamped down to this. */
1869 public static final long MAX_ALLOWED_PERIOD_MS = 365 * 24 * 60 * 60 * 1000L;
1870
1871 /**
1872 * Called after a periodic has executed so we can reschedule it. We take the last execution
1873 * time of the job to be the time of completion (i.e. the time at which this function is
1874 * called).
1875 * <p>This could be inaccurate b/c the job can run for as long as
1876 * {@link Constants#DEFAULT_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS}, but
1877 * will lead to underscheduling at least, rather than if we had taken the last execution time
1878 * to be the start of the execution.
1879 *
1880 * @return A new job representing the execution criteria for this instantiation of the
1881 * recurring job.
1882 */
1883 @VisibleForTesting
1884 JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
1885 final long elapsedNow = sElapsedRealtimeClock.millis();
1886 final long newLatestRuntimeElapsed;
1887 // Make sure period is in the interval [min_possible_period, max_possible_period].
1888 final long period = Math.max(JobInfo.getMinPeriodMillis(),
1889 Math.min(MAX_ALLOWED_PERIOD_MS, periodicToReschedule.getJob().getIntervalMillis()));
1890 // Make sure flex is in the interval [min_possible_flex, period].
1891 final long flex = Math.max(JobInfo.getMinFlexMillis(),
1892 Math.min(period, periodicToReschedule.getJob().getFlexMillis()));
1893 long rescheduleBuffer = 0;
1894
1895 long olrte = periodicToReschedule.getOriginalLatestRunTimeElapsed();
1896 if (olrte < 0 || olrte == JobStatus.NO_LATEST_RUNTIME) {
1897 Slog.wtf(TAG, "Invalid periodic job original latest run time: " + olrte);
1898 olrte = elapsedNow;
1899 }
1900 final long latestRunTimeElapsed = olrte;
1901
1902 final long diffMs = Math.abs(elapsedNow - latestRunTimeElapsed);
1903 if (elapsedNow > latestRunTimeElapsed) {
1904 // The job ran past its expected run window. Have it count towards the current window
1905 // and schedule a new job for the next window.
1906 if (DEBUG) {
1907 Slog.i(TAG, "Periodic job ran after its intended window by " + diffMs + " ms");
1908 }
1909 long numSkippedWindows = (diffMs / period) + 1; // +1 to include original window
1910 // Determine how far into a single period the job ran, and determine if it's too close
1911 // to the start of the next period. If the difference between the start of the execution
1912 // window and the previous execution time inside of the period is less than the
1913 // threshold, then we say that the job ran too close to the next period.
1914 if (period != flex && (period - flex - (diffMs % period)) <= flex / 6) {
1915 if (DEBUG) {
1916 Slog.d(TAG, "Custom flex job ran too close to next window.");
1917 }
1918 // For custom flex periods, if the job was run too close to the next window,
1919 // skip the next window and schedule for the following one.
1920 numSkippedWindows += 1;
1921 }
1922 newLatestRuntimeElapsed = latestRunTimeElapsed + (period * numSkippedWindows);
1923 } else {
1924 newLatestRuntimeElapsed = latestRunTimeElapsed + period;
1925 if (diffMs < PERIODIC_JOB_WINDOW_BUFFER && diffMs < period / 6) {
1926 // Add a little buffer to the start of the next window so the job doesn't run
1927 // too soon after this completed one.
1928 rescheduleBuffer = Math.min(PERIODIC_JOB_WINDOW_BUFFER, period / 6 - diffMs);
1929 }
1930 }
1931
1932 if (newLatestRuntimeElapsed < elapsedNow) {
1933 Slog.wtf(TAG, "Rescheduling calculated latest runtime in the past: "
1934 + newLatestRuntimeElapsed);
1935 return new JobStatus(periodicToReschedule,
1936 elapsedNow + period - flex, elapsedNow + period,
1937 0 /* backoffAttempt */,
1938 sSystemClock.millis() /* lastSuccessfulRunTime */,
1939 periodicToReschedule.getLastFailedRunTime());
1940 }
1941
1942 final long newEarliestRunTimeElapsed = newLatestRuntimeElapsed
1943 - Math.min(flex, period - rescheduleBuffer);
1944
1945 if (DEBUG) {
1946 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1947 newEarliestRunTimeElapsed / 1000 + ", " + newLatestRuntimeElapsed / 1000
1948 + "]s");
1949 }
1950 return new JobStatus(periodicToReschedule,
1951 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1952 0 /* backoffAttempt */,
1953 sSystemClock.millis() /* lastSuccessfulRunTime */,
1954 periodicToReschedule.getLastFailedRunTime());
1955 }
1956
1957 // JobCompletedListener implementations.
1958
1959 /**
1960 * A job just finished executing. We fetch the
1961 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
1962 * whether we want to reschedule we re-add it to the controllers.
1963 *
1964 * @param jobStatus Completed job.
1965 * @param needsReschedule Whether the implementing class should reschedule this job.
1966 */
1967 @Override
1968 public void onJobCompletedLocked(JobStatus jobStatus, int debugStopReason,
1969 boolean needsReschedule) {
1970 if (DEBUG) {
1971 Slog.d(TAG, "Completed " + jobStatus + ", reason=" + debugStopReason
1972 + ", reschedule=" + needsReschedule);
1973 }
1974
1975 mLastCompletedJobs[mLastCompletedJobIndex] = jobStatus;
1976 mLastCompletedJobTimeElapsed[mLastCompletedJobIndex] = sElapsedRealtimeClock.millis();
1977 mLastCompletedJobIndex = (mLastCompletedJobIndex + 1) % NUM_COMPLETED_JOB_HISTORY;
1978
1979 if (debugStopReason == JobParameters.INTERNAL_STOP_REASON_UNINSTALL
1980 || debugStopReason == JobParameters.INTERNAL_STOP_REASON_DATA_CLEARED) {
1981 // The job should have already been cleared from the rest of the JS tracking. No need
1982 // to go through all that flow again.
1983 jobStatus.unprepareLocked();
1984 reportActiveLocked();
1985 return;
1986 }
1987
1988 // Intentionally not checking expedited job quota here. An app can't find out if it's run
1989 // out of quota when it asks JS to reschedule an expedited job. Instead, the rescheduled
1990 // EJ will just be demoted to a regular job if the app has no EJ quota left.
1991
1992 // If the job wants to be rescheduled, we first need to make the next upcoming
1993 // job so we can transfer any appropriate state over from the previous job when
1994 // we stop it.
1995 final JobStatus rescheduledJob = needsReschedule
1996 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1997 if (rescheduledJob != null
1998 && (debugStopReason == JobParameters.INTERNAL_STOP_REASON_TIMEOUT
1999 || debugStopReason == JobParameters.INTERNAL_STOP_REASON_PREEMPT)) {
2000 rescheduledJob.disallowRunInBatterySaverAndDoze();
2001 }
2002
2003 // Do not write back immediately if this is a periodic job. The job may get lost if system
2004 // shuts down before it is added back.
2005 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
2006 if (DEBUG) {
2007 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
2008 }
2009 JobStatus newJs = mJobs.getJobByUidAndJobId(jobStatus.getUid(), jobStatus.getJobId());
2010 if (newJs != null) {
2011 // This job was stopped because the app scheduled a new job with the same job ID.
2012 // Check if the new job is ready to run.
2013 mHandler.obtainMessage(MSG_CHECK_INDIVIDUAL_JOB, newJs).sendToTarget();
2014 }
2015 return;
2016 }
2017
2018 if (rescheduledJob != null) {
2019 try {
2020 rescheduledJob.prepareLocked();
2021 } catch (SecurityException e) {
2022 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
2023 }
2024 startTrackingJobLocked(rescheduledJob, jobStatus);
2025 } else if (jobStatus.getJob().isPeriodic()) {
2026 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
2027 try {
2028 rescheduledPeriodic.prepareLocked();
2029 } catch (SecurityException e) {
2030 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
2031 }
2032 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
2033 }
2034 jobStatus.unprepareLocked();
2035 reportActiveLocked();
2036 }
2037
2038 // StateChangedListener implementations.
2039
2040 /**
2041 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} to run
2042 * through a list of jobs and start/stop any whose status has changed.
2043 */
2044 @Override
2045 public void onControllerStateChanged(@Nullable ArraySet<JobStatus> changedJobs) {
2046 if (changedJobs == null) {
2047 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2048 } else if (changedJobs.size() > 0) {
2049 synchronized (mLock) {
2050 mChangedJobList.addAll(changedJobs);
2051 }
2052 mHandler.obtainMessage(MSG_CHECK_CHANGED_JOB_LIST).sendToTarget();
2053 }
2054 }
2055
2056 @Override
2057 public void onRunJobNow(JobStatus jobStatus) {
2058 if (jobStatus == null) {
2059 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
2060 } else {
2061 mHandler.obtainMessage(MSG_CHECK_INDIVIDUAL_JOB, jobStatus).sendToTarget();
2062 }
2063 }
2064
2065 final private class JobHandler extends Handler {
2066
2067 public JobHandler(Looper looper) {
2068 super(looper);
2069 }
2070
2071 @Override
2072 public void handleMessage(Message message) {
2073 synchronized (mLock) {
2074 if (!mReadyToRock) {
2075 return;
2076 }
2077 switch (message.what) {
2078 case MSG_CHECK_INDIVIDUAL_JOB: {
2079 JobStatus js = (JobStatus) message.obj;
2080 if (js != null) {
2081 if (isReadyToBeExecutedLocked(js)) {
2082 mJobPackageTracker.notePending(js);
2083 mPendingJobQueue.add(js);
2084 }
2085 mChangedJobList.remove(js);
2086 } else {
2087 Slog.e(TAG, "Given null job to check individually");
2088 }
2089 } break;
2090 case MSG_CHECK_JOB:
2091 if (DEBUG) {
2092 Slog.d(TAG, "MSG_CHECK_JOB");
2093 }
2094 if (mReportedActive) {
2095 // if jobs are currently being run, queue all ready jobs for execution.
2096 queueReadyJobsForExecutionLocked();
2097 } else {
2098 // Check the list of jobs and run some of them if we feel inclined.
2099 maybeQueueReadyJobsForExecutionLocked();
2100 }
2101 break;
2102 case MSG_CHECK_JOB_GREEDY:
2103 if (DEBUG) {
2104 Slog.d(TAG, "MSG_CHECK_JOB_GREEDY");
2105 }
2106 queueReadyJobsForExecutionLocked();
2107 break;
2108 case MSG_CHECK_CHANGED_JOB_LIST:
2109 if (DEBUG) {
2110 Slog.d(TAG, "MSG_CHECK_CHANGED_JOB_LIST");
2111 }
2112 checkChangedJobListLocked();
2113 break;
2114 case MSG_STOP_JOB:
2115 cancelJobImplLocked((JobStatus) message.obj, null, message.arg1,
2116 JobParameters.INTERNAL_STOP_REASON_CONSTRAINTS_NOT_SATISFIED,
2117 "app no longer allowed to run");
2118 break;
2119
2120 case MSG_UID_STATE_CHANGED: {
2121 final int uid = message.arg1;
2122 final int procState = message.arg2;
2123 updateUidState(uid, procState);
2124 break;
2125 }
2126 case MSG_UID_GONE: {
2127 final int uid = message.arg1;
2128 final boolean disabled = message.arg2 != 0;
2129 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2130 if (disabled) {
2131 cancelJobsForUid(uid,
2132 JobParameters.STOP_REASON_BACKGROUND_RESTRICTION,
2133 JobParameters.INTERNAL_STOP_REASON_CONSTRAINTS_NOT_SATISFIED,
2134 "uid gone");
2135 }
2136 synchronized (mLock) {
2137 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
2138 }
2139 break;
2140 }
2141 case MSG_UID_ACTIVE: {
2142 final int uid = message.arg1;
2143 synchronized (mLock) {
2144 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
2145 }
2146 break;
2147 }
2148 case MSG_UID_IDLE: {
2149 final int uid = message.arg1;
2150 final boolean disabled = message.arg2 != 0;
2151 if (disabled) {
2152 cancelJobsForUid(uid,
2153 JobParameters.STOP_REASON_BACKGROUND_RESTRICTION,
2154 JobParameters.INTERNAL_STOP_REASON_CONSTRAINTS_NOT_SATISFIED,
2155 "app uid idle");
2156 }
2157 synchronized (mLock) {
2158 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
2159 }
2160 break;
2161 }
2162
2163 case MSG_CHECK_MEDIA_EXEMPTION: {
2164 final SomeArgs args = (SomeArgs) message.obj;
2165 synchronized (mLock) {
2166 updateMediaBackupExemptionLocked(
2167 args.argi1, (String) args.arg1, (String) args.arg2);
2168 }
2169 args.recycle();
2170 break;
2171 }
2172 }
2173 maybeRunPendingJobsLocked();
2174 }
2175 }
2176 }
2177
2178 /**
2179 * Check if a job is restricted by any of the declared {@link JobRestriction JobRestrictions}.
2180 * Note, that the jobs with {@link JobInfo#BIAS_FOREGROUND_SERVICE} bias or higher may not
2181 * be restricted, thus we won't even perform the check, but simply return null early.
2182 *
2183 * @param job to be checked
2184 * @return the first {@link JobRestriction} restricting the given job that has been found; null
2185 * - if passes all the restrictions or has {@link JobInfo#BIAS_FOREGROUND_SERVICE} bias
2186 * or higher.
2187 */
2188 @GuardedBy("mLock")
2189 JobRestriction checkIfRestricted(JobStatus job) {
2190 if (evaluateJobBiasLocked(job) >= JobInfo.BIAS_FOREGROUND_SERVICE) {
2191 // Jobs with BIAS_FOREGROUND_SERVICE or higher should not be restricted
2192 return null;
2193 }
2194 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
2195 final JobRestriction restriction = mJobRestrictions.get(i);
2196 if (restriction.isJobRestricted(job)) {
2197 return restriction;
2198 }
2199 }
2200 return null;
2201 }
2202
2203 @GuardedBy("mLock")
2204 private void stopNonReadyActiveJobsLocked() {
2205 mConcurrencyManager.stopNonReadyActiveJobsLocked();
2206 }
2207
2208 /**
2209 * Run through list of jobs and execute all possible - at least one is expired so we do
2210 * as many as we can.
2211 */
2212 @GuardedBy("mLock")
2213 private void queueReadyJobsForExecutionLocked() {
2214 // This method will check and capture all ready jobs, so we don't need to keep any messages
2215 // in the queue.
2216 mHandler.removeMessages(MSG_CHECK_JOB_GREEDY);
2217 mHandler.removeMessages(MSG_CHECK_INDIVIDUAL_JOB);
2218 // MSG_CHECK_JOB is a weaker form of _GREEDY. Since we're checking and queueing all ready
2219 // jobs, we don't need to keep any MSG_CHECK_JOB messages in the queue.
2220 mHandler.removeMessages(MSG_CHECK_JOB);
2221 // MSG_CHECK_CHANGED_JOB_LIST is a weaker form of _GREEDY. Since we're checking and queueing
2222 // all ready jobs, we don't need to keep any MSG_CHECK_CHANGED_JOB_LIST messages in the
2223 // queue.
2224 mHandler.removeMessages(MSG_CHECK_CHANGED_JOB_LIST);
2225 mChangedJobList.clear();
2226 if (DEBUG) {
2227 Slog.d(TAG, "queuing all ready jobs for execution:");
2228 }
2229 clearPendingJobQueue();
2230 stopNonReadyActiveJobsLocked();
2231 mJobs.forEachJob(mReadyQueueFunctor);
2232 mReadyQueueFunctor.postProcessLocked();
2233
2234 if (DEBUG) {
2235 final int queuedJobs = mPendingJobQueue.size();
2236 if (queuedJobs == 0) {
2237 Slog.d(TAG, "No jobs pending.");
2238 } else {
2239 Slog.d(TAG, queuedJobs + " jobs queued.");
2240 }
2241 }
2242 }
2243
2244 final class ReadyJobQueueFunctor implements Consumer<JobStatus> {
2245 final ArrayList<JobStatus> newReadyJobs = new ArrayList<>();
2246
2247 @Override
2248 public void accept(JobStatus job) {
2249 if (isReadyToBeExecutedLocked(job)) {
2250 if (DEBUG) {
2251 Slog.d(TAG, " queued " + job.toShortString());
2252 }
2253 newReadyJobs.add(job);
2254 } else {
2255 evaluateControllerStatesLocked(job);
2256 }
2257 }
2258
2259 @GuardedBy("mLock")
2260 private void postProcessLocked() {
2261 noteJobsPending(newReadyJobs);
2262 mPendingJobQueue.addAll(newReadyJobs);
2263
2264 newReadyJobs.clear();
2265 }
2266 }
2267
2268 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
2269
2270 /**
2271 * The state of at least one job has changed. Here is where we could enforce various
2272 * policies on when we want to execute jobs.
2273 */
2274 final class MaybeReadyJobQueueFunctor implements Consumer<JobStatus> {
2275 int forceBatchedCount;
2276 int unbatchedCount;
2277 final List<JobStatus> runnableJobs = new ArrayList<>();
2278
2279 public MaybeReadyJobQueueFunctor() {
2280 reset();
2281 }
2282
2283 @Override
2284 public void accept(JobStatus job) {
2285 final boolean isRunning = isCurrentlyRunningLocked(job);
2286 if (isReadyToBeExecutedLocked(job, false)) {
2287 if (mActivityManagerInternal.isAppStartModeDisabled(job.getUid(),
2288 job.getJob().getService().getPackageName())) {
2289 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
2290 + job.getJob().toString() + " -- package not allowed to start");
2291 if (isRunning) {
2292 mHandler.obtainMessage(MSG_STOP_JOB,
2293 JobParameters.STOP_REASON_BACKGROUND_RESTRICTION, 0, job)
2294 .sendToTarget();
2295 } else if (mPendingJobQueue.remove(job)) {
2296 noteJobNonPending(job);
2297 }
2298 return;
2299 }
2300
2301 final boolean shouldForceBatchJob;
2302 if (job.shouldTreatAsExpeditedJob()) {
2303 // Never batch expedited jobs, even for RESTRICTED apps.
2304 shouldForceBatchJob = false;
2305 } else if (job.getEffectiveStandbyBucket() == RESTRICTED_INDEX) {
2306 // Restricted jobs must always be batched
2307 shouldForceBatchJob = true;
2308 } else if (job.getJob().isPrefetch()) {
2309 // Only relax batching on prefetch jobs if we expect the app to be launched
2310 // relatively soon. PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS defines what
2311 // "relatively soon" means.
2312 final long relativelySoonCutoffTime = sSystemClock.millis()
2313 + mConstants.PREFETCH_FORCE_BATCH_RELAX_THRESHOLD_MS;
2314 shouldForceBatchJob =
2315 mPrefetchController.getNextEstimatedLaunchTimeLocked(job)
2316 > relativelySoonCutoffTime;
2317 } else if (job.getNumFailures() > 0) {
2318 shouldForceBatchJob = false;
2319 } else {
2320 final long nowElapsed = sElapsedRealtimeClock.millis();
2321 final boolean batchDelayExpired = job.getFirstForceBatchedTimeElapsed() > 0
2322 && nowElapsed - job.getFirstForceBatchedTimeElapsed()
2323 >= mConstants.MAX_NON_ACTIVE_JOB_BATCH_DELAY_MS;
2324 shouldForceBatchJob =
2325 mConstants.MIN_READY_NON_ACTIVE_JOBS_COUNT > 1
2326 && job.getEffectiveStandbyBucket() != ACTIVE_INDEX
2327 && job.getEffectiveStandbyBucket() != EXEMPTED_INDEX
2328 && !batchDelayExpired;
2329 }
2330
2331 if (shouldForceBatchJob) {
2332 // Force batching non-ACTIVE jobs. Don't include them in the other counts.
2333 forceBatchedCount++;
2334 if (job.getFirstForceBatchedTimeElapsed() == 0) {
2335 job.setFirstForceBatchedTimeElapsed(sElapsedRealtimeClock.millis());
2336 }
2337 } else {
2338 unbatchedCount++;
2339 }
2340 if (!isRunning) {
2341 runnableJobs.add(job);
2342 }
2343 } else {
2344 if (isRunning) {
2345 final int internalStopReason;
2346 final String debugReason;
2347 if (!job.isReady()) {
2348 if (job.getEffectiveStandbyBucket() == RESTRICTED_INDEX
2349 && job.getStopReason() == JobParameters.STOP_REASON_APP_STANDBY) {
2350 internalStopReason =
2351 JobParameters.INTERNAL_STOP_REASON_RESTRICTED_BUCKET;
2352 debugReason = "cancelled due to restricted bucket";
2353 } else {
2354 internalStopReason =
2355 JobParameters.INTERNAL_STOP_REASON_CONSTRAINTS_NOT_SATISFIED;
2356 debugReason = "cancelled due to unsatisfied constraints";
2357 }
2358 } else {
2359 final JobRestriction restriction = checkIfRestricted(job);
2360 if (restriction != null) {
2361 internalStopReason = restriction.getInternalReason();
2362 debugReason = "restricted due to "
2363 + JobParameters.getInternalReasonCodeDescription(
2364 internalStopReason);
2365 } else {
2366 internalStopReason = JobParameters.INTERNAL_STOP_REASON_UNKNOWN;
2367 debugReason = "couldn't figure out why the job should stop running";
2368 }
2369 }
2370 mConcurrencyManager.stopJobOnServiceContextLocked(job, job.getStopReason(),
2371 internalStopReason, debugReason);
2372 } else if (mPendingJobQueue.remove(job)) {
2373 noteJobNonPending(job);
2374 }
2375 evaluateControllerStatesLocked(job);
2376 }
2377 }
2378
2379 @GuardedBy("mLock")
2380 @VisibleForTesting
2381 void postProcessLocked() {
2382 if (unbatchedCount > 0
2383 || forceBatchedCount >= mConstants.MIN_READY_NON_ACTIVE_JOBS_COUNT) {
2384 if (DEBUG) {
2385 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
2386 }
2387 noteJobsPending(runnableJobs);
2388 mPendingJobQueue.addAll(runnableJobs);
2389 } else {
2390 if (DEBUG) {
2391 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
2392 }
2393 }
2394
2395 // Be ready for next time
2396 reset();
2397 }
2398
2399 @VisibleForTesting
2400 void reset() {
2401 forceBatchedCount = 0;
2402 unbatchedCount = 0;
2403 runnableJobs.clear();
2404 }
2405 }
2406
2407 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
2408
2409 @GuardedBy("mLock")
2410 private void maybeQueueReadyJobsForExecutionLocked() {
2411 mHandler.removeMessages(MSG_CHECK_JOB);
2412 // This method will evaluate all jobs, so we don't need to keep any messages for a subset
2413 // of jobs in the queue.
2414 mHandler.removeMessages(MSG_CHECK_CHANGED_JOB_LIST);
2415 mChangedJobList.clear();
2416 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
2417
2418 clearPendingJobQueue();
2419 stopNonReadyActiveJobsLocked();
2420 mJobs.forEachJob(mMaybeQueueFunctor);
2421 mMaybeQueueFunctor.postProcessLocked();
2422 }
2423
2424 @GuardedBy("mLock")
2425 private void checkChangedJobListLocked() {
2426 mHandler.removeMessages(MSG_CHECK_CHANGED_JOB_LIST);
2427 if (DEBUG) {
2428 Slog.d(TAG, "Check changed jobs...");
2429 }
2430 if (mChangedJobList.size() == 0) {
2431 return;
2432 }
2433
2434 mChangedJobList.forEach(mMaybeQueueFunctor);
2435 mMaybeQueueFunctor.postProcessLocked();
2436 mChangedJobList.clear();
2437 }
2438
2439 @GuardedBy("mLock")
2440 private void updateMediaBackupExemptionLocked(int userId, @Nullable String oldPkg,
2441 @Nullable String newPkg) {
2442 final Predicate<JobStatus> shouldProcessJob =
2443 (job) -> job.getSourceUserId() == userId
2444 && (job.getSourcePackageName().equals(oldPkg)
2445 || job.getSourcePackageName().equals(newPkg));
2446 mJobs.forEachJob(shouldProcessJob,
2447 (job) -> {
2448 if (job.updateMediaBackupExemptionStatus()) {
2449 mChangedJobList.add(job);
2450 }
2451 });
2452 mHandler.sendEmptyMessage(MSG_CHECK_CHANGED_JOB_LIST);
2453 }
2454
2455 /** Returns true if both the calling and source users for the job are started. */
2456 @GuardedBy("mLock")
2457 public boolean areUsersStartedLocked(final JobStatus job) {
2458 boolean sourceStarted = ArrayUtils.contains(mStartedUsers, job.getSourceUserId());
2459 if (job.getUserId() == job.getSourceUserId()) {
2460 return sourceStarted;
2461 }
2462 return sourceStarted && ArrayUtils.contains(mStartedUsers, job.getUserId());
2463 }
2464
2465 /**
2466 * Criteria for moving a job into the pending queue:
2467 * - It's ready.
2468 * - It's not pending.
2469 * - It's not already running on a JSC.
2470 * - The user that requested the job is running.
2471 * - The job's standby bucket has come due to be runnable.
2472 * - The component is enabled and runnable.
2473 */
2474 @VisibleForTesting
2475 @GuardedBy("mLock")
2476 boolean isReadyToBeExecutedLocked(JobStatus job) {
2477 return isReadyToBeExecutedLocked(job, true);
2478 }
2479
2480 @GuardedBy("mLock")
2481 boolean isReadyToBeExecutedLocked(JobStatus job, boolean rejectActive) {
2482 final boolean jobReady = job.isReady();
2483
2484 if (DEBUG) {
2485 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2486 + " ready=" + jobReady);
2487 }
2488
2489 // This is a condition that is very likely to be false (most jobs that are
2490 // scheduled are sitting there, not ready yet) and very cheap to check (just
2491 // a few conditions on data in JobStatus).
2492 if (!jobReady) {
2493 if (job.getSourcePackageName().equals("android.jobscheduler.cts.jobtestapp")) {
2494 Slog.v(TAG, " NOT READY: " + job);
2495 }
2496 return false;
2497 }
2498
2499 final boolean jobExists = mJobs.containsJob(job);
2500 final boolean userStarted = areUsersStartedLocked(job);
2501 final boolean backingUp = mBackingUpUids.get(job.getSourceUid());
2502
2503 if (DEBUG) {
2504 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2505 + " exists=" + jobExists + " userStarted=" + userStarted
2506 + " backingUp=" + backingUp);
2507 }
2508
2509 // These are also fairly cheap to check, though they typically will not
2510 // be conditions we fail.
2511 if (!jobExists || !userStarted || backingUp) {
2512 return false;
2513 }
2514
2515 if (checkIfRestricted(job) != null) {
2516 return false;
2517 }
2518
2519 final boolean jobPending = mPendingJobQueue.contains(job);
2520 final boolean jobActive = rejectActive && mConcurrencyManager.isJobRunningLocked(job);
2521
2522 if (DEBUG) {
2523 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2524 + " pending=" + jobPending + " active=" + jobActive);
2525 }
2526
2527 // These can be a little more expensive (especially jobActive, since we need to
2528 // go through the array of all potentially active jobs), so we are doing them
2529 // later... but still before checking with the package manager!
2530 if (jobPending || jobActive) {
2531 return false;
2532 }
2533
2534 // Validate that the defined package+service is still present & viable.
2535 return isComponentUsable(job);
2536 }
2537
2538 private boolean isComponentUsable(@NonNull JobStatus job) {
2539 final ServiceInfo service = job.serviceInfo;
2540
2541 if (service == null) {
2542 if (DEBUG) {
2543 Slog.v(TAG, "isComponentUsable: " + job.toShortString()
2544 + " component not present");
2545 }
2546 return false;
2547 }
2548
2549 // Everything else checked out so far, so this is the final yes/no check
2550 final boolean appIsBad = mActivityManagerInternal.isAppBad(
2551 service.processName, service.applicationInfo.uid);
2552 if (DEBUG && appIsBad) {
2553 Slog.i(TAG, "App is bad for " + job.toShortString() + " so not runnable");
2554 }
2555 return !appIsBad;
2556 }
2557
2558 @VisibleForTesting
2559 void evaluateControllerStatesLocked(final JobStatus job) {
2560 for (int c = mControllers.size() - 1; c >= 0; --c) {
2561 final StateController sc = mControllers.get(c);
2562 sc.evaluateStateLocked(job);
2563 }
2564 }
2565
2566 /**
2567 * Returns true if non-job constraint components are in place -- if job.isReady() returns true
2568 * and this method returns true, then the job is ready to be executed.
2569 */
2570 public boolean areComponentsInPlaceLocked(JobStatus job) {
2571 // This code is very similar to the code in isReadyToBeExecutedLocked --- it uses the same
2572 // conditions.
2573
2574 final boolean jobExists = mJobs.containsJob(job);
2575 final boolean userStarted = areUsersStartedLocked(job);
2576 final boolean backingUp = mBackingUpUids.get(job.getSourceUid());
2577
2578 if (DEBUG) {
2579 Slog.v(TAG, "areComponentsInPlaceLocked: " + job.toShortString()
2580 + " exists=" + jobExists + " userStarted=" + userStarted
2581 + " backingUp=" + backingUp);
2582 }
2583
2584 // These are also fairly cheap to check, though they typically will not
2585 // be conditions we fail.
2586 if (!jobExists || !userStarted || backingUp) {
2587 return false;
2588 }
2589
2590 final JobRestriction restriction = checkIfRestricted(job);
2591 if (restriction != null) {
2592 if (DEBUG) {
2593 Slog.v(TAG, "areComponentsInPlaceLocked: " + job.toShortString()
2594 + " restricted due to " + restriction.getInternalReason());
2595 }
2596 return false;
2597 }
2598
2599 // Job pending/active doesn't affect the readiness of a job.
2600
2601 // The expensive check: validate that the defined package+service is
2602 // still present & viable.
2603 return isComponentUsable(job);
2604 }
2605
2606 /** Returns the minimum amount of time we should let this job run before timing out. */
2607 public long getMinJobExecutionGuaranteeMs(JobStatus job) {
2608 synchronized (mLock) {
2609 if (job.shouldTreatAsExpeditedJob()) {
2610 // Don't guarantee RESTRICTED jobs more than 5 minutes.
2611 return job.getEffectiveStandbyBucket() != RESTRICTED_INDEX
2612 ? mConstants.RUNTIME_MIN_EJ_GUARANTEE_MS
2613 : Math.min(mConstants.RUNTIME_MIN_EJ_GUARANTEE_MS, 5 * MINUTE_IN_MILLIS);
2614 } else if (job.getEffectivePriority() >= JobInfo.PRIORITY_HIGH) {
2615 return mConstants.RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS;
2616 } else {
2617 return mConstants.RUNTIME_MIN_GUARANTEE_MS;
2618 }
2619 }
2620 }
2621
2622 /** Returns the maximum amount of time this job could run for. */
2623 public long getMaxJobExecutionTimeMs(JobStatus job) {
2624 synchronized (mLock) {
2625 return Math.min(mConstants.RUNTIME_FREE_QUOTA_MAX_LIMIT_MS,
2626 mConstants.USE_TARE_POLICY
2627 ? mTareController.getMaxJobExecutionTimeMsLocked(job)
2628 : mQuotaController.getMaxJobExecutionTimeMsLocked(job));
2629 }
2630 }
2631
2632 /**
2633 * Reconcile jobs in the pending queue against available execution contexts.
2634 * A controller can force a job into the pending queue even if it's already running, but
2635 * here is where we decide whether to actually execute it.
2636 */
2637 void maybeRunPendingJobsLocked() {
2638 if (DEBUG) {
2639 Slog.d(TAG, "pending queue: " + mPendingJobQueue.size() + " jobs.");
2640 }
2641 mConcurrencyManager.assignJobsToContextsLocked();
2642 reportActiveLocked();
2643 }
2644
2645 private int adjustJobBias(int curBias, JobStatus job) {
2646 if (curBias < JobInfo.BIAS_TOP_APP) {
2647 float factor = mJobPackageTracker.getLoadFactor(job);
2648 if (factor >= mConstants.HEAVY_USE_FACTOR) {
2649 curBias += JobInfo.BIAS_ADJ_ALWAYS_RUNNING;
2650 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
2651 curBias += JobInfo.BIAS_ADJ_OFTEN_RUNNING;
2652 }
2653 }
2654 return curBias;
2655 }
2656
2657 int evaluateJobBiasLocked(JobStatus job) {
2658 int bias = job.getBias();
2659 if (bias >= JobInfo.BIAS_BOUND_FOREGROUND_SERVICE) {
2660 return adjustJobBias(bias, job);
2661 }
2662 int override = mUidBiasOverride.get(job.getSourceUid(), 0);
2663 if (override != 0) {
2664 return adjustJobBias(override, job);
2665 }
2666 return adjustJobBias(bias, job);
2667 }
2668
2669 private final class BatteryStateTracker extends BroadcastReceiver {
2670 /**
2671 * Track whether we're "charging", where charging means that we're ready to commit to
2672 * doing work.
2673 */
2674 private boolean mCharging;
2675 /** Keep track of whether the battery is charged enough that we want to do work. */
2676 private boolean mBatteryNotLow;
2677 /** Sequence number of last broadcast. */
2678 private int mLastBatterySeq = -1;
2679
2680 private BroadcastReceiver mMonitor;
2681
2682 BatteryStateTracker() {
2683 }
2684
2685 public void startTracking() {
2686 IntentFilter filter = new IntentFilter();
2687
2688 // Battery health.
2689 filter.addAction(Intent.ACTION_BATTERY_LOW);
2690 filter.addAction(Intent.ACTION_BATTERY_OKAY);
2691 // Charging/not charging.
2692 filter.addAction(BatteryManager.ACTION_CHARGING);
2693 filter.addAction(BatteryManager.ACTION_DISCHARGING);
2694 getTestableContext().registerReceiver(this, filter);
2695
2696 // Initialise tracker state.
2697 BatteryManagerInternal batteryManagerInternal =
2698 LocalServices.getService(BatteryManagerInternal.class);
2699 mBatteryNotLow = !batteryManagerInternal.getBatteryLevelLow();
2700 mCharging = batteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
2701 }
2702
2703 public void setMonitorBatteryLocked(boolean enabled) {
2704 if (enabled) {
2705 if (mMonitor == null) {
2706 mMonitor = new BroadcastReceiver() {
2707 @Override
2708 public void onReceive(Context context, Intent intent) {
2709 onReceiveInternal(intent);
2710 }
2711 };
2712 IntentFilter filter = new IntentFilter();
2713 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
2714 getTestableContext().registerReceiver(mMonitor, filter);
2715 }
2716 } else if (mMonitor != null) {
2717 getTestableContext().unregisterReceiver(mMonitor);
2718 mMonitor = null;
2719 }
2720 }
2721
2722 public boolean isCharging() {
2723 return mCharging;
2724 }
2725
2726 public boolean isBatteryNotLow() {
2727 return mBatteryNotLow;
2728 }
2729
2730 public boolean isMonitoring() {
2731 return mMonitor != null;
2732 }
2733
2734 public int getSeq() {
2735 return mLastBatterySeq;
2736 }
2737
2738 @Override
2739 public void onReceive(Context context, Intent intent) {
2740 onReceiveInternal(intent);
2741 }
2742
2743 @VisibleForTesting
2744 public void onReceiveInternal(Intent intent) {
2745 synchronized (mLock) {
2746 final String action = intent.getAction();
2747 boolean changed = false;
2748 if (Intent.ACTION_BATTERY_LOW.equals(action)) {
2749 if (DEBUG) {
2750 Slog.d(TAG, "Battery life too low @ " + sElapsedRealtimeClock.millis());
2751 }
2752 if (mBatteryNotLow) {
2753 mBatteryNotLow = false;
2754 changed = true;
2755 }
2756 } else if (Intent.ACTION_BATTERY_OKAY.equals(action)) {
2757 if (DEBUG) {
2758 Slog.d(TAG, "Battery high enough @ " + sElapsedRealtimeClock.millis());
2759 }
2760 if (!mBatteryNotLow) {
2761 mBatteryNotLow = true;
2762 changed = true;
2763 }
2764 } else if (BatteryManager.ACTION_CHARGING.equals(action)) {
2765 if (DEBUG) {
2766 Slog.d(TAG, "Battery charging @ " + sElapsedRealtimeClock.millis());
2767 }
2768 if (!mCharging) {
2769 mCharging = true;
2770 changed = true;
2771 }
2772 } else if (BatteryManager.ACTION_DISCHARGING.equals(action)) {
2773 if (DEBUG) {
2774 Slog.d(TAG, "Battery discharging @ " + sElapsedRealtimeClock.millis());
2775 }
2776 if (mCharging) {
2777 mCharging = false;
2778 changed = true;
2779 }
2780 }
2781 mLastBatterySeq =
2782 intent.getIntExtra(BatteryManager.EXTRA_SEQUENCE, mLastBatterySeq);
2783 if (changed) {
2784 for (int c = mControllers.size() - 1; c >= 0; --c) {
2785 mControllers.get(c).onBatteryStateChangedLocked();
2786 }
2787 }
2788 }
2789 }
2790 }
2791
2792 final class LocalService implements JobSchedulerInternal {
2793
2794 /**
2795 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2796 * jobs are always considered pending.
2797 */
2798 @Override
2799 public List<JobInfo> getSystemScheduledPendingJobs() {
2800 synchronized (mLock) {
2801 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
2802 mJobs.forEachJob(Process.SYSTEM_UID, (job) -> {
2803 if (job.getJob().isPeriodic() || !mConcurrencyManager.isJobRunningLocked(job)) {
2804 pendingJobs.add(job.getJob());
2805 }
2806 });
2807 return pendingJobs;
2808 }
2809 }
2810
2811 @Override
2812 public void cancelJobsForUid(int uid, @JobParameters.StopReason int reason,
2813 int internalReasonCode, String debugReason) {
2814 JobSchedulerService.this.cancelJobsForUid(uid, reason, internalReasonCode, debugReason);
2815 }
2816
2817 @Override
2818 public void addBackingUpUid(int uid) {
2819 synchronized (mLock) {
2820 // No need to actually do anything here, since for a full backup the
2821 // activity manager will kill the process which will kill the job (and
2822 // cause it to restart, but now it can't run).
2823 mBackingUpUids.put(uid, true);
2824 }
2825 }
2826
2827 @Override
2828 public void removeBackingUpUid(int uid) {
2829 synchronized (mLock) {
2830 mBackingUpUids.delete(uid);
2831 // If there are any jobs for this uid, we need to rebuild the pending list
2832 // in case they are now ready to run.
2833 if (mJobs.countJobsForUid(uid) > 0) {
2834 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2835 }
2836 }
2837 }
2838
2839 @Override
2840 public void clearAllBackingUpUids() {
2841 synchronized (mLock) {
2842 if (mBackingUpUids.size() > 0) {
2843 mBackingUpUids.clear();
2844 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2845 }
2846 }
2847 }
2848
2849 @Override
2850 public String getCloudMediaProviderPackage(int userId) {
2851 return mCloudMediaProviderPackages.get(userId);
2852 }
2853
2854 @Override
2855 public void reportAppUsage(String packageName, int userId) {
2856 JobSchedulerService.this.reportAppUsage(packageName, userId);
2857 }
2858
2859 @Override
2860 public JobStorePersistStats getPersistStats() {
2861 synchronized (mLock) {
2862 return new JobStorePersistStats(mJobs.getPersistStats());
2863 }
2864 }
2865 }
2866
2867 /**
2868 * Tracking of app assignments to standby buckets
2869 */
2870 final class StandbyTracker extends AppIdleStateChangeListener {
2871
2872 // AppIdleStateChangeListener interface for live updates
2873
2874 @Override
2875 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
2876 boolean idle, int bucket, int reason) {
2877 // QuotaController handles this now.
2878 }
2879
2880 @Override
2881 public void onUserInteractionStarted(String packageName, int userId) {
2882 final int uid = mLocalPM.getPackageUid(packageName,
2883 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2884 if (uid < 0) {
2885 // Quietly ignore; the case is already logged elsewhere
2886 return;
2887 }
2888
2889 long sinceLast = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2890 if (sinceLast > 2 * DateUtils.DAY_IN_MILLIS) {
2891 // Too long ago, not worth logging
2892 sinceLast = 0L;
2893 }
2894 final DeferredJobCounter counter = new DeferredJobCounter();
2895 synchronized (mLock) {
2896 mJobs.forEachJobForSourceUid(uid, counter);
2897 }
2898 if (counter.numDeferred() > 0 || sinceLast > 0) {
2899 BatteryStatsInternal mBatteryStatsInternal = LocalServices.getService
2900 (BatteryStatsInternal.class);
2901 mBatteryStatsInternal.noteJobsDeferred(uid, counter.numDeferred(), sinceLast);
2902 FrameworkStatsLog.write_non_chained(
2903 FrameworkStatsLog.DEFERRED_JOB_STATS_REPORTED, uid, null,
2904 counter.numDeferred(), sinceLast);
2905 }
2906 }
2907 }
2908
2909 static class DeferredJobCounter implements Consumer<JobStatus> {
2910 private int mDeferred = 0;
2911
2912 public int numDeferred() {
2913 return mDeferred;
2914 }
2915
2916 @Override
2917 public void accept(JobStatus job) {
2918 if (job.getWhenStandbyDeferred() > 0) {
2919 mDeferred++;
2920 }
2921 }
2922 }
2923
2924 public static int standbyBucketToBucketIndex(int bucket) {
2925 // Normalize AppStandby constants to indices into our bookkeeping
2926 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) {
2927 return NEVER_INDEX;
2928 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_RARE) {
2929 return RESTRICTED_INDEX;
2930 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
2931 return RARE_INDEX;
2932 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
2933 return FREQUENT_INDEX;
2934 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) {
2935 return WORKING_INDEX;
2936 } else if (bucket > UsageStatsManager.STANDBY_BUCKET_EXEMPTED) {
2937 return ACTIVE_INDEX;
2938 } else {
2939 return EXEMPTED_INDEX;
2940 }
2941 }
2942
2943 // Static to support external callers
2944 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2945 UsageStatsManagerInternal usageStats = LocalServices.getService(
2946 UsageStatsManagerInternal.class);
2947 int bucket = usageStats != null
2948 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2949 : 0;
2950
2951 bucket = standbyBucketToBucketIndex(bucket);
2952
2953 if (DEBUG_STANDBY) {
2954 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2955 }
2956 return bucket;
2957 }
2958
2959 private class CloudProviderChangeListener implements
2960 StorageManagerInternal.CloudProviderChangeListener {
2961
2962 @Override
2963 public void onCloudProviderChanged(int userId, @Nullable String authority) {
2964 final PackageManager pm = getContext()
2965 .createContextAsUser(UserHandle.of(userId), 0)
2966 .getPackageManager();
2967 final ProviderInfo pi = pm.resolveContentProvider(
2968 authority, PackageManager.ComponentInfoFlags.of(0));
2969 final String newPkg = (pi == null) ? null : pi.packageName;
2970 synchronized (mLock) {
2971 final String oldPkg = mCloudMediaProviderPackages.get(userId);
2972 if (!Objects.equals(oldPkg, newPkg)) {
2973 if (DEBUG) {
2974 Slog.d(TAG, "Cloud provider of user " + userId + " changed from " + oldPkg
2975 + " to " + newPkg);
2976 }
2977 mCloudMediaProviderPackages.put(userId, newPkg);
2978 SomeArgs args = SomeArgs.obtain();
2979 args.argi1 = userId;
2980 args.arg1 = oldPkg;
2981 args.arg2 = newPkg;
2982 mHandler.obtainMessage(MSG_CHECK_MEDIA_EXEMPTION, args).sendToTarget();
2983 }
2984 }
2985 }
2986 }
2987
2988 /**
2989 * Binder stub trampoline implementation
2990 */
2991 final class JobSchedulerStub extends IJobScheduler.Stub {
2992 /**
2993 * Cache determination of whether a given app can persist jobs
2994 * key is uid of the calling app; value is undetermined/true/false
2995 */
2996 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2997
2998 // Enforce that only the app itself (or shared uid participant) can schedule a
2999 // job that runs one of the app's services, as well as verifying that the
3000 // named service properly requires the BIND_JOB_SERVICE permission
3001 private void enforceValidJobRequest(int uid, JobInfo job) {
3002 final PackageManager pm = getContext()
3003 .createContextAsUser(UserHandle.getUserHandleForUid(uid), 0)
3004 .getPackageManager();
3005 final ComponentName service = job.getService();
3006 try {
3007 ServiceInfo si = pm.getServiceInfo(service,
3008 PackageManager.MATCH_DIRECT_BOOT_AWARE
3009 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3010 if (si == null) {
3011 throw new IllegalArgumentException("No such service " + service);
3012 }
3013 if (si.applicationInfo.uid != uid) {
3014 throw new IllegalArgumentException("uid " + uid +
3015 " cannot schedule job in " + service.getPackageName());
3016 }
3017 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
3018 throw new IllegalArgumentException("Scheduled service " + service
3019 + " does not require android.permission.BIND_JOB_SERVICE permission");
3020 }
3021 } catch (NameNotFoundException e) {
3022 throw new IllegalArgumentException(
3023 "Tried to schedule job for non-existent component: " + service);
3024 }
3025 }
3026
3027 private boolean canPersistJobs(int pid, int uid) {
3028 // If we get this far we're good to go; all we need to do now is check
3029 // whether the app is allowed to persist its scheduled work.
3030 final boolean canPersist;
3031 synchronized (mPersistCache) {
3032 Boolean cached = mPersistCache.get(uid);
3033 if (cached != null) {
3034 canPersist = cached.booleanValue();
3035 } else {
3036 // Persisting jobs is tantamount to running at boot, so we permit
3037 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
3038 // permission
3039 int result = getContext().checkPermission(
3040 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
3041 canPersist = (result == PackageManager.PERMISSION_GRANTED);
3042 mPersistCache.put(uid, canPersist);
3043 }
3044 }
3045 return canPersist;
3046 }
3047
3048 private void validateJobFlags(JobInfo job, int callingUid) {
3049 job.enforceValidity(
3050 CompatChanges.isChangeEnabled(
3051 JobInfo.DISALLOW_DEADLINES_FOR_PREFETCH_JOBS, callingUid));
3052 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
3053 getContext().enforceCallingOrSelfPermission(
3054 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
3055 }
3056 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
3057 if (callingUid != Process.SYSTEM_UID) {
3058 throw new SecurityException("Job has invalid flags");
3059 }
3060 if (job.isPeriodic()) {
3061 Slog.wtf(TAG, "Periodic jobs mustn't have"
3062 + " FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
3063 }
3064 }
3065 }
3066
3067 // IJobScheduler implementation
3068 @Override
3069 public int schedule(JobInfo job) throws RemoteException {
3070 if (DEBUG) {
3071 Slog.d(TAG, "Scheduling job: " + job.toString());
3072 }
3073 final int pid = Binder.getCallingPid();
3074 final int uid = Binder.getCallingUid();
3075 final int userId = UserHandle.getUserId(uid);
3076
3077 enforceValidJobRequest(uid, job);
3078 if (job.isPersisted()) {
3079 if (!canPersistJobs(pid, uid)) {
3080 throw new IllegalArgumentException("Error: requested job be persisted without"
3081 + " holding RECEIVE_BOOT_COMPLETED permission.");
3082 }
3083 }
3084
3085 validateJobFlags(job, uid);
3086
3087 final long ident = Binder.clearCallingIdentity();
3088 try {
3089 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
3090 null);
3091 } finally {
3092 Binder.restoreCallingIdentity(ident);
3093 }
3094 }
3095
3096 // IJobScheduler implementation
3097 @Override
3098 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
3099 if (DEBUG) {
3100 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
3101 }
3102 final int uid = Binder.getCallingUid();
3103 final int userId = UserHandle.getUserId(uid);
3104
3105 enforceValidJobRequest(uid, job);
3106 if (job.isPersisted()) {
3107 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
3108 }
3109 if (work == null) {
3110 throw new NullPointerException("work is null");
3111 }
3112
3113 work.enforceValidity();
3114 validateJobFlags(job, uid);
3115
3116 final long ident = Binder.clearCallingIdentity();
3117 try {
3118 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
3119 null);
3120 } finally {
3121 Binder.restoreCallingIdentity(ident);
3122 }
3123 }
3124
3125 @Override
3126 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
3127 throws RemoteException {
3128 final int callerUid = Binder.getCallingUid();
3129 if (DEBUG) {
3130 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
3131 + " on behalf of " + packageName + "/");
3132 }
3133
3134 if (packageName == null) {
3135 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
3136 }
3137
3138 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
3139 android.Manifest.permission.UPDATE_DEVICE_STATS);
3140 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
3141 throw new SecurityException("Caller uid " + callerUid
3142 + " not permitted to schedule jobs for other apps");
3143 }
3144
3145 validateJobFlags(job, callerUid);
3146
3147 final long ident = Binder.clearCallingIdentity();
3148 try {
3149 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
3150 packageName, userId, tag);
3151 } finally {
3152 Binder.restoreCallingIdentity(ident);
3153 }
3154 }
3155
3156 @Override
3157 public ParceledListSlice<JobInfo> getAllPendingJobs() throws RemoteException {
3158 final int uid = Binder.getCallingUid();
3159
3160 final long ident = Binder.clearCallingIdentity();
3161 try {
3162 return new ParceledListSlice<>(JobSchedulerService.this.getPendingJobs(uid));
3163 } finally {
3164 Binder.restoreCallingIdentity(ident);
3165 }
3166 }
3167
3168 @Override
3169 public JobInfo getPendingJob(int jobId) throws RemoteException {
3170 final int uid = Binder.getCallingUid();
3171
3172 final long ident = Binder.clearCallingIdentity();
3173 try {
3174 return JobSchedulerService.this.getPendingJob(uid, jobId);
3175 } finally {
3176 Binder.restoreCallingIdentity(ident);
3177 }
3178 }
3179
3180 @Override
3181 public void cancelAll() throws RemoteException {
3182 final int uid = Binder.getCallingUid();
3183 final long ident = Binder.clearCallingIdentity();
3184 try {
3185 JobSchedulerService.this.cancelJobsForUid(uid,
3186 JobParameters.STOP_REASON_CANCELLED_BY_APP,
3187 JobParameters.INTERNAL_STOP_REASON_CANCELED,
3188 "cancelAll() called by app, callingUid=" + uid);
3189 } finally {
3190 Binder.restoreCallingIdentity(ident);
3191 }
3192 }
3193
3194 @Override
3195 public void cancel(int jobId) throws RemoteException {
3196 final int uid = Binder.getCallingUid();
3197
3198 final long ident = Binder.clearCallingIdentity();
3199 try {
3200 JobSchedulerService.this.cancelJob(uid, jobId, uid,
3201 JobParameters.STOP_REASON_CANCELLED_BY_APP);
3202 } finally {
3203 Binder.restoreCallingIdentity(ident);
3204 }
3205 }
3206
3207 /**
3208 * "dumpsys" infrastructure
3209 */
3210 @Override
3211 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3212 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
3213
3214 int filterUid = -1;
3215 boolean proto = false;
3216 if (!ArrayUtils.isEmpty(args)) {
3217 int opti = 0;
3218 while (opti < args.length) {
3219 String arg = args[opti];
3220 if ("-h".equals(arg)) {
3221 dumpHelp(pw);
3222 return;
3223 } else if ("-a".equals(arg)) {
3224 // Ignore, we always dump all.
3225 } else if ("--proto".equals(arg)) {
3226 proto = true;
3227 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
3228 pw.println("Unknown option: " + arg);
3229 return;
3230 } else {
3231 break;
3232 }
3233 opti++;
3234 }
3235 if (opti < args.length) {
3236 String pkg = args[opti];
3237 try {
3238 filterUid = getContext().getPackageManager().getPackageUid(pkg,
3239 PackageManager.MATCH_ANY_USER);
3240 } catch (NameNotFoundException ignored) {
3241 pw.println("Invalid package: " + pkg);
3242 return;
3243 }
3244 }
3245 }
3246
3247 final long identityToken = Binder.clearCallingIdentity();
3248 try {
3249 if (proto) {
3250 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
3251 } else {
3252 JobSchedulerService.this.dumpInternal(new IndentingPrintWriter(pw, " "),
3253 filterUid);
3254 }
3255 } finally {
3256 Binder.restoreCallingIdentity(identityToken);
3257 }
3258 }
3259
3260 @Override
3261 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
3262 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
3263 @NonNull String[] args) {
3264 return (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
3265 this, in.getFileDescriptor(), out.getFileDescriptor(), err.getFileDescriptor(),
3266 args);
3267 }
3268
3269 /**
3270 * <b>For internal system user only!</b>
3271 * Returns a list of all currently-executing jobs.
3272 */
3273 @Override
3274 public List<JobInfo> getStartedJobs() {
3275 final int uid = Binder.getCallingUid();
3276 if (uid != Process.SYSTEM_UID) {
3277 throw new SecurityException("getStartedJobs() is system internal use only.");
3278 }
3279
3280 final ArrayList<JobInfo> runningJobs;
3281
3282 synchronized (mLock) {
3283 final ArraySet<JobStatus> runningJobStatuses =
3284 mConcurrencyManager.getRunningJobsLocked();
3285 runningJobs = new ArrayList<>(runningJobStatuses.size());
3286 for (int i = runningJobStatuses.size() - 1; i >= 0; --i) {
3287 final JobStatus job = runningJobStatuses.valueAt(i);
3288 if (job != null) {
3289 runningJobs.add(job.getJob());
3290 }
3291 }
3292 }
3293
3294 return runningJobs;
3295 }
3296
3297 /**
3298 * <b>For internal system user only!</b>
3299 * Returns a snapshot of the state of all jobs known to the system.
3300 *
3301 * <p class="note">This is a slow operation, so it should be called sparingly.
3302 */
3303 @Override
3304 public ParceledListSlice<JobSnapshot> getAllJobSnapshots() {
3305 final int uid = Binder.getCallingUid();
3306 if (uid != Process.SYSTEM_UID) {
3307 throw new SecurityException("getAllJobSnapshots() is system internal use only.");
3308 }
3309 synchronized (mLock) {
3310 final ArrayList<JobSnapshot> snapshots = new ArrayList<>(mJobs.size());
3311 mJobs.forEachJob((job) -> snapshots.add(
3312 new JobSnapshot(job.getJob(), job.getSatisfiedConstraintFlags(),
3313 isReadyToBeExecutedLocked(job))));
3314 return new ParceledListSlice<>(snapshots);
3315 }
3316 }
3317 }
3318
3319 // Shell command infrastructure: run the given job immediately
3320 int executeRunCommand(String pkgName, int userId, int jobId, boolean satisfied, boolean force) {
3321 Slog.d(TAG, "executeRunCommand(): " + pkgName + "/" + userId
3322 + " " + jobId + " s=" + satisfied + " f=" + force);
3323
3324 try {
3325 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
3326 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
3327 if (uid < 0) {
3328 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
3329 }
3330
3331 synchronized (mLock) {
3332 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
3333 if (js == null) {
3334 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
3335 }
3336
3337 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL
3338 : (satisfied ? JobStatus.OVERRIDE_SORTING : JobStatus.OVERRIDE_SOFT);
3339
3340 // Re-evaluate constraints after the override is set in case one of the overridden
3341 // constraints was preventing another constraint from thinking it needed to update.
3342 for (int c = mControllers.size() - 1; c >= 0; --c) {
3343 mControllers.get(c).reevaluateStateLocked(uid);
3344 }
3345
3346 if (!js.isConstraintsSatisfied()) {
3347 js.overrideState = JobStatus.OVERRIDE_NONE;
3348 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
3349 }
3350
3351 queueReadyJobsForExecutionLocked();
3352 maybeRunPendingJobsLocked();
3353 }
3354 } catch (RemoteException e) {
3355 // can't happen
3356 }
3357 return 0;
3358 }
3359
3360 // Shell command infrastructure: immediately timeout currently executing jobs
3361 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
3362 boolean hasJobId, int jobId) {
3363 if (DEBUG) {
3364 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
3365 }
3366
3367 synchronized (mLock) {
3368 final boolean foundSome = mConcurrencyManager.executeTimeoutCommandLocked(pw,
3369 pkgName, userId, hasJobId, jobId);
3370 if (!foundSome) {
3371 pw.println("No matching executing jobs found.");
3372 }
3373 }
3374 return 0;
3375 }
3376
3377 // Shell command infrastructure: cancel a scheduled job
3378 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
3379 boolean hasJobId, int jobId) {
3380 if (DEBUG) {
3381 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
3382 }
3383
3384 int pkgUid = -1;
3385 try {
3386 IPackageManager pm = AppGlobals.getPackageManager();
3387 pkgUid = pm.getPackageUid(pkgName, 0, userId);
3388 } catch (RemoteException e) { /* can't happen */ }
3389
3390 if (pkgUid < 0) {
3391 pw.println("Package " + pkgName + " not found.");
3392 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
3393 }
3394
3395 if (!hasJobId) {
3396 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
3397 if (!cancelJobsForUid(pkgUid, JobParameters.STOP_REASON_USER,
3398 JobParameters.INTERNAL_STOP_REASON_CANCELED,
3399 "cancel shell command for package")) {
3400 pw.println("No matching jobs found.");
3401 }
3402 } else {
3403 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
3404 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID, JobParameters.STOP_REASON_USER)) {
3405 pw.println("No matching job found.");
3406 }
3407 }
3408
3409 return 0;
3410 }
3411
3412 void setMonitorBattery(boolean enabled) {
3413 synchronized (mLock) {
3414 mBatteryStateTracker.setMonitorBatteryLocked(enabled);
3415 }
3416 }
3417
3418 int getBatterySeq() {
3419 synchronized (mLock) {
3420 return mBatteryStateTracker.getSeq();
3421 }
3422 }
3423
3424 /** Return {@code true} if the device is currently charging. */
3425 public boolean isBatteryCharging() {
3426 synchronized (mLock) {
3427 return mBatteryStateTracker.isCharging();
3428 }
3429 }
3430
3431 /** Return {@code true} if the battery is not low. */
3432 public boolean isBatteryNotLow() {
3433 synchronized (mLock) {
3434 return mBatteryStateTracker.isBatteryNotLow();
3435 }
3436 }
3437
3438 int getStorageSeq() {
3439 synchronized (mLock) {
3440 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
3441 }
3442 }
3443
3444 boolean getStorageNotLow() {
3445 synchronized (mLock) {
3446 return mStorageController != null
3447 ? mStorageController.getTracker().isStorageNotLow() : false;
3448 }
3449 }
3450
3451 // Shell command infrastructure
3452 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
3453 try {
3454 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
3455 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
3456 if (uid < 0) {
3457 pw.print("unknown("); pw.print(pkgName); pw.println(")");
3458 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
3459 }
3460
3461 synchronized (mLock) {
3462 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
3463 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
3464 if (js == null) {
3465 pw.print("unknown("); UserHandle.formatUid(pw, uid);
3466 pw.print("/jid"); pw.print(jobId); pw.println(")");
3467 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
3468 }
3469
3470 boolean printed = false;
3471 if (mPendingJobQueue.contains(js)) {
3472 pw.print("pending");
3473 printed = true;
3474 }
3475 if (mConcurrencyManager.isJobRunningLocked(js)) {
3476 if (printed) {
3477 pw.print(" ");
3478 }
3479 printed = true;
3480 pw.println("active");
3481 }
3482 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
3483 if (printed) {
3484 pw.print(" ");
3485 }
3486 printed = true;
3487 pw.println("user-stopped");
3488 }
3489 if (!ArrayUtils.contains(mStartedUsers, js.getSourceUserId())) {
3490 if (printed) {
3491 pw.print(" ");
3492 }
3493 printed = true;
3494 pw.println("source-user-stopped");
3495 }
3496 if (mBackingUpUids.get(js.getSourceUid())) {
3497 if (printed) {
3498 pw.print(" ");
3499 }
3500 printed = true;
3501 pw.println("backing-up");
3502 }
3503 boolean componentPresent = false;
3504 try {
3505 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3506 js.getServiceComponent(),
3507 PackageManager.MATCH_DIRECT_BOOT_AUTO,
3508 js.getUserId()) != null);
3509 } catch (RemoteException e) {
3510 }
3511 if (!componentPresent) {
3512 if (printed) {
3513 pw.print(" ");
3514 }
3515 printed = true;
3516 pw.println("no-component");
3517 }
3518 if (js.isReady()) {
3519 if (printed) {
3520 pw.print(" ");
3521 }
3522 printed = true;
3523 pw.println("ready");
3524 }
3525 if (!printed) {
3526 pw.print("waiting");
3527 }
3528 pw.println();
3529 }
3530 } catch (RemoteException e) {
3531 // can't happen
3532 }
3533 return 0;
3534 }
3535
3536 void resetExecutionQuota(@NonNull String pkgName, int userId) {
3537 synchronized (mLock) {
3538 mQuotaController.clearAppStatsLocked(userId, pkgName);
3539 }
3540 }
3541
3542 void resetScheduleQuota() {
3543 mQuotaTracker.clear();
3544 }
3545
3546 void triggerDockState(boolean idleState) {
3547 final Intent dockIntent;
3548 if (idleState) {
3549 dockIntent = new Intent(Intent.ACTION_DOCK_IDLE);
3550 } else {
3551 dockIntent = new Intent(Intent.ACTION_DOCK_ACTIVE);
3552 }
3553 dockIntent.setPackage("android");
3554 dockIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
3555 getContext().sendBroadcastAsUser(dockIntent, UserHandle.ALL);
3556 }
3557
3558 static void dumpHelp(PrintWriter pw) {
3559 pw.println("Job Scheduler (jobscheduler) dump options:");
3560 pw.println(" [-h] [package] ...");
3561 pw.println(" -h: print this help");
3562 pw.println(" [package] is an optional package name to limit the output to.");
3563 }
3564
3565 /** Sort jobs by caller UID, then by Job ID. */
3566 private static void sortJobs(List<JobStatus> jobs) {
3567 Collections.sort(jobs, new Comparator<JobStatus>() {
3568 @Override
3569 public int compare(JobStatus o1, JobStatus o2) {
3570 int uid1 = o1.getUid();
3571 int uid2 = o2.getUid();
3572 int id1 = o1.getJobId();
3573 int id2 = o2.getJobId();
3574 if (uid1 != uid2) {
3575 return uid1 < uid2 ? -1 : 1;
3576 }
3577 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
3578 }
3579 });
3580 }
3581
3582 @NeverCompile // Avoid size overhead of debugging code.
3583 void dumpInternal(final IndentingPrintWriter pw, int filterUid) {
3584 final int filterAppId = UserHandle.getAppId(filterUid);
3585 final long now = sSystemClock.millis();
3586 final long nowElapsed = sElapsedRealtimeClock.millis();
3587 final long nowUptime = sUptimeMillisClock.millis();
3588
3589 final Predicate<JobStatus> predicate = (js) -> {
3590 return filterAppId == -1 || UserHandle.getAppId(js.getUid()) == filterAppId
3591 || UserHandle.getAppId(js.getSourceUid()) == filterAppId;
3592 };
3593 synchronized (mLock) {
3594 mConstants.dump(pw);
3595 for (StateController controller : mControllers) {
3596 pw.increaseIndent();
3597 controller.dumpConstants(pw);
3598 pw.decreaseIndent();
3599 }
3600 pw.println();
3601
3602 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
3603 mJobRestrictions.get(i).dumpConstants(pw);
3604 }
3605 pw.println();
3606
3607 mQuotaTracker.dump(pw);
3608 pw.println();
3609
3610 pw.print("Battery charging: ");
3611 pw.println(mBatteryStateTracker.isCharging());
3612 pw.print("Battery not low: ");
3613 pw.println(mBatteryStateTracker.isBatteryNotLow());
3614 if (mBatteryStateTracker.isMonitoring()) {
3615 pw.print("MONITORING: seq=");
3616 pw.println(mBatteryStateTracker.getSeq());
3617 }
3618 pw.println();
3619
3620 pw.println("Started users: " + Arrays.toString(mStartedUsers));
3621 pw.println();
3622
3623 pw.print("Media Cloud Providers: ");
3624 pw.println(mCloudMediaProviderPackages);
3625 pw.println();
3626
3627 pw.print("Registered ");
3628 pw.print(mJobs.size());
3629 pw.println(" jobs:");
3630 pw.increaseIndent();
3631 boolean jobPrinted = false;
3632 if (mJobs.size() > 0) {
3633 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
3634 sortJobs(jobs);
3635 for (JobStatus job : jobs) {
3636 // Skip printing details if the caller requested a filter
3637 if (!predicate.test(job)) {
3638 continue;
3639 }
3640 jobPrinted = true;
3641
3642 pw.print("JOB #"); job.printUniqueId(pw); pw.print(": ");
3643 pw.println(job.toShortStringExceptUniqueId());
3644
3645 pw.increaseIndent();
3646 job.dump(pw, true, nowElapsed);
3647
3648 pw.print("Restricted due to:");
3649 final boolean isRestricted = checkIfRestricted(job) != null;
3650 if (isRestricted) {
3651 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
3652 final JobRestriction restriction = mJobRestrictions.get(i);
3653 if (restriction.isJobRestricted(job)) {
3654 final int reason = restriction.getInternalReason();
3655 pw.print(" ");
3656 pw.print(JobParameters.getInternalReasonCodeDescription(reason));
3657 }
3658 }
3659 } else {
3660 pw.print(" none");
3661 }
3662 pw.println(".");
3663
3664 pw.print("Ready: ");
3665 pw.print(isReadyToBeExecutedLocked(job));
3666 pw.print(" (job=");
3667 pw.print(job.isReady());
3668 pw.print(" user=");
3669 pw.print(areUsersStartedLocked(job));
3670 pw.print(" !restricted=");
3671 pw.print(!isRestricted);
3672 pw.print(" !pending=");
3673 pw.print(!mPendingJobQueue.contains(job));
3674 pw.print(" !active=");
3675 pw.print(!mConcurrencyManager.isJobRunningLocked(job));
3676 pw.print(" !backingup=");
3677 pw.print(!(mBackingUpUids.get(job.getSourceUid())));
3678 pw.print(" comp=");
3679 pw.print(isComponentUsable(job));
3680 pw.println(")");
3681
3682 pw.decreaseIndent();
3683 }
3684 }
3685 if (!jobPrinted) {
3686 pw.println("None.");
3687 }
3688 pw.decreaseIndent();
3689
3690 for (int i = 0; i < mControllers.size(); i++) {
3691 pw.println();
3692 pw.println(mControllers.get(i).getClass().getSimpleName() + ":");
3693 pw.increaseIndent();
3694 mControllers.get(i).dumpControllerStateLocked(pw, predicate);
3695 pw.decreaseIndent();
3696 }
3697
3698 boolean overridePrinted = false;
3699 for (int i = 0; i < mUidBiasOverride.size(); i++) {
3700 int uid = mUidBiasOverride.keyAt(i);
3701 if (filterAppId == -1 || filterAppId == UserHandle.getAppId(uid)) {
3702 if (!overridePrinted) {
3703 overridePrinted = true;
3704 pw.println();
3705 pw.println("Uid bias overrides:");
3706 pw.increaseIndent();
3707 }
3708 pw.print(UserHandle.formatUid(uid));
3709 pw.print(": "); pw.println(mUidBiasOverride.valueAt(i));
3710 }
3711 }
3712 if (overridePrinted) {
3713 pw.decreaseIndent();
3714 }
3715
3716 boolean uidMapPrinted = false;
3717 for (int i = 0; i < mUidToPackageCache.size(); ++i) {
3718 final int uid = mUidToPackageCache.keyAt(i);
3719 if (filterUid != -1 && filterUid != uid) {
3720 continue;
3721 }
3722 if (!uidMapPrinted) {
3723 uidMapPrinted = true;
3724 pw.println();
3725 pw.println("Cached UID->package map:");
3726 pw.increaseIndent();
3727 }
3728 pw.print(uid);
3729 pw.print(": ");
3730 pw.println(mUidToPackageCache.get(uid));
3731 }
3732 if (uidMapPrinted) {
3733 pw.decreaseIndent();
3734 }
3735
3736 boolean backingPrinted = false;
3737 for (int i = 0; i < mBackingUpUids.size(); i++) {
3738 int uid = mBackingUpUids.keyAt(i);
3739 if (filterAppId == -1 || filterAppId == UserHandle.getAppId(uid)) {
3740 if (!backingPrinted) {
3741 pw.println();
3742 pw.println("Backing up uids:");
3743 pw.increaseIndent();
3744 backingPrinted = true;
3745 } else {
3746 pw.print(", ");
3747 }
3748 pw.print(UserHandle.formatUid(uid));
3749 }
3750 }
3751 if (backingPrinted) {
3752 pw.decreaseIndent();
3753 pw.println();
3754 }
3755
3756 pw.println();
3757 mJobPackageTracker.dump(pw, filterAppId);
3758 pw.println();
3759 if (mJobPackageTracker.dumpHistory(pw, filterAppId)) {
3760 pw.println();
3761 }
3762
3763 boolean pendingPrinted = false;
3764 pw.println("Pending queue:");
3765 pw.increaseIndent();
3766 JobStatus job;
3767 int pendingIdx = 0;
3768 mPendingJobQueue.resetIterator();
3769 while ((job = mPendingJobQueue.next()) != null) {
3770 pendingIdx++;
3771 if (!predicate.test(job)) {
3772 continue;
3773 }
3774 if (!pendingPrinted) {
3775 pendingPrinted = true;
3776 }
3777
3778 pw.print("Pending #"); pw.print(pendingIdx); pw.print(": ");
3779 pw.println(job.toShortString());
3780
3781 pw.increaseIndent();
3782 job.dump(pw, false, nowElapsed);
3783 int bias = evaluateJobBiasLocked(job);
3784 pw.print("Evaluated bias: ");
3785 pw.println(JobInfo.getBiasString(bias));
3786
3787 pw.print("Tag: "); pw.println(job.getTag());
3788 pw.print("Enq: ");
3789 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
3790 pw.decreaseIndent();
3791 pw.println();
3792 }
3793 if (!pendingPrinted) {
3794 pw.println("None");
3795 }
3796 pw.decreaseIndent();
3797
3798 pw.println();
3799 mConcurrencyManager.dumpContextInfoLocked(pw, predicate, nowElapsed, nowUptime);
3800
3801 pw.println();
3802 boolean recentPrinted = false;
3803 pw.println("Recently completed jobs:");
3804 pw.increaseIndent();
3805 for (int r = 1; r <= NUM_COMPLETED_JOB_HISTORY; ++r) {
3806 // Print most recent first
3807 final int idx = (mLastCompletedJobIndex + NUM_COMPLETED_JOB_HISTORY - r)
3808 % NUM_COMPLETED_JOB_HISTORY;
3809 job = mLastCompletedJobs[idx];
3810 if (job != null) {
3811 if (!predicate.test(job)) {
3812 continue;
3813 }
3814 recentPrinted = true;
3815 TimeUtils.formatDuration(mLastCompletedJobTimeElapsed[idx], nowElapsed, pw);
3816 pw.println();
3817 // Double indent for readability
3818 pw.increaseIndent();
3819 pw.increaseIndent();
3820 pw.println(job.toShortString());
3821 job.dump(pw, true, nowElapsed);
3822 pw.decreaseIndent();
3823 pw.decreaseIndent();
3824 }
3825 }
3826 if (!recentPrinted) {
3827 pw.println("None");
3828 }
3829 pw.decreaseIndent();
3830 pw.println();
3831
3832 if (filterUid == -1) {
3833 pw.println();
3834 pw.print("mReadyToRock="); pw.println(mReadyToRock);
3835 pw.print("mReportedActive="); pw.println(mReportedActive);
3836 }
3837 pw.println();
3838
3839 mConcurrencyManager.dumpLocked(pw, now, nowElapsed);
3840
3841 pw.println();
3842 pw.print("PersistStats: ");
3843 pw.println(mJobs.getPersistStats());
3844 }
3845 pw.println();
3846 }
3847
3848 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
3849 ProtoOutputStream proto = new ProtoOutputStream(fd);
3850 final int filterAppId = UserHandle.getAppId(filterUid);
3851 final long now = sSystemClock.millis();
3852 final long nowElapsed = sElapsedRealtimeClock.millis();
3853 final long nowUptime = sUptimeMillisClock.millis();
3854 final Predicate<JobStatus> predicate = (js) -> {
3855 return filterAppId == -1 || UserHandle.getAppId(js.getUid()) == filterAppId
3856 || UserHandle.getAppId(js.getSourceUid()) == filterAppId;
3857 };
3858
3859 synchronized (mLock) {
3860 final long settingsToken = proto.start(JobSchedulerServiceDumpProto.SETTINGS);
3861 mConstants.dump(proto);
3862 for (StateController controller : mControllers) {
3863 controller.dumpConstants(proto);
3864 }
3865 proto.end(settingsToken);
3866
3867 for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
3868 mJobRestrictions.get(i).dumpConstants(proto);
3869 }
3870
3871 for (int u : mStartedUsers) {
3872 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
3873 }
3874
3875 mQuotaTracker.dump(proto, JobSchedulerServiceDumpProto.QUOTA_TRACKER);
3876
3877 if (mJobs.size() > 0) {
3878 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
3879 sortJobs(jobs);
3880 for (JobStatus job : jobs) {
3881 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
3882 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
3883
3884 // Skip printing details if the caller requested a filter
3885 if (!predicate.test(job)) {
3886 continue;
3887 }
3888
3889 job.dump(proto,
3890 JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
3891
3892 proto.write(
3893 JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY_TO_BE_EXECUTED,
3894 isReadyToBeExecutedLocked(job));
3895 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
3896 job.isReady());
3897 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.ARE_USERS_STARTED,
3898 areUsersStartedLocked(job));
3899 proto.write(
3900 JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_RESTRICTED,
3901 checkIfRestricted(job) != null);
3902 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
3903 mPendingJobQueue.contains(job));
3904 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
3905 mConcurrencyManager.isJobRunningLocked(job));
3906 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
3907 mBackingUpUids.get(job.getSourceUid()));
3908 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_USABLE,
3909 isComponentUsable(job));
3910
3911 for (JobRestriction restriction : mJobRestrictions) {
3912 final long restrictionsToken = proto.start(
3913 JobSchedulerServiceDumpProto.RegisteredJob.RESTRICTIONS);
3914 proto.write(JobSchedulerServiceDumpProto.JobRestriction.REASON,
3915 restriction.getInternalReason());
3916 proto.write(JobSchedulerServiceDumpProto.JobRestriction.IS_RESTRICTING,
3917 restriction.isJobRestricted(job));
3918 proto.end(restrictionsToken);
3919 }
3920
3921 proto.end(rjToken);
3922 }
3923 }
3924 for (StateController controller : mControllers) {
3925 controller.dumpControllerStateLocked(
3926 proto, JobSchedulerServiceDumpProto.CONTROLLERS, predicate);
3927 }
3928 for (int i = 0; i < mUidBiasOverride.size(); i++) {
3929 int uid = mUidBiasOverride.keyAt(i);
3930 if (filterAppId == -1 || filterAppId == UserHandle.getAppId(uid)) {
3931 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3932 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3933 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3934 mUidBiasOverride.valueAt(i));
3935 proto.end(pToken);
3936 }
3937 }
3938 for (int i = 0; i < mBackingUpUids.size(); i++) {
3939 int uid = mBackingUpUids.keyAt(i);
3940 if (filterAppId == -1 || filterAppId == UserHandle.getAppId(uid)) {
3941 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3942 }
3943 }
3944
3945 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3946 filterAppId);
3947 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3948 filterAppId);
3949
3950 JobStatus job;
3951 mPendingJobQueue.resetIterator();
3952 while ((job = mPendingJobQueue.next()) != null) {
3953 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3954
3955 job.writeToShortProto(proto, PendingJob.INFO);
3956 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
3957 proto.write(PendingJob.EVALUATED_PRIORITY, evaluateJobBiasLocked(job));
3958 proto.write(PendingJob.PENDING_DURATION_MS, nowUptime - job.madePending);
3959
3960 proto.end(pjToken);
3961 }
3962 if (filterUid == -1) {
3963 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3964 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3965 }
3966 mConcurrencyManager.dumpProtoLocked(proto,
3967 JobSchedulerServiceDumpProto.CONCURRENCY_MANAGER, now, nowElapsed);
3968
3969 mJobs.getPersistStats().dumpDebug(proto, JobSchedulerServiceDumpProto.PERSIST_STATS);
3970 }
3971
3972 proto.flush();
3973 }
3974 }