blob: 4f8b1dcc6bb468c468f3474bbe466a37c516efbc [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.job;
18
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070019import static com.android.server.job.JobSchedulerService.sElapsedRealtimeClock;
20import static com.android.server.job.JobSchedulerService.sSystemClock;
21
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -070022import android.annotation.Nullable;
Dianne Hackborna47223f2017-03-30 13:49:13 -070023import android.app.ActivityManager;
24import android.app.IActivityManager;
Christopher Tate7060b042014-06-09 19:50:00 -070025import android.app.job.JobInfo;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070026import android.content.ComponentName;
Christopher Tate7060b042014-06-09 19:50:00 -070027import android.content.Context;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070028import android.net.NetworkRequest;
Christopher Tate7060b042014-06-09 19:50:00 -070029import android.os.Environment;
30import android.os.Handler;
31import android.os.PersistableBundle;
Makoto Onukie7b02982017-08-24 14:23:36 -070032import android.os.Process;
Dianne Hackborne17b4452018-01-10 13:15:40 -080033import android.os.SystemClock;
Christopher Tate7060b042014-06-09 19:50:00 -070034import android.os.UserHandle;
Matthew Williamsfa8e5082015-10-15 15:59:12 -070035import android.text.format.DateUtils;
Christopher Tate7060b042014-06-09 19:50:00 -070036import android.util.ArraySet;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070037import android.util.AtomicFile;
Christopher Tate7060b042014-06-09 19:50:00 -070038import android.util.Pair;
39import android.util.Slog;
Christopher Tate2f36fd62016-02-18 18:36:08 -080040import android.util.SparseArray;
Christopher Tate7060b042014-06-09 19:50:00 -070041import android.util.Xml;
42
43import com.android.internal.annotations.VisibleForTesting;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070044import com.android.internal.util.ArrayUtils;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070045import com.android.internal.util.BitUtils;
Christopher Tate7060b042014-06-09 19:50:00 -070046import com.android.internal.util.FastXmlSerializer;
47import com.android.server.IoThread;
Christopher Tatea732f012017-10-26 17:26:53 -070048import com.android.server.LocalServices;
Makoto Onukie7b02982017-08-24 14:23:36 -070049import com.android.server.job.JobSchedulerInternal.JobStorePersistStats;
Christopher Tate7060b042014-06-09 19:50:00 -070050import com.android.server.job.controllers.JobStatus;
51
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070052import org.xmlpull.v1.XmlPullParser;
53import org.xmlpull.v1.XmlPullParserException;
54import org.xmlpull.v1.XmlSerializer;
55
Christopher Tate7060b042014-06-09 19:50:00 -070056import java.io.ByteArrayOutputStream;
57import java.io.File;
58import java.io.FileInputStream;
59import java.io.FileNotFoundException;
60import java.io.FileOutputStream;
61import java.io.IOException;
Wojciech Staszkiewicz4f117542015-05-08 14:58:46 +010062import java.nio.charset.StandardCharsets;
Christopher Tate7060b042014-06-09 19:50:00 -070063import java.util.ArrayList;
Christopher Tate7060b042014-06-09 19:50:00 -070064import java.util.List;
Shreyas Basarged09973b2015-12-16 18:10:05 +000065import java.util.Set;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -070066import java.util.function.Consumer;
Suprabh Shukla7b21bb52018-01-26 17:19:28 -080067import java.util.function.Predicate;
Christopher Tate7060b042014-06-09 19:50:00 -070068
Christopher Tate7060b042014-06-09 19:50:00 -070069/**
Matthew Williams48a30db2014-09-23 13:39:36 -070070 * Maintains the master list of jobs that the job scheduler is tracking. These jobs are compared by
71 * reference, so none of the functions in this class should make a copy.
72 * Also handles read/write of persisted jobs.
Christopher Tate7060b042014-06-09 19:50:00 -070073 *
74 * Note on locking:
75 * All callers to this class must <strong>lock on the class object they are calling</strong>.
76 * This is important b/c {@link com.android.server.job.JobStore.WriteJobsMapToDiskRunnable}
77 * and {@link com.android.server.job.JobStore.ReadJobMapFromDiskRunnable} lock on that
78 * object.
Makoto Onuki15407842018-01-19 14:23:11 -080079 *
80 * Test:
81 * atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/job/JobStoreTest.java
Christopher Tate7060b042014-06-09 19:50:00 -070082 */
Dianne Hackborn6466c1c2017-06-13 10:33:19 -070083public final class JobStore {
Christopher Tate7060b042014-06-09 19:50:00 -070084 private static final String TAG = "JobStore";
85 private static final boolean DEBUG = JobSchedulerService.DEBUG;
86
87 /** Threshold to adjust how often we want to write to the db. */
88 private static final int MAX_OPS_BEFORE_WRITE = 1;
Christopher Tate616541d2017-07-26 14:27:38 -070089
Dianne Hackborn33d31c52016-02-16 10:30:33 -080090 final Object mLock;
Suprabh Shukla7b21bb52018-01-26 17:19:28 -080091 final JobSet mJobSet; // per-caller-uid and per-source-uid tracking
Christopher Tate7060b042014-06-09 19:50:00 -070092 final Context mContext;
93
Christopher Tate616541d2017-07-26 14:27:38 -070094 // Bookkeeping around incorrect boot-time system clock
95 private final long mXmlTimestamp;
96 private boolean mRtcGood;
97
Christopher Tate7060b042014-06-09 19:50:00 -070098 private int mDirtyOperations;
99
100 private static final Object sSingletonLock = new Object();
101 private final AtomicFile mJobsFile;
102 /** Handler backed by IoThread for writing to disk. */
103 private final Handler mIoHandler = IoThread.getHandler();
104 private static JobStore sSingleton;
105
Makoto Onukie7b02982017-08-24 14:23:36 -0700106 private JobStorePersistStats mPersistInfo = new JobStorePersistStats();
107
Christopher Tate7060b042014-06-09 19:50:00 -0700108 /** Used by the {@link JobSchedulerService} to instantiate the JobStore. */
109 static JobStore initAndGet(JobSchedulerService jobManagerService) {
110 synchronized (sSingletonLock) {
111 if (sSingleton == null) {
112 sSingleton = new JobStore(jobManagerService.getContext(),
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800113 jobManagerService.getLock(), Environment.getDataDirectory());
Christopher Tate7060b042014-06-09 19:50:00 -0700114 }
115 return sSingleton;
116 }
117 }
118
Matthew Williams01ac45b2014-07-22 20:44:12 -0700119 /**
120 * @return A freshly initialized job store object, with no loaded jobs.
121 */
Christopher Tate7060b042014-06-09 19:50:00 -0700122 @VisibleForTesting
Matthew Williams01ac45b2014-07-22 20:44:12 -0700123 public static JobStore initAndGetForTesting(Context context, File dataDir) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800124 JobStore jobStoreUnderTest = new JobStore(context, new Object(), dataDir);
Matthew Williams01ac45b2014-07-22 20:44:12 -0700125 jobStoreUnderTest.clear();
126 return jobStoreUnderTest;
Christopher Tate7060b042014-06-09 19:50:00 -0700127 }
128
Matthew Williams01ac45b2014-07-22 20:44:12 -0700129 /**
130 * Construct the instance of the job store. This results in a blocking read from disk.
131 */
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800132 private JobStore(Context context, Object lock, File dataDir) {
133 mLock = lock;
Christopher Tate7060b042014-06-09 19:50:00 -0700134 mContext = context;
135 mDirtyOperations = 0;
136
137 File systemDir = new File(dataDir, "system");
138 File jobDir = new File(systemDir, "job");
139 jobDir.mkdirs();
Dianne Hackborne17b4452018-01-10 13:15:40 -0800140 mJobsFile = new AtomicFile(new File(jobDir, "jobs.xml"), "jobs");
Christopher Tate7060b042014-06-09 19:50:00 -0700141
Christopher Tate2f36fd62016-02-18 18:36:08 -0800142 mJobSet = new JobSet();
Christopher Tate7060b042014-06-09 19:50:00 -0700143
Christopher Tate616541d2017-07-26 14:27:38 -0700144 // If the current RTC is earlier than the timestamp on our persisted jobs file,
145 // we suspect that the RTC is uninitialized and so we cannot draw conclusions
146 // about persisted job scheduling.
147 //
148 // Note that if the persisted jobs file does not exist, we proceed with the
149 // assumption that the RTC is good. This is less work and is safe: if the
150 // clock updates to sanity then we'll be saving the persisted jobs file in that
151 // correct state, which is normal; or we'll wind up writing the jobs file with
152 // an incorrect historical timestamp. That's fine; at worst we'll reboot with
153 // a *correct* timestamp, see a bunch of overdue jobs, and run them; then
154 // settle into normal operation.
155 mXmlTimestamp = mJobsFile.getLastModifiedTime();
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700156 mRtcGood = (sSystemClock.millis() > mXmlTimestamp);
Christopher Tate616541d2017-07-26 14:27:38 -0700157
158 readJobMapFromDisk(mJobSet, mRtcGood);
159 }
160
161 public boolean jobTimesInflatedValid() {
162 return mRtcGood;
163 }
164
165 public boolean clockNowValidToInflate(long now) {
166 return now >= mXmlTimestamp;
167 }
168
169 /**
170 * Find all the jobs that were affected by RTC clock uncertainty at boot time. Returns
171 * parallel lists of the existing JobStatus objects and of new, equivalent JobStatus instances
172 * with now-corrected time bounds.
173 */
174 public void getRtcCorrectedJobsLocked(final ArrayList<JobStatus> toAdd,
175 final ArrayList<JobStatus> toRemove) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700176 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate616541d2017-07-26 14:27:38 -0700177
178 // Find the jobs that need to be fixed up, collecting them for post-iteration
179 // replacement with their new versions
180 forEachJob(job -> {
181 final Pair<Long, Long> utcTimes = job.getPersistedUtcTimes();
182 if (utcTimes != null) {
183 Pair<Long, Long> elapsedRuntimes =
184 convertRtcBoundsToElapsed(utcTimes, elapsedNow);
Christopher Tatea732f012017-10-26 17:26:53 -0700185 toAdd.add(new JobStatus(job, job.getBaseHeartbeat(),
186 elapsedRuntimes.first, elapsedRuntimes.second,
Christopher Tate616541d2017-07-26 14:27:38 -0700187 0, job.getLastSuccessfulRunTime(), job.getLastFailedRunTime()));
188 toRemove.add(job);
189 }
190 });
Christopher Tate7060b042014-06-09 19:50:00 -0700191 }
192
193 /**
194 * Add a job to the master list, persisting it if necessary. If the JobStatus already exists,
195 * it will be replaced.
196 * @param jobStatus Job to add.
197 * @return Whether or not an equivalent JobStatus was replaced by this operation.
198 */
199 public boolean add(JobStatus jobStatus) {
200 boolean replaced = mJobSet.remove(jobStatus);
201 mJobSet.add(jobStatus);
202 if (jobStatus.isPersisted()) {
203 maybeWriteStatusToDiskAsync();
204 }
205 if (DEBUG) {
206 Slog.d(TAG, "Added job status to store: " + jobStatus);
207 }
208 return replaced;
209 }
210
Matthew Williams48a30db2014-09-23 13:39:36 -0700211 boolean containsJob(JobStatus jobStatus) {
212 return mJobSet.contains(jobStatus);
213 }
214
Christopher Tate7060b042014-06-09 19:50:00 -0700215 public int size() {
216 return mJobSet.size();
217 }
218
Makoto Onukie7b02982017-08-24 14:23:36 -0700219 public JobStorePersistStats getPersistStats() {
220 return mPersistInfo;
221 }
222
Christopher Tate2f36fd62016-02-18 18:36:08 -0800223 public int countJobsForUid(int uid) {
224 return mJobSet.countJobsForUid(uid);
225 }
226
Christopher Tate7060b042014-06-09 19:50:00 -0700227 /**
228 * Remove the provided job. Will also delete the job if it was persisted.
Shreyas Basarge73f10252016-02-11 17:06:13 +0000229 * @param writeBack If true, the job will be deleted (if it was persisted) immediately.
Christopher Tate7060b042014-06-09 19:50:00 -0700230 * @return Whether or not the job existed to be removed.
231 */
Shreyas Basarge73f10252016-02-11 17:06:13 +0000232 public boolean remove(JobStatus jobStatus, boolean writeBack) {
Christopher Tate7060b042014-06-09 19:50:00 -0700233 boolean removed = mJobSet.remove(jobStatus);
234 if (!removed) {
235 if (DEBUG) {
236 Slog.d(TAG, "Couldn't remove job: didn't exist: " + jobStatus);
237 }
238 return false;
239 }
Shreyas Basarge73f10252016-02-11 17:06:13 +0000240 if (writeBack && jobStatus.isPersisted()) {
Matthew Williams900c67f2014-07-09 12:46:53 -0700241 maybeWriteStatusToDiskAsync();
242 }
Christopher Tate7060b042014-06-09 19:50:00 -0700243 return removed;
244 }
245
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -0700246 /**
247 * Remove the jobs of users not specified in the whitelist.
248 * @param whitelist Array of User IDs whose jobs are not to be removed.
249 */
250 public void removeJobsOfNonUsers(int[] whitelist) {
251 mJobSet.removeJobsOfNonUsers(whitelist);
252 }
253
Christopher Tate7060b042014-06-09 19:50:00 -0700254 @VisibleForTesting
255 public void clear() {
256 mJobSet.clear();
257 maybeWriteStatusToDiskAsync();
258 }
259
Matthew Williams48a30db2014-09-23 13:39:36 -0700260 /**
261 * @param userHandle User for whom we are querying the list of jobs.
Suprabh Shukla106203b2017-11-02 21:23:44 -0700262 * @return A list of all the jobs scheduled for the provided user. Never null.
Matthew Williams48a30db2014-09-23 13:39:36 -0700263 */
Christopher Tate7060b042014-06-09 19:50:00 -0700264 public List<JobStatus> getJobsByUser(int userHandle) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800265 return mJobSet.getJobsByUser(userHandle);
Christopher Tate7060b042014-06-09 19:50:00 -0700266 }
267
268 /**
269 * @param uid Uid of the requesting app.
Matthew Williams48a30db2014-09-23 13:39:36 -0700270 * @return All JobStatus objects for a given uid from the master list. Never null.
Christopher Tate7060b042014-06-09 19:50:00 -0700271 */
272 public List<JobStatus> getJobsByUid(int uid) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800273 return mJobSet.getJobsByUid(uid);
Christopher Tate7060b042014-06-09 19:50:00 -0700274 }
275
276 /**
277 * @param uid Uid of the requesting app.
278 * @param jobId Job id, specified at schedule-time.
279 * @return the JobStatus that matches the provided uId and jobId, or null if none found.
280 */
281 public JobStatus getJobByUidAndJobId(int uid, int jobId) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800282 return mJobSet.get(uid, jobId);
Christopher Tate7060b042014-06-09 19:50:00 -0700283 }
284
285 /**
Christopher Tate2f36fd62016-02-18 18:36:08 -0800286 * Iterate over the set of all jobs, invoking the supplied functor on each. This is for
287 * customers who need to examine each job; we'd much rather not have to generate
288 * transient unified collections for them to iterate over and then discard, or creating
289 * iterators every time a client needs to perform a sweep.
Christopher Tate7060b042014-06-09 19:50:00 -0700290 */
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -0700291 public void forEachJob(Consumer<JobStatus> functor) {
292 mJobSet.forEachJob(null, functor);
Christopher Tate2f36fd62016-02-18 18:36:08 -0800293 }
294
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -0700295 public void forEachJob(@Nullable Predicate<JobStatus> filterPredicate,
296 Consumer<JobStatus> functor) {
297 mJobSet.forEachJob(filterPredicate, functor);
298 }
299
300 public void forEachJob(int uid, Consumer<JobStatus> functor) {
Shreyas Basargecbf5ae92016-03-08 16:13:06 +0000301 mJobSet.forEachJob(uid, functor);
302 }
303
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -0700304 public void forEachJobForSourceUid(int sourceUid, Consumer<JobStatus> functor) {
Suprabh Shukla106203b2017-11-02 21:23:44 -0700305 mJobSet.forEachJobForSourceUid(sourceUid, functor);
306 }
307
Christopher Tate7060b042014-06-09 19:50:00 -0700308 /** Version of the db schema. */
309 private static final int JOBS_FILE_VERSION = 0;
310 /** Tag corresponds to constraints this job needs. */
311 private static final String XML_TAG_PARAMS_CONSTRAINTS = "constraints";
312 /** Tag corresponds to execution parameters. */
313 private static final String XML_TAG_PERIODIC = "periodic";
314 private static final String XML_TAG_ONEOFF = "one-off";
315 private static final String XML_TAG_EXTRAS = "extras";
316
317 /**
318 * Every time the state changes we write all the jobs in one swath, instead of trying to
319 * track incremental changes.
Christopher Tate7060b042014-06-09 19:50:00 -0700320 */
321 private void maybeWriteStatusToDiskAsync() {
322 mDirtyOperations++;
323 if (mDirtyOperations >= MAX_OPS_BEFORE_WRITE) {
324 if (DEBUG) {
325 Slog.v(TAG, "Writing jobs to disk.");
326 }
Christopher Tate616541d2017-07-26 14:27:38 -0700327 mIoHandler.removeCallbacks(mWriteRunnable);
328 mIoHandler.post(mWriteRunnable);
Christopher Tate7060b042014-06-09 19:50:00 -0700329 }
330 }
331
Matthew Williams01ac45b2014-07-22 20:44:12 -0700332 @VisibleForTesting
Christopher Tate616541d2017-07-26 14:27:38 -0700333 public void readJobMapFromDisk(JobSet jobSet, boolean rtcGood) {
334 new ReadJobMapFromDiskRunnable(jobSet, rtcGood).run();
Christopher Tate7060b042014-06-09 19:50:00 -0700335 }
336
337 /**
338 * Runnable that writes {@link #mJobSet} out to xml.
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800339 * NOTE: This Runnable locks on mLock
Christopher Tate7060b042014-06-09 19:50:00 -0700340 */
Christopher Tate616541d2017-07-26 14:27:38 -0700341 private final Runnable mWriteRunnable = new Runnable() {
Christopher Tate7060b042014-06-09 19:50:00 -0700342 @Override
343 public void run() {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700344 final long startElapsed = sElapsedRealtimeClock.millis();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800345 final List<JobStatus> storeCopy = new ArrayList<JobStatus>();
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800346 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800347 // Clone the jobs so we can release the lock before writing.
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -0700348 mJobSet.forEachJob(null, (job) -> {
349 if (job.isPersisted()) {
350 storeCopy.add(new JobStatus(job));
Shreyas Basarge7ef490f2015-12-03 16:45:22 +0000351 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800352 });
Christopher Tate7060b042014-06-09 19:50:00 -0700353 }
Christopher Tate2f36fd62016-02-18 18:36:08 -0800354 writeJobsMapImpl(storeCopy);
Christopher Tate616541d2017-07-26 14:27:38 -0700355 if (DEBUG) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700356 Slog.v(TAG, "Finished writing, took " + (sElapsedRealtimeClock.millis()
Christopher Tate7060b042014-06-09 19:50:00 -0700357 - startElapsed) + "ms");
358 }
359 }
360
Matthew Williams49a85b62014-06-12 11:02:34 -0700361 private void writeJobsMapImpl(List<JobStatus> jobList) {
Makoto Onukie7b02982017-08-24 14:23:36 -0700362 int numJobs = 0;
363 int numSystemJobs = 0;
364 int numSyncJobs = 0;
Christopher Tate7060b042014-06-09 19:50:00 -0700365 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -0800366 final long startTime = SystemClock.uptimeMillis();
Christopher Tate7060b042014-06-09 19:50:00 -0700367 ByteArrayOutputStream baos = new ByteArrayOutputStream();
368 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz4f117542015-05-08 14:58:46 +0100369 out.setOutput(baos, StandardCharsets.UTF_8.name());
Christopher Tate7060b042014-06-09 19:50:00 -0700370 out.startDocument(null, true);
371 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
372
373 out.startTag(null, "job-info");
374 out.attribute(null, "version", Integer.toString(JOBS_FILE_VERSION));
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700375 for (int i=0; i<jobList.size(); i++) {
376 JobStatus jobStatus = jobList.get(i);
Christopher Tate7060b042014-06-09 19:50:00 -0700377 if (DEBUG) {
378 Slog.d(TAG, "Saving job " + jobStatus.getJobId());
379 }
380 out.startTag(null, "job");
Shreyas Basarge5db09082016-01-07 13:38:29 +0000381 addAttributesToJobTag(out, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -0700382 writeConstraintsToXml(out, jobStatus);
383 writeExecutionCriteriaToXml(out, jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -0700384 writeBundleToXml(jobStatus.getJob().getExtras(), out);
Christopher Tate7060b042014-06-09 19:50:00 -0700385 out.endTag(null, "job");
Makoto Onukie7b02982017-08-24 14:23:36 -0700386
387 numJobs++;
388 if (jobStatus.getUid() == Process.SYSTEM_UID) {
389 numSystemJobs++;
390 if (isSyncJob(jobStatus)) {
391 numSyncJobs++;
392 }
393 }
Christopher Tate7060b042014-06-09 19:50:00 -0700394 }
395 out.endTag(null, "job-info");
396 out.endDocument();
397
Christopher Tate616541d2017-07-26 14:27:38 -0700398 // Write out to disk in one fell swoop.
Dianne Hackborne17b4452018-01-10 13:15:40 -0800399 FileOutputStream fos = mJobsFile.startWrite(startTime);
Christopher Tate7060b042014-06-09 19:50:00 -0700400 fos.write(baos.toByteArray());
401 mJobsFile.finishWrite(fos);
402 mDirtyOperations = 0;
403 } catch (IOException e) {
404 if (DEBUG) {
405 Slog.v(TAG, "Error writing out job data.", e);
406 }
407 } catch (XmlPullParserException e) {
408 if (DEBUG) {
409 Slog.d(TAG, "Error persisting bundle.", e);
410 }
Makoto Onukie7b02982017-08-24 14:23:36 -0700411 } finally {
412 mPersistInfo.countAllJobsSaved = numJobs;
413 mPersistInfo.countSystemServerJobsSaved = numSystemJobs;
414 mPersistInfo.countSystemSyncManagerJobsSaved = numSyncJobs;
Christopher Tate7060b042014-06-09 19:50:00 -0700415 }
416 }
417
Shreyas Basarge5db09082016-01-07 13:38:29 +0000418 /** Write out a tag with data comprising the required fields and priority of this job and
419 * its client.
420 */
421 private void addAttributesToJobTag(XmlSerializer out, JobStatus jobStatus)
Christopher Tate7060b042014-06-09 19:50:00 -0700422 throws IOException {
423 out.attribute(null, "jobid", Integer.toString(jobStatus.getJobId()));
424 out.attribute(null, "package", jobStatus.getServiceComponent().getPackageName());
425 out.attribute(null, "class", jobStatus.getServiceComponent().getClassName());
Shreyas Basarge968ac752016-01-11 23:09:26 +0000426 if (jobStatus.getSourcePackageName() != null) {
427 out.attribute(null, "sourcePackageName", jobStatus.getSourcePackageName());
428 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800429 if (jobStatus.getSourceTag() != null) {
430 out.attribute(null, "sourceTag", jobStatus.getSourceTag());
431 }
Shreyas Basarge968ac752016-01-11 23:09:26 +0000432 out.attribute(null, "sourceUserId", String.valueOf(jobStatus.getSourceUserId()));
Christopher Tate7060b042014-06-09 19:50:00 -0700433 out.attribute(null, "uid", Integer.toString(jobStatus.getUid()));
Shreyas Basarge5db09082016-01-07 13:38:29 +0000434 out.attribute(null, "priority", String.valueOf(jobStatus.getPriority()));
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600435 out.attribute(null, "flags", String.valueOf(jobStatus.getFlags()));
Makoto Onuki15407842018-01-19 14:23:11 -0800436 if (jobStatus.getInternalFlags() != 0) {
437 out.attribute(null, "internalFlags", String.valueOf(jobStatus.getInternalFlags()));
438 }
Makoto Onukiab8a67f2017-06-20 12:20:34 -0700439
440 out.attribute(null, "lastSuccessfulRunTime",
441 String.valueOf(jobStatus.getLastSuccessfulRunTime()));
442 out.attribute(null, "lastFailedRunTime",
443 String.valueOf(jobStatus.getLastFailedRunTime()));
Christopher Tate7060b042014-06-09 19:50:00 -0700444 }
445
446 private void writeBundleToXml(PersistableBundle extras, XmlSerializer out)
447 throws IOException, XmlPullParserException {
448 out.startTag(null, XML_TAG_EXTRAS);
Shreyas Basarged09973b2015-12-16 18:10:05 +0000449 PersistableBundle extrasCopy = deepCopyBundle(extras, 10);
450 extrasCopy.saveToXml(out);
Christopher Tate7060b042014-06-09 19:50:00 -0700451 out.endTag(null, XML_TAG_EXTRAS);
452 }
Shreyas Basarged09973b2015-12-16 18:10:05 +0000453
454 private PersistableBundle deepCopyBundle(PersistableBundle bundle, int maxDepth) {
455 if (maxDepth <= 0) {
456 return null;
457 }
458 PersistableBundle copy = (PersistableBundle) bundle.clone();
459 Set<String> keySet = bundle.keySet();
460 for (String key: keySet) {
Shreyas Basarge5db09082016-01-07 13:38:29 +0000461 Object o = copy.get(key);
462 if (o instanceof PersistableBundle) {
463 PersistableBundle bCopy = deepCopyBundle((PersistableBundle) o, maxDepth-1);
Shreyas Basarged09973b2015-12-16 18:10:05 +0000464 copy.putPersistableBundle(key, bCopy);
465 }
466 }
467 return copy;
468 }
469
Christopher Tate7060b042014-06-09 19:50:00 -0700470 /**
471 * Write out a tag with data identifying this job's constraints. If the constraint isn't here
472 * it doesn't apply.
473 */
474 private void writeConstraintsToXml(XmlSerializer out, JobStatus jobStatus) throws IOException {
475 out.startTag(null, XML_TAG_PARAMS_CONSTRAINTS);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700476 if (jobStatus.hasConnectivityConstraint()) {
477 final NetworkRequest network = jobStatus.getJob().getRequiredNetwork();
478 out.attribute(null, "net-capabilities", Long.toString(
479 BitUtils.packBits(network.networkCapabilities.getCapabilities())));
Pavel Maltsev3ec36ef2018-03-15 16:17:48 -0700480 out.attribute(null, "net-unwanted-capabilities", Long.toString(
481 BitUtils.packBits(network.networkCapabilities.getUnwantedCapabilities())));
482
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700483 out.attribute(null, "net-transport-types", Long.toString(
484 BitUtils.packBits(network.networkCapabilities.getTransportTypes())));
Christopher Tate7060b042014-06-09 19:50:00 -0700485 }
486 if (jobStatus.hasIdleConstraint()) {
487 out.attribute(null, "idle", Boolean.toString(true));
488 }
489 if (jobStatus.hasChargingConstraint()) {
490 out.attribute(null, "charging", Boolean.toString(true));
491 }
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800492 if (jobStatus.hasBatteryNotLowConstraint()) {
493 out.attribute(null, "battery-not-low", Boolean.toString(true));
494 }
Christopher Tate7060b042014-06-09 19:50:00 -0700495 out.endTag(null, XML_TAG_PARAMS_CONSTRAINTS);
496 }
497
498 private void writeExecutionCriteriaToXml(XmlSerializer out, JobStatus jobStatus)
499 throws IOException {
500 final JobInfo job = jobStatus.getJob();
501 if (jobStatus.getJob().isPeriodic()) {
502 out.startTag(null, XML_TAG_PERIODIC);
503 out.attribute(null, "period", Long.toString(job.getIntervalMillis()));
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000504 out.attribute(null, "flex", Long.toString(job.getFlexMillis()));
Christopher Tate7060b042014-06-09 19:50:00 -0700505 } else {
506 out.startTag(null, XML_TAG_ONEOFF);
507 }
508
Christopher Tate616541d2017-07-26 14:27:38 -0700509 // If we still have the persisted times, we need to record those directly because
510 // we haven't yet been able to calculate the usual elapsed-timebase bounds
511 // correctly due to wall-clock uncertainty.
512 Pair <Long, Long> utcJobTimes = jobStatus.getPersistedUtcTimes();
513 if (DEBUG && utcJobTimes != null) {
514 Slog.i(TAG, "storing original UTC timestamps for " + jobStatus);
515 }
516
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700517 final long nowRTC = sSystemClock.millis();
518 final long nowElapsed = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -0700519 if (jobStatus.hasDeadlineConstraint()) {
520 // Wall clock deadline.
Christopher Tate616541d2017-07-26 14:27:38 -0700521 final long deadlineWallclock = (utcJobTimes == null)
522 ? nowRTC + (jobStatus.getLatestRunTimeElapsed() - nowElapsed)
523 : utcJobTimes.second;
Christopher Tate7060b042014-06-09 19:50:00 -0700524 out.attribute(null, "deadline", Long.toString(deadlineWallclock));
525 }
526 if (jobStatus.hasTimingDelayConstraint()) {
Christopher Tate616541d2017-07-26 14:27:38 -0700527 final long delayWallclock = (utcJobTimes == null)
528 ? nowRTC + (jobStatus.getEarliestRunTime() - nowElapsed)
529 : utcJobTimes.first;
Christopher Tate7060b042014-06-09 19:50:00 -0700530 out.attribute(null, "delay", Long.toString(delayWallclock));
531 }
532
533 // Only write out back-off policy if it differs from the default.
534 // This also helps the case where the job is idle -> these aren't allowed to specify
535 // back-off.
536 if (jobStatus.getJob().getInitialBackoffMillis() != JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS
537 || jobStatus.getJob().getBackoffPolicy() != JobInfo.DEFAULT_BACKOFF_POLICY) {
538 out.attribute(null, "backoff-policy", Integer.toString(job.getBackoffPolicy()));
539 out.attribute(null, "initial-backoff", Long.toString(job.getInitialBackoffMillis()));
540 }
541 if (job.isPeriodic()) {
542 out.endTag(null, XML_TAG_PERIODIC);
543 } else {
544 out.endTag(null, XML_TAG_ONEOFF);
545 }
546 }
Christopher Tate616541d2017-07-26 14:27:38 -0700547 };
548
549 /**
550 * Translate the supplied RTC times to the elapsed timebase, with clamping appropriate
551 * to interpreting them as a job's delay + deadline times for alarm-setting purposes.
552 * @param rtcTimes a Pair<Long, Long> in which {@code first} is the "delay" earliest
553 * allowable runtime for the job, and {@code second} is the "deadline" time at which
554 * the job becomes overdue.
555 */
556 private static Pair<Long, Long> convertRtcBoundsToElapsed(Pair<Long, Long> rtcTimes,
557 long nowElapsed) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700558 final long nowWallclock = sSystemClock.millis();
Christopher Tate616541d2017-07-26 14:27:38 -0700559 final long earliest = (rtcTimes.first > JobStatus.NO_EARLIEST_RUNTIME)
560 ? nowElapsed + Math.max(rtcTimes.first - nowWallclock, 0)
561 : JobStatus.NO_EARLIEST_RUNTIME;
562 final long latest = (rtcTimes.second < JobStatus.NO_LATEST_RUNTIME)
563 ? nowElapsed + Math.max(rtcTimes.second - nowWallclock, 0)
564 : JobStatus.NO_LATEST_RUNTIME;
565 return Pair.create(earliest, latest);
Christopher Tate7060b042014-06-09 19:50:00 -0700566 }
567
Makoto Onukie7b02982017-08-24 14:23:36 -0700568 private static boolean isSyncJob(JobStatus status) {
569 return com.android.server.content.SyncJobService.class.getName()
570 .equals(status.getServiceComponent().getClassName());
571 }
572
Christopher Tate7060b042014-06-09 19:50:00 -0700573 /**
Matthew Williams01ac45b2014-07-22 20:44:12 -0700574 * Runnable that reads list of persisted job from xml. This is run once at start up, so doesn't
575 * need to go through {@link JobStore#add(com.android.server.job.controllers.JobStatus)}.
Christopher Tate7060b042014-06-09 19:50:00 -0700576 */
Dianne Hackborn6466c1c2017-06-13 10:33:19 -0700577 private final class ReadJobMapFromDiskRunnable implements Runnable {
Christopher Tate2f36fd62016-02-18 18:36:08 -0800578 private final JobSet jobSet;
Christopher Tate616541d2017-07-26 14:27:38 -0700579 private final boolean rtcGood;
Matthew Williams01ac45b2014-07-22 20:44:12 -0700580
581 /**
582 * @param jobSet Reference to the (empty) set of JobStatus objects that back the JobStore,
583 * so that after disk read we can populate it directly.
584 */
Christopher Tate616541d2017-07-26 14:27:38 -0700585 ReadJobMapFromDiskRunnable(JobSet jobSet, boolean rtcIsGood) {
Matthew Williams01ac45b2014-07-22 20:44:12 -0700586 this.jobSet = jobSet;
Christopher Tate616541d2017-07-26 14:27:38 -0700587 this.rtcGood = rtcIsGood;
Christopher Tate7060b042014-06-09 19:50:00 -0700588 }
589
590 @Override
591 public void run() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -0700592 int numJobs = 0;
Makoto Onukie7b02982017-08-24 14:23:36 -0700593 int numSystemJobs = 0;
594 int numSyncJobs = 0;
Christopher Tate7060b042014-06-09 19:50:00 -0700595 try {
596 List<JobStatus> jobs;
597 FileInputStream fis = mJobsFile.openRead();
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800598 synchronized (mLock) {
Christopher Tate616541d2017-07-26 14:27:38 -0700599 jobs = readJobMapImpl(fis, rtcGood);
Matthew Williams01ac45b2014-07-22 20:44:12 -0700600 if (jobs != null) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700601 long now = sElapsedRealtimeClock.millis();
Dianne Hackborna47223f2017-03-30 13:49:13 -0700602 IActivityManager am = ActivityManager.getService();
Matthew Williams01ac45b2014-07-22 20:44:12 -0700603 for (int i=0; i<jobs.size(); i++) {
Dianne Hackborna47223f2017-03-30 13:49:13 -0700604 JobStatus js = jobs.get(i);
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700605 js.prepareLocked(am);
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700606 js.enqueueTime = now;
Dianne Hackborna47223f2017-03-30 13:49:13 -0700607 this.jobSet.add(js);
Makoto Onukie7b02982017-08-24 14:23:36 -0700608
Makoto Onukidd4b14f2017-08-17 14:03:48 -0700609 numJobs++;
Makoto Onukie7b02982017-08-24 14:23:36 -0700610 if (js.getUid() == Process.SYSTEM_UID) {
611 numSystemJobs++;
612 if (isSyncJob(js)) {
613 numSyncJobs++;
614 }
615 }
Matthew Williams01ac45b2014-07-22 20:44:12 -0700616 }
617 }
Christopher Tate7060b042014-06-09 19:50:00 -0700618 }
619 fis.close();
Christopher Tate7060b042014-06-09 19:50:00 -0700620 } catch (FileNotFoundException e) {
Christopher Tate616541d2017-07-26 14:27:38 -0700621 if (DEBUG) {
Christopher Tate7060b042014-06-09 19:50:00 -0700622 Slog.d(TAG, "Could not find jobs file, probably there was nothing to load.");
623 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -0700624 } catch (XmlPullParserException | IOException e) {
625 Slog.wtf(TAG, "Error jobstore xml.", e);
Makoto Onukie7b02982017-08-24 14:23:36 -0700626 } finally {
627 if (mPersistInfo.countAllJobsLoaded < 0) { // Only set them once.
628 mPersistInfo.countAllJobsLoaded = numJobs;
629 mPersistInfo.countSystemServerJobsLoaded = numSystemJobs;
630 mPersistInfo.countSystemSyncManagerJobsLoaded = numSyncJobs;
631 }
Christopher Tate7060b042014-06-09 19:50:00 -0700632 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -0700633 Slog.i(TAG, "Read " + numJobs + " jobs");
Christopher Tate7060b042014-06-09 19:50:00 -0700634 }
635
Christopher Tate616541d2017-07-26 14:27:38 -0700636 private List<JobStatus> readJobMapImpl(FileInputStream fis, boolean rtcIsGood)
Matthew Williams900c67f2014-07-09 12:46:53 -0700637 throws XmlPullParserException, IOException {
Christopher Tate7060b042014-06-09 19:50:00 -0700638 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz4f117542015-05-08 14:58:46 +0100639 parser.setInput(fis, StandardCharsets.UTF_8.name());
Christopher Tate7060b042014-06-09 19:50:00 -0700640
641 int eventType = parser.getEventType();
642 while (eventType != XmlPullParser.START_TAG &&
643 eventType != XmlPullParser.END_DOCUMENT) {
644 eventType = parser.next();
riddle_hsu98bfb342015-07-30 21:52:58 +0800645 Slog.d(TAG, "Start tag: " + parser.getName());
Christopher Tate7060b042014-06-09 19:50:00 -0700646 }
647 if (eventType == XmlPullParser.END_DOCUMENT) {
648 if (DEBUG) {
649 Slog.d(TAG, "No persisted jobs.");
650 }
651 return null;
652 }
653
654 String tagName = parser.getName();
655 if ("job-info".equals(tagName)) {
656 final List<JobStatus> jobs = new ArrayList<JobStatus>();
657 // Read in version info.
658 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +0100659 int version = Integer.parseInt(parser.getAttributeValue(null, "version"));
Christopher Tate7060b042014-06-09 19:50:00 -0700660 if (version != JOBS_FILE_VERSION) {
661 Slog.d(TAG, "Invalid version number, aborting jobs file read.");
662 return null;
663 }
664 } catch (NumberFormatException e) {
665 Slog.e(TAG, "Invalid version number, aborting jobs file read.");
666 return null;
667 }
668 eventType = parser.next();
669 do {
670 // Read each <job/>
671 if (eventType == XmlPullParser.START_TAG) {
672 tagName = parser.getName();
673 // Start reading job.
674 if ("job".equals(tagName)) {
Christopher Tate616541d2017-07-26 14:27:38 -0700675 JobStatus persistedJob = restoreJobFromXml(rtcIsGood, parser);
Christopher Tate7060b042014-06-09 19:50:00 -0700676 if (persistedJob != null) {
677 if (DEBUG) {
678 Slog.d(TAG, "Read out " + persistedJob);
679 }
680 jobs.add(persistedJob);
681 } else {
682 Slog.d(TAG, "Error reading job from file.");
683 }
684 }
685 }
686 eventType = parser.next();
687 } while (eventType != XmlPullParser.END_DOCUMENT);
688 return jobs;
689 }
690 return null;
691 }
692
693 /**
694 * @param parser Xml parser at the beginning of a "<job/>" tag. The next "parser.next()" call
695 * will take the parser into the body of the job tag.
696 * @return Newly instantiated job holding all the information we just read out of the xml tag.
697 */
Christopher Tate616541d2017-07-26 14:27:38 -0700698 private JobStatus restoreJobFromXml(boolean rtcIsGood, XmlPullParser parser)
699 throws XmlPullParserException, IOException {
Christopher Tate7060b042014-06-09 19:50:00 -0700700 JobInfo.Builder jobBuilder;
Shreyas Basarge8e64e2e2016-02-12 15:49:31 +0000701 int uid, sourceUserId;
Makoto Onukiab8a67f2017-06-20 12:20:34 -0700702 long lastSuccessfulRunTime;
703 long lastFailedRunTime;
Makoto Onuki15407842018-01-19 14:23:11 -0800704 int internalFlags = 0;
Christopher Tate7060b042014-06-09 19:50:00 -0700705
Shreyas Basarge5db09082016-01-07 13:38:29 +0000706 // Read out job identifier attributes and priority.
Christopher Tate7060b042014-06-09 19:50:00 -0700707 try {
708 jobBuilder = buildBuilderFromXml(parser);
Matthew Williamsd1c06752014-08-22 14:15:28 -0700709 jobBuilder.setPersisted(true);
Narayan Kamatha09b4d22016-04-15 18:32:45 +0100710 uid = Integer.parseInt(parser.getAttributeValue(null, "uid"));
Shreyas Basarge5db09082016-01-07 13:38:29 +0000711
Shreyas Basarge968ac752016-01-11 23:09:26 +0000712 String val = parser.getAttributeValue(null, "priority");
713 if (val != null) {
Narayan Kamatha09b4d22016-04-15 18:32:45 +0100714 jobBuilder.setPriority(Integer.parseInt(val));
Shreyas Basarge5db09082016-01-07 13:38:29 +0000715 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600716 val = parser.getAttributeValue(null, "flags");
717 if (val != null) {
718 jobBuilder.setFlags(Integer.parseInt(val));
719 }
Makoto Onuki15407842018-01-19 14:23:11 -0800720 val = parser.getAttributeValue(null, "internalFlags");
721 if (val != null) {
722 internalFlags = Integer.parseInt(val);
723 }
Shreyas Basarge968ac752016-01-11 23:09:26 +0000724 val = parser.getAttributeValue(null, "sourceUserId");
Narayan Kamatha09b4d22016-04-15 18:32:45 +0100725 sourceUserId = val == null ? -1 : Integer.parseInt(val);
Makoto Onukiab8a67f2017-06-20 12:20:34 -0700726
727 val = parser.getAttributeValue(null, "lastSuccessfulRunTime");
728 lastSuccessfulRunTime = val == null ? 0 : Long.parseLong(val);
729
730 val = parser.getAttributeValue(null, "lastFailedRunTime");
731 lastFailedRunTime = val == null ? 0 : Long.parseLong(val);
Christopher Tate7060b042014-06-09 19:50:00 -0700732 } catch (NumberFormatException e) {
733 Slog.e(TAG, "Error parsing job's required fields, skipping");
734 return null;
735 }
736
Christopher Tate0213ace02016-02-24 14:18:35 -0800737 String sourcePackageName = parser.getAttributeValue(null, "sourcePackageName");
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800738 final String sourceTag = parser.getAttributeValue(null, "sourceTag");
739
Christopher Tate7060b042014-06-09 19:50:00 -0700740 int eventType;
741 // Read out constraints tag.
742 do {
743 eventType = parser.next();
744 } while (eventType == XmlPullParser.TEXT); // Push through to next START_TAG.
745
746 if (!(eventType == XmlPullParser.START_TAG &&
747 XML_TAG_PARAMS_CONSTRAINTS.equals(parser.getName()))) {
748 // Expecting a <constraints> start tag.
749 return null;
750 }
751 try {
752 buildConstraintsFromXml(jobBuilder, parser);
753 } catch (NumberFormatException e) {
754 Slog.d(TAG, "Error reading constraints, skipping.");
755 return null;
756 }
757 parser.next(); // Consume </constraints>
758
759 // Read out execution parameters tag.
760 do {
761 eventType = parser.next();
762 } while (eventType == XmlPullParser.TEXT);
763 if (eventType != XmlPullParser.START_TAG) {
764 return null;
765 }
766
Christopher Tate616541d2017-07-26 14:27:38 -0700767 // Tuple of (earliest runtime, latest runtime) in UTC.
768 final Pair<Long, Long> rtcRuntimes;
Christopher Tate7060b042014-06-09 19:50:00 -0700769 try {
Christopher Tate616541d2017-07-26 14:27:38 -0700770 rtcRuntimes = buildRtcExecutionTimesFromXml(parser);
Christopher Tate7060b042014-06-09 19:50:00 -0700771 } catch (NumberFormatException e) {
772 if (DEBUG) {
773 Slog.d(TAG, "Error parsing execution time parameters, skipping.");
774 }
775 return null;
776 }
777
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700778 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate616541d2017-07-26 14:27:38 -0700779 Pair<Long, Long> elapsedRuntimes = convertRtcBoundsToElapsed(rtcRuntimes, elapsedNow);
780
Christopher Tate7060b042014-06-09 19:50:00 -0700781 if (XML_TAG_PERIODIC.equals(parser.getName())) {
782 try {
783 String val = parser.getAttributeValue(null, "period");
Tobias Thierer28532d02016-04-21 14:52:10 +0100784 final long periodMillis = Long.parseLong(val);
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000785 val = parser.getAttributeValue(null, "flex");
786 final long flexMillis = (val != null) ? Long.valueOf(val) : periodMillis;
Shreyas Basarge8e64e2e2016-02-12 15:49:31 +0000787 jobBuilder.setPeriodic(periodMillis, flexMillis);
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000788 // As a sanity check, cap the recreated run time to be no later than flex+period
Matthew Williamsfa8e5082015-10-15 15:59:12 -0700789 // from now. This is the latest the periodic could be pushed out. This could
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000790 // happen if the periodic ran early (at flex time before period), and then the
Matthew Williamsfa8e5082015-10-15 15:59:12 -0700791 // device rebooted.
Shreyas Basarge89ee6182015-12-17 15:16:36 +0000792 if (elapsedRuntimes.second > elapsedNow + periodMillis + flexMillis) {
793 final long clampedLateRuntimeElapsed = elapsedNow + flexMillis
794 + periodMillis;
795 final long clampedEarlyRuntimeElapsed = clampedLateRuntimeElapsed
796 - flexMillis;
Matthew Williamsfa8e5082015-10-15 15:59:12 -0700797 Slog.w(TAG,
798 String.format("Periodic job for uid='%d' persisted run-time is" +
799 " too big [%s, %s]. Clamping to [%s,%s]",
800 uid,
801 DateUtils.formatElapsedTime(elapsedRuntimes.first / 1000),
802 DateUtils.formatElapsedTime(elapsedRuntimes.second / 1000),
803 DateUtils.formatElapsedTime(
804 clampedEarlyRuntimeElapsed / 1000),
805 DateUtils.formatElapsedTime(
806 clampedLateRuntimeElapsed / 1000))
807 );
808 elapsedRuntimes =
809 Pair.create(clampedEarlyRuntimeElapsed, clampedLateRuntimeElapsed);
810 }
Christopher Tate7060b042014-06-09 19:50:00 -0700811 } catch (NumberFormatException e) {
812 Slog.d(TAG, "Error reading periodic execution criteria, skipping.");
813 return null;
814 }
815 } else if (XML_TAG_ONEOFF.equals(parser.getName())) {
816 try {
Matthew Williamsfa8e5082015-10-15 15:59:12 -0700817 if (elapsedRuntimes.first != JobStatus.NO_EARLIEST_RUNTIME) {
818 jobBuilder.setMinimumLatency(elapsedRuntimes.first - elapsedNow);
Christopher Tate7060b042014-06-09 19:50:00 -0700819 }
Matthew Williamsfa8e5082015-10-15 15:59:12 -0700820 if (elapsedRuntimes.second != JobStatus.NO_LATEST_RUNTIME) {
Christopher Tate7060b042014-06-09 19:50:00 -0700821 jobBuilder.setOverrideDeadline(
Matthew Williamsfa8e5082015-10-15 15:59:12 -0700822 elapsedRuntimes.second - elapsedNow);
Christopher Tate7060b042014-06-09 19:50:00 -0700823 }
824 } catch (NumberFormatException e) {
825 Slog.d(TAG, "Error reading job execution criteria, skipping.");
826 return null;
827 }
828 } else {
829 if (DEBUG) {
830 Slog.d(TAG, "Invalid parameter tag, skipping - " + parser.getName());
831 }
832 // Expecting a parameters start tag.
833 return null;
834 }
835 maybeBuildBackoffPolicyFromXml(jobBuilder, parser);
836
837 parser.nextTag(); // Consume parameters end tag.
838
839 // Read out extras Bundle.
840 do {
841 eventType = parser.next();
842 } while (eventType == XmlPullParser.TEXT);
Matthew Williamsfa8e5082015-10-15 15:59:12 -0700843 if (!(eventType == XmlPullParser.START_TAG
844 && XML_TAG_EXTRAS.equals(parser.getName()))) {
Christopher Tate7060b042014-06-09 19:50:00 -0700845 if (DEBUG) {
846 Slog.d(TAG, "Error reading extras, skipping.");
847 }
848 return null;
849 }
850
851 PersistableBundle extras = PersistableBundle.restoreFromXml(parser);
852 jobBuilder.setExtras(extras);
853 parser.nextTag(); // Consume </extras>
854
Christopher Tate0213ace02016-02-24 14:18:35 -0800855 // Migrate sync jobs forward from earlier, incomplete representation
856 if ("android".equals(sourcePackageName)
857 && extras != null
858 && extras.getBoolean("SyncManagerJob", false)) {
859 sourcePackageName = extras.getString("owningPackage", sourcePackageName);
860 if (DEBUG) {
861 Slog.i(TAG, "Fixing up sync job source package name from 'android' to '"
862 + sourcePackageName + "'");
863 }
864 }
865
866 // And now we're done
Christopher Tatea732f012017-10-26 17:26:53 -0700867 JobSchedulerInternal service = LocalServices.getService(JobSchedulerInternal.class);
868 final int appBucket = JobSchedulerService.standbyBucketForPackage(sourcePackageName,
869 sourceUserId, elapsedNow);
870 long currentHeartbeat = service != null ? service.currentHeartbeat() : 0;
Shreyas Basarge968ac752016-01-11 23:09:26 +0000871 JobStatus js = new JobStatus(
Christopher Tatea732f012017-10-26 17:26:53 -0700872 jobBuilder.build(), uid, sourcePackageName, sourceUserId,
873 appBucket, currentHeartbeat, sourceTag,
Makoto Onukiab8a67f2017-06-20 12:20:34 -0700874 elapsedRuntimes.first, elapsedRuntimes.second,
Christopher Tate616541d2017-07-26 14:27:38 -0700875 lastSuccessfulRunTime, lastFailedRunTime,
Makoto Onuki15407842018-01-19 14:23:11 -0800876 (rtcIsGood) ? null : rtcRuntimes, internalFlags);
Shreyas Basarge968ac752016-01-11 23:09:26 +0000877 return js;
Christopher Tate7060b042014-06-09 19:50:00 -0700878 }
879
880 private JobInfo.Builder buildBuilderFromXml(XmlPullParser parser) throws NumberFormatException {
881 // Pull out required fields from <job> attributes.
Narayan Kamatha09b4d22016-04-15 18:32:45 +0100882 int jobId = Integer.parseInt(parser.getAttributeValue(null, "jobid"));
Christopher Tate7060b042014-06-09 19:50:00 -0700883 String packageName = parser.getAttributeValue(null, "package");
884 String className = parser.getAttributeValue(null, "class");
885 ComponentName cname = new ComponentName(packageName, className);
886
887 return new JobInfo.Builder(jobId, cname);
888 }
889
890 private void buildConstraintsFromXml(JobInfo.Builder jobBuilder, XmlPullParser parser) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700891 String val;
892
893 final String netCapabilities = parser.getAttributeValue(null, "net-capabilities");
Pavel Maltsev3ec36ef2018-03-15 16:17:48 -0700894 final String netUnwantedCapabilities = parser.getAttributeValue(
895 null, "net-unwanted-capabilities");
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700896 final String netTransportTypes = parser.getAttributeValue(null, "net-transport-types");
897 if (netCapabilities != null && netTransportTypes != null) {
898 final NetworkRequest request = new NetworkRequest.Builder().build();
Pavel Maltsev3ec36ef2018-03-15 16:17:48 -0700899 final long unwantedCapabilities = netUnwantedCapabilities != null
900 ? Long.parseLong(netUnwantedCapabilities)
901 : BitUtils.packBits(request.networkCapabilities.getUnwantedCapabilities());
902
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700903 // We're okay throwing NFE here; caught by caller
904 request.networkCapabilities.setCapabilities(
Pavel Maltsev3ec36ef2018-03-15 16:17:48 -0700905 BitUtils.unpackBits(Long.parseLong(netCapabilities)),
906 BitUtils.unpackBits(unwantedCapabilities));
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700907 request.networkCapabilities.setTransportTypes(
908 BitUtils.unpackBits(Long.parseLong(netTransportTypes)));
909 jobBuilder.setRequiredNetwork(request);
910 } else {
911 // Read legacy values
912 val = parser.getAttributeValue(null, "connectivity");
913 if (val != null) {
914 jobBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
915 }
916 val = parser.getAttributeValue(null, "metered");
917 if (val != null) {
918 jobBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_METERED);
919 }
920 val = parser.getAttributeValue(null, "unmetered");
921 if (val != null) {
922 jobBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
923 }
924 val = parser.getAttributeValue(null, "not-roaming");
925 if (val != null) {
926 jobBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NOT_ROAMING);
927 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600928 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700929
Christopher Tate7060b042014-06-09 19:50:00 -0700930 val = parser.getAttributeValue(null, "idle");
931 if (val != null) {
932 jobBuilder.setRequiresDeviceIdle(true);
933 }
934 val = parser.getAttributeValue(null, "charging");
935 if (val != null) {
936 jobBuilder.setRequiresCharging(true);
937 }
938 }
939
940 /**
941 * Builds the back-off policy out of the params tag. These attributes may not exist, depending
942 * on whether the back-off was set when the job was first scheduled.
943 */
944 private void maybeBuildBackoffPolicyFromXml(JobInfo.Builder jobBuilder, XmlPullParser parser) {
945 String val = parser.getAttributeValue(null, "initial-backoff");
946 if (val != null) {
Tobias Thierer28532d02016-04-21 14:52:10 +0100947 long initialBackoff = Long.parseLong(val);
Christopher Tate7060b042014-06-09 19:50:00 -0700948 val = parser.getAttributeValue(null, "backoff-policy");
Narayan Kamatha09b4d22016-04-15 18:32:45 +0100949 int backoffPolicy = Integer.parseInt(val); // Will throw NFE which we catch higher up.
Christopher Tate7060b042014-06-09 19:50:00 -0700950 jobBuilder.setBackoffCriteria(initialBackoff, backoffPolicy);
951 }
952 }
953
954 /**
Christopher Tate616541d2017-07-26 14:27:38 -0700955 * Extract a job's earliest/latest run time data from XML. These are returned in
956 * unadjusted UTC wall clock time, because we do not yet know whether the system
957 * clock is reliable for purposes of calculating deltas from 'now'.
958 *
959 * @param parser
960 * @return A Pair of timestamps in UTC wall-clock time. The first is the earliest
961 * time at which the job is to become runnable, and the second is the deadline at
962 * which it becomes overdue to execute.
963 * @throws NumberFormatException
964 */
965 private Pair<Long, Long> buildRtcExecutionTimesFromXml(XmlPullParser parser)
966 throws NumberFormatException {
967 String val;
968 // Pull out execution time data.
969 val = parser.getAttributeValue(null, "delay");
970 final long earliestRunTimeRtc = (val != null)
971 ? Long.parseLong(val)
972 : JobStatus.NO_EARLIEST_RUNTIME;
973 val = parser.getAttributeValue(null, "deadline");
974 final long latestRunTimeRtc = (val != null)
975 ? Long.parseLong(val)
976 : JobStatus.NO_LATEST_RUNTIME;
977 return Pair.create(earliestRunTimeRtc, latestRunTimeRtc);
978 }
979
980 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700981 * Convenience function to read out and convert deadline and delay from xml into elapsed real
982 * time.
983 * @return A {@link android.util.Pair}, where the first value is the earliest elapsed runtime
984 * and the second is the latest elapsed runtime.
985 */
986 private Pair<Long, Long> buildExecutionTimesFromXml(XmlPullParser parser)
987 throws NumberFormatException {
988 // Pull out execution time data.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700989 final long nowWallclock = sSystemClock.millis();
990 final long nowElapsed = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -0700991
992 long earliestRunTimeElapsed = JobStatus.NO_EARLIEST_RUNTIME;
993 long latestRunTimeElapsed = JobStatus.NO_LATEST_RUNTIME;
994 String val = parser.getAttributeValue(null, "deadline");
995 if (val != null) {
Tobias Thierer28532d02016-04-21 14:52:10 +0100996 long latestRuntimeWallclock = Long.parseLong(val);
Christopher Tate7060b042014-06-09 19:50:00 -0700997 long maxDelayElapsed =
998 Math.max(latestRuntimeWallclock - nowWallclock, 0);
999 latestRunTimeElapsed = nowElapsed + maxDelayElapsed;
1000 }
1001 val = parser.getAttributeValue(null, "delay");
1002 if (val != null) {
Tobias Thierer28532d02016-04-21 14:52:10 +01001003 long earliestRuntimeWallclock = Long.parseLong(val);
Christopher Tate7060b042014-06-09 19:50:00 -07001004 long minDelayElapsed =
1005 Math.max(earliestRuntimeWallclock - nowWallclock, 0);
1006 earliestRunTimeElapsed = nowElapsed + minDelayElapsed;
1007
1008 }
1009 return Pair.create(earliestRunTimeElapsed, latestRunTimeElapsed);
1010 }
1011 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001012
Dianne Hackborn6466c1c2017-06-13 10:33:19 -07001013 static final class JobSet {
Suprabh Shukla7b21bb52018-01-26 17:19:28 -08001014 @VisibleForTesting // Key is the getUid() originator of the jobs in each sheaf
1015 final SparseArray<ArraySet<JobStatus>> mJobs;
1016
1017 @VisibleForTesting // Same data but with the key as getSourceUid() of the jobs in each sheaf
1018 final SparseArray<ArraySet<JobStatus>> mJobsPerSourceUid;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001019
1020 public JobSet() {
1021 mJobs = new SparseArray<ArraySet<JobStatus>>();
Suprabh Shukla106203b2017-11-02 21:23:44 -07001022 mJobsPerSourceUid = new SparseArray<>();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001023 }
1024
1025 public List<JobStatus> getJobsByUid(int uid) {
1026 ArrayList<JobStatus> matchingJobs = new ArrayList<JobStatus>();
1027 ArraySet<JobStatus> jobs = mJobs.get(uid);
1028 if (jobs != null) {
1029 matchingJobs.addAll(jobs);
1030 }
1031 return matchingJobs;
1032 }
1033
1034 // By user, not by uid, so we need to traverse by key and check
1035 public List<JobStatus> getJobsByUser(int userId) {
Suprabh Shukla106203b2017-11-02 21:23:44 -07001036 final ArrayList<JobStatus> result = new ArrayList<JobStatus>();
1037 for (int i = mJobsPerSourceUid.size() - 1; i >= 0; i--) {
1038 if (UserHandle.getUserId(mJobsPerSourceUid.keyAt(i)) == userId) {
1039 final ArraySet<JobStatus> jobs = mJobsPerSourceUid.valueAt(i);
Christopher Tate2f36fd62016-02-18 18:36:08 -08001040 if (jobs != null) {
1041 result.addAll(jobs);
1042 }
1043 }
1044 }
1045 return result;
1046 }
1047
1048 public boolean add(JobStatus job) {
1049 final int uid = job.getUid();
Suprabh Shukla106203b2017-11-02 21:23:44 -07001050 final int sourceUid = job.getSourceUid();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001051 ArraySet<JobStatus> jobs = mJobs.get(uid);
1052 if (jobs == null) {
1053 jobs = new ArraySet<JobStatus>();
1054 mJobs.put(uid, jobs);
1055 }
Suprabh Shukla106203b2017-11-02 21:23:44 -07001056 ArraySet<JobStatus> jobsForSourceUid = mJobsPerSourceUid.get(sourceUid);
1057 if (jobsForSourceUid == null) {
1058 jobsForSourceUid = new ArraySet<>();
1059 mJobsPerSourceUid.put(sourceUid, jobsForSourceUid);
1060 }
Suprabh Shukla7b21bb52018-01-26 17:19:28 -08001061 final boolean added = jobs.add(job);
1062 final boolean addedInSource = jobsForSourceUid.add(job);
1063 if (added != addedInSource) {
1064 Slog.wtf(TAG, "mJobs and mJobsPerSourceUid mismatch; caller= " + added
1065 + " source= " + addedInSource);
1066 }
1067 return added || addedInSource;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001068 }
1069
1070 public boolean remove(JobStatus job) {
1071 final int uid = job.getUid();
Suprabh Shukla106203b2017-11-02 21:23:44 -07001072 final ArraySet<JobStatus> jobs = mJobs.get(uid);
1073 final int sourceUid = job.getSourceUid();
1074 final ArraySet<JobStatus> jobsForSourceUid = mJobsPerSourceUid.get(sourceUid);
Christopher Tate19a2f242018-01-24 16:43:33 -08001075 final boolean didRemove = jobs != null && jobs.remove(job);
1076 final boolean sourceRemove = jobsForSourceUid != null && jobsForSourceUid.remove(job);
1077 if (didRemove != sourceRemove) {
1078 Slog.wtf(TAG, "Job presence mismatch; caller=" + didRemove
1079 + " source=" + sourceRemove);
1080 }
1081 if (didRemove || sourceRemove) {
1082 // no more jobs for this uid? let the now-empty set objects be GC'd.
1083 if (jobs != null && jobs.size() == 0) {
Suprabh Shukla106203b2017-11-02 21:23:44 -07001084 mJobs.remove(uid);
1085 }
Christopher Tate19a2f242018-01-24 16:43:33 -08001086 if (jobsForSourceUid != null && jobsForSourceUid.size() == 0) {
Suprabh Shukla106203b2017-11-02 21:23:44 -07001087 mJobsPerSourceUid.remove(sourceUid);
1088 }
1089 return true;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001090 }
Suprabh Shukla106203b2017-11-02 21:23:44 -07001091 return false;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001092 }
1093
Suprabh Shukla106203b2017-11-02 21:23:44 -07001094 /**
1095 * Removes the jobs of all users not specified by the whitelist of user ids.
Suprabh Shukla7b21bb52018-01-26 17:19:28 -08001096 * This will remove jobs scheduled *by* non-existent users as well as jobs scheduled *for*
1097 * non-existent users
Suprabh Shukla106203b2017-11-02 21:23:44 -07001098 */
Suprabh Shukla7b21bb52018-01-26 17:19:28 -08001099 public void removeJobsOfNonUsers(final int[] whitelist) {
1100 final Predicate<JobStatus> noSourceUser =
1101 job -> !ArrayUtils.contains(whitelist, job.getSourceUserId());
1102 final Predicate<JobStatus> noCallingUser =
1103 job -> !ArrayUtils.contains(whitelist, job.getUserId());
1104 removeAll(noSourceUser.or(noCallingUser));
1105 }
1106
1107 private void removeAll(Predicate<JobStatus> predicate) {
Suprabh Shukla106203b2017-11-02 21:23:44 -07001108 for (int jobSetIndex = mJobs.size() - 1; jobSetIndex >= 0; jobSetIndex--) {
Suprabh Shukla7b21bb52018-01-26 17:19:28 -08001109 final ArraySet<JobStatus> jobs = mJobs.valueAt(jobSetIndex);
1110 for (int jobIndex = jobs.size() - 1; jobIndex >= 0; jobIndex--) {
1111 if (predicate.test(jobs.valueAt(jobIndex))) {
1112 jobs.removeAt(jobIndex);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001113 }
1114 }
Suprabh Shukla7b21bb52018-01-26 17:19:28 -08001115 if (jobs.size() == 0) {
Suprabh Shukla106203b2017-11-02 21:23:44 -07001116 mJobs.removeAt(jobSetIndex);
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001117 }
1118 }
Suprabh Shukla7b21bb52018-01-26 17:19:28 -08001119 for (int jobSetIndex = mJobsPerSourceUid.size() - 1; jobSetIndex >= 0; jobSetIndex--) {
1120 final ArraySet<JobStatus> jobs = mJobsPerSourceUid.valueAt(jobSetIndex);
1121 for (int jobIndex = jobs.size() - 1; jobIndex >= 0; jobIndex--) {
1122 if (predicate.test(jobs.valueAt(jobIndex))) {
1123 jobs.removeAt(jobIndex);
1124 }
1125 }
1126 if (jobs.size() == 0) {
1127 mJobsPerSourceUid.removeAt(jobSetIndex);
1128 }
1129 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001130 }
1131
Christopher Tate2f36fd62016-02-18 18:36:08 -08001132 public boolean contains(JobStatus job) {
1133 final int uid = job.getUid();
1134 ArraySet<JobStatus> jobs = mJobs.get(uid);
1135 return jobs != null && jobs.contains(job);
1136 }
1137
1138 public JobStatus get(int uid, int jobId) {
1139 ArraySet<JobStatus> jobs = mJobs.get(uid);
1140 if (jobs != null) {
1141 for (int i = jobs.size() - 1; i >= 0; i--) {
1142 JobStatus job = jobs.valueAt(i);
1143 if (job.getJobId() == jobId) {
1144 return job;
1145 }
1146 }
1147 }
1148 return null;
1149 }
1150
1151 // Inefficient; use only for testing
1152 public List<JobStatus> getAllJobs() {
1153 ArrayList<JobStatus> allJobs = new ArrayList<JobStatus>(size());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07001154 for (int i = mJobs.size() - 1; i >= 0; i--) {
1155 ArraySet<JobStatus> jobs = mJobs.valueAt(i);
1156 if (jobs != null) {
1157 // Use a for loop over the ArraySet, so we don't need to make its
1158 // optional collection class iterator implementation or have to go
1159 // through a temporary array from toArray().
1160 for (int j = jobs.size() - 1; j >= 0; j--) {
1161 allJobs.add(jobs.valueAt(j));
1162 }
1163 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001164 }
1165 return allJobs;
1166 }
1167
1168 public void clear() {
1169 mJobs.clear();
Suprabh Shukla106203b2017-11-02 21:23:44 -07001170 mJobsPerSourceUid.clear();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001171 }
1172
1173 public int size() {
1174 int total = 0;
1175 for (int i = mJobs.size() - 1; i >= 0; i--) {
1176 total += mJobs.valueAt(i).size();
1177 }
1178 return total;
1179 }
1180
1181 // We only want to count the jobs that this uid has scheduled on its own
1182 // behalf, not those that the app has scheduled on someone else's behalf.
1183 public int countJobsForUid(int uid) {
1184 int total = 0;
1185 ArraySet<JobStatus> jobs = mJobs.get(uid);
1186 if (jobs != null) {
1187 for (int i = jobs.size() - 1; i >= 0; i--) {
1188 JobStatus job = jobs.valueAt(i);
1189 if (job.getUid() == job.getSourceUid()) {
1190 total++;
1191 }
1192 }
1193 }
1194 return total;
1195 }
1196
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001197 public void forEachJob(@Nullable Predicate<JobStatus> filterPredicate,
1198 Consumer<JobStatus> functor) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001199 for (int uidIndex = mJobs.size() - 1; uidIndex >= 0; uidIndex--) {
1200 ArraySet<JobStatus> jobs = mJobs.valueAt(uidIndex);
Christopher Tate41f3fe82017-12-08 17:52:09 -08001201 if (jobs != null) {
1202 for (int i = jobs.size() - 1; i >= 0; i--) {
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001203 final JobStatus jobStatus = jobs.valueAt(i);
1204 if ((filterPredicate == null) || filterPredicate.test(jobStatus)) {
1205 functor.accept(jobStatus);
1206 }
Christopher Tate41f3fe82017-12-08 17:52:09 -08001207 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001208 }
1209 }
1210 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001211
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001212 public void forEachJob(int callingUid, Consumer<JobStatus> functor) {
Suprabh Shukla106203b2017-11-02 21:23:44 -07001213 ArraySet<JobStatus> jobs = mJobs.get(callingUid);
1214 if (jobs != null) {
1215 for (int i = jobs.size() - 1; i >= 0; i--) {
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001216 functor.accept(jobs.valueAt(i));
Suprabh Shukla106203b2017-11-02 21:23:44 -07001217 }
1218 }
1219 }
1220
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001221 public void forEachJobForSourceUid(int sourceUid, Consumer<JobStatus> functor) {
Suprabh Shukla106203b2017-11-02 21:23:44 -07001222 final ArraySet<JobStatus> jobs = mJobsPerSourceUid.get(sourceUid);
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001223 if (jobs != null) {
1224 for (int i = jobs.size() - 1; i >= 0; i--) {
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001225 functor.accept(jobs.valueAt(i));
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00001226 }
1227 }
1228 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001229 }
Matthew Williams01ac45b2014-07-22 20:44:12 -07001230}