blob: ceb7db6b85235950523e8d757466c44c66f13443 [file] [log] [blame]
Craig Mautner21d24a22014-04-23 11:45:37 -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.am;
18
Suprabh Shukla4bccb462016-02-10 18:45:12 -080019import android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.app.ActivityManager;
Craig Mautner21d24a22014-04-23 11:45:37 -070022import android.graphics.Bitmap;
23import android.graphics.BitmapFactory;
24import android.os.Debug;
Suprabh Shukla23593142015-11-03 17:31:15 -080025import android.os.Environment;
26import android.os.FileUtils;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080027import android.os.Process;
Craig Mautner21d24a22014-04-23 11:45:37 -070028import android.os.SystemClock;
29import android.util.ArraySet;
30import android.util.AtomicFile;
31import android.util.Slog;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080032import android.util.SparseArray;
33import android.util.SparseBooleanArray;
Craig Mautner21d24a22014-04-23 11:45:37 -070034import android.util.Xml;
Wale Ogunwale18795a22014-12-03 11:38:33 -080035
Suprabh Shukla4bccb462016-02-10 18:45:12 -080036import com.android.internal.annotations.VisibleForTesting;
Craig Mautner21d24a22014-04-23 11:45:37 -070037import com.android.internal.util.FastXmlSerializer;
38import com.android.internal.util.XmlUtils;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080039import libcore.io.IoUtils;
40
Craig Mautner21d24a22014-04-23 11:45:37 -070041import org.xmlpull.v1.XmlPullParser;
42import org.xmlpull.v1.XmlPullParserException;
43import org.xmlpull.v1.XmlSerializer;
44
45import java.io.BufferedReader;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080046import java.io.BufferedWriter;
Craig Mautner21d24a22014-04-23 11:45:37 -070047import java.io.File;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080048import java.io.FileNotFoundException;
Craig Mautner21d24a22014-04-23 11:45:37 -070049import java.io.FileOutputStream;
50import java.io.FileReader;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080051import java.io.FileWriter;
Craig Mautner21d24a22014-04-23 11:45:37 -070052import java.io.IOException;
53import java.io.StringWriter;
54import java.util.ArrayList;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080055import java.util.Collections;
Craig Mautner21d24a22014-04-23 11:45:37 -070056import java.util.Comparator;
Suprabh Shukla23593142015-11-03 17:31:15 -080057import java.util.List;
Wale Ogunwale18795a22014-12-03 11:38:33 -080058
Craig Mautner21d24a22014-04-23 11:45:37 -070059public class TaskPersister {
60 static final String TAG = "TaskPersister";
Stefan Kuhnee88d1e52015-05-18 10:33:45 -070061 static final boolean DEBUG = false;
Craig Mautner21d24a22014-04-23 11:45:37 -070062
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070063 /** When not flushing don't write out files faster than this */
64 private static final long INTER_WRITE_DELAY_MS = 500;
65
Suprabh Shukla23593142015-11-03 17:31:15 -080066 /**
67 * When not flushing delay this long before writing the first file out. This gives the next task
68 * being launched a chance to load its resources without this occupying IO bandwidth.
69 */
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070070 private static final long PRE_TASK_DELAY_MS = 3000;
Craig Mautner21d24a22014-04-23 11:45:37 -070071
Craig Mautner63f10902014-09-16 23:57:21 -070072 /** The maximum number of entries to keep in the queue before draining it automatically. */
73 private static final int MAX_WRITE_QUEUE_LENGTH = 6;
74
75 /** Special value for mWriteTime to mean don't wait, just write */
76 private static final long FLUSH_QUEUE = -1;
77
Craig Mautner21d24a22014-04-23 11:45:37 -070078 private static final String RECENTS_FILENAME = "_task";
79 private static final String TASKS_DIRNAME = "recent_tasks";
80 private static final String TASK_EXTENSION = ".xml";
81 private static final String IMAGES_DIRNAME = "recent_images";
Suprabh Shukla4bccb462016-02-10 18:45:12 -080082 private static final String PERSISTED_TASK_IDS_FILENAME = "persisted_taskIds.txt";
Craig Mautnerc0ffce52014-07-01 12:38:52 -070083 static final String IMAGE_EXTENSION = ".png";
Craig Mautner21d24a22014-04-23 11:45:37 -070084
85 private static final String TAG_TASK = "task";
86
Craig Mautner21d24a22014-04-23 11:45:37 -070087 private final ActivityManagerService mService;
88 private final ActivityStackSupervisor mStackSupervisor;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080089 private final RecentTasks mRecentTasks;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080090 private final SparseArray<SparseBooleanArray> mTaskIdsInFile = new SparseArray<>();
Suprabh Shuklaf50b4582016-02-23 17:44:22 -080091 private final File mTaskIdsDir;
Craig Mautner21d24a22014-04-23 11:45:37 -070092
Suprabh Shukla23593142015-11-03 17:31:15 -080093 /**
94 * Value determines write delay mode as follows: < 0 We are Flushing. No delays between writes
95 * until the image queue is drained and all tasks needing persisting are written to disk. There
96 * is no delay between writes. == 0 We are Idle. Next writes will be delayed by
97 * #PRE_TASK_DELAY_MS. > 0 We are Actively writing. Next write will be at this time. Subsequent
98 * writes will be delayed by #INTER_WRITE_DELAY_MS.
99 */
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700100 private long mNextWriteTime = 0;
Craig Mautner21d24a22014-04-23 11:45:37 -0700101
102 private final LazyTaskWriterThread mLazyTaskWriterThread;
103
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700104 private static class WriteQueueItem {}
Suprabh Shukla23593142015-11-03 17:31:15 -0800105
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700106 private static class TaskWriteQueueItem extends WriteQueueItem {
107 final TaskRecord mTask;
Winsonc809cbb2015-11-02 12:06:15 -0800108
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700109 TaskWriteQueueItem(TaskRecord task) {
110 mTask = task;
111 }
112 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800113
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700114 private static class ImageWriteQueueItem extends WriteQueueItem {
Suprabh Shukla23593142015-11-03 17:31:15 -0800115 final String mFilePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700116 Bitmap mImage;
Winsonc809cbb2015-11-02 12:06:15 -0800117
Suprabh Shukla23593142015-11-03 17:31:15 -0800118 ImageWriteQueueItem(String filePath, Bitmap image) {
119 mFilePath = filePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700120 mImage = image;
121 }
122 }
123
124 ArrayList<WriteQueueItem> mWriteQueue = new ArrayList<WriteQueueItem>();
125
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800126 TaskPersister(File systemDir, ActivityStackSupervisor stackSupervisor,
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800127 ActivityManagerService service, RecentTasks recentTasks) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800128
129 final File legacyImagesDir = new File(systemDir, IMAGES_DIRNAME);
130 if (legacyImagesDir.exists()) {
131 if (!FileUtils.deleteContents(legacyImagesDir) || !legacyImagesDir.delete()) {
132 Slog.i(TAG, "Failure deleting legacy images directory: " + legacyImagesDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700133 }
134 }
135
Suprabh Shukla23593142015-11-03 17:31:15 -0800136 final File legacyTasksDir = new File(systemDir, TASKS_DIRNAME);
137 if (legacyTasksDir.exists()) {
138 if (!FileUtils.deleteContents(legacyTasksDir) || !legacyTasksDir.delete()) {
139 Slog.i(TAG, "Failure deleting legacy tasks directory: " + legacyTasksDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700140 }
141 }
142
Suprabh Shuklaf50b4582016-02-23 17:44:22 -0800143 mTaskIdsDir = new File(Environment.getDataDirectory(), "system_de");
Craig Mautner21d24a22014-04-23 11:45:37 -0700144 mStackSupervisor = stackSupervisor;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800145 mService = service;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800146 mRecentTasks = recentTasks;
Craig Mautner21d24a22014-04-23 11:45:37 -0700147 mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThread");
148 }
149
Suprabh Shuklaf50b4582016-02-23 17:44:22 -0800150 @VisibleForTesting
151 TaskPersister(File workingDir) {
152 mTaskIdsDir = workingDir;
153 mStackSupervisor = null;
154 mService = null;
155 mRecentTasks = null;
156 mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThreadTest");
157 }
158
Craig Mautner21d24a22014-04-23 11:45:37 -0700159 void startPersisting() {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800160 if (!mLazyTaskWriterThread.isAlive()) {
161 mLazyTaskWriterThread.start();
162 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700163 }
164
Craig Mautner63f10902014-09-16 23:57:21 -0700165 private void removeThumbnails(TaskRecord task) {
166 final String taskString = Integer.toString(task.taskId);
167 for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
168 final WriteQueueItem item = mWriteQueue.get(queueNdx);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800169 if (item instanceof ImageWriteQueueItem) {
170 final File thumbnailFile = new File(((ImageWriteQueueItem) item).mFilePath);
171 if (thumbnailFile.getName().startsWith(taskString)) {
172 if (DEBUG) {
173 Slog.d(TAG, "Removing " + ((ImageWriteQueueItem) item).mFilePath +
174 " from write queue");
175 }
176 mWriteQueue.remove(queueNdx);
177 }
Craig Mautner63f10902014-09-16 23:57:21 -0700178 }
179 }
180 }
181
182 private void yieldIfQueueTooDeep() {
183 boolean stall = false;
184 synchronized (this) {
185 if (mNextWriteTime == FLUSH_QUEUE) {
186 stall = true;
187 }
188 }
189 if (stall) {
190 Thread.yield();
191 }
192 }
193
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800194 @NonNull
195 SparseBooleanArray loadPersistedTaskIdsForUser(int userId) {
196 if (mTaskIdsInFile.get(userId) != null) {
197 return mTaskIdsInFile.get(userId).clone();
198 }
199 final SparseBooleanArray persistedTaskIds = new SparseBooleanArray();
200 BufferedReader reader = null;
201 String line;
202 try {
203 reader = new BufferedReader(new FileReader(getUserPersistedTaskIdsFile(userId)));
204 while ((line = reader.readLine()) != null) {
205 for (String taskIdString : line.split("\\s+")) {
206 int id = Integer.parseInt(taskIdString);
207 persistedTaskIds.put(id, true);
208 }
209 }
210 } catch (FileNotFoundException e) {
211 // File doesn't exist. Ignore.
212 } catch (Exception e) {
213 Slog.e(TAG, "Error while reading taskIds file for user " + userId, e);
214 } finally {
215 IoUtils.closeQuietly(reader);
216 }
217 mTaskIdsInFile.put(userId, persistedTaskIds);
218 return persistedTaskIds.clone();
219 }
220
Suprabh Shuklaf50b4582016-02-23 17:44:22 -0800221 @VisibleForTesting
222 void maybeWritePersistedTaskIdsForUser(@NonNull SparseBooleanArray taskIds, int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800223 if (userId < 0) {
224 return;
225 }
226 SparseBooleanArray persistedIdsInFile = mTaskIdsInFile.get(userId);
227 if (persistedIdsInFile != null && persistedIdsInFile.equals(taskIds)) {
228 return;
229 }
230 final File persistedTaskIdsFile = getUserPersistedTaskIdsFile(userId);
231 BufferedWriter writer = null;
232 try {
233 writer = new BufferedWriter(new FileWriter(persistedTaskIdsFile));
234 for (int i = 0; i < taskIds.size(); i++) {
235 if (taskIds.valueAt(i)) {
236 writer.write(String.valueOf(taskIds.keyAt(i)));
237 writer.newLine();
238 }
239 }
240 } catch (Exception e) {
241 Slog.e(TAG, "Error while writing taskIds file for user " + userId, e);
242 } finally {
243 IoUtils.closeQuietly(writer);
244 }
245 mTaskIdsInFile.put(userId, taskIds.clone());
246 }
247
248 void unloadUserDataFromMemory(int userId) {
249 mTaskIdsInFile.delete(userId);
250 }
251
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700252 void wakeup(TaskRecord task, boolean flush) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700253 synchronized (this) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700254 if (task != null) {
255 int queueNdx;
256 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
257 final WriteQueueItem item = mWriteQueue.get(queueNdx);
258 if (item instanceof TaskWriteQueueItem &&
259 ((TaskWriteQueueItem) item).mTask == task) {
Craig Mautner63f10902014-09-16 23:57:21 -0700260 if (!task.inRecents) {
261 // This task is being removed.
262 removeThumbnails(task);
263 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700264 break;
265 }
266 }
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700267 if (queueNdx < 0 && task.isPersistable) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700268 mWriteQueue.add(new TaskWriteQueueItem(task));
269 }
270 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800271 // Dummy. Ensures removeObsoleteFiles is called when LazyTaskThreadWriter is
272 // notified.
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700273 mWriteQueue.add(new WriteQueueItem());
274 }
Craig Mautner63f10902014-09-16 23:57:21 -0700275 if (flush || mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
276 mNextWriteTime = FLUSH_QUEUE;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700277 } else if (mNextWriteTime == 0) {
278 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
279 }
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700280 if (DEBUG) Slog.d(TAG, "wakeup: task=" + task + " flush=" + flush + " mNextWriteTime="
281 + mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size()
282 + " Callers=" + Debug.getCallers(4));
Craig Mautner21d24a22014-04-23 11:45:37 -0700283 notifyAll();
284 }
Craig Mautner63f10902014-09-16 23:57:21 -0700285
286 yieldIfQueueTooDeep();
Craig Mautner21d24a22014-04-23 11:45:37 -0700287 }
288
Dianne Hackbornce0fd762014-09-19 12:58:15 -0700289 void flush() {
290 synchronized (this) {
291 mNextWriteTime = FLUSH_QUEUE;
292 notifyAll();
293 do {
294 try {
295 wait();
296 } catch (InterruptedException e) {
297 }
298 } while (mNextWriteTime == FLUSH_QUEUE);
299 }
300 }
301
Suprabh Shukla23593142015-11-03 17:31:15 -0800302 void saveImage(Bitmap image, String filePath) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700303 synchronized (this) {
304 int queueNdx;
305 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
306 final WriteQueueItem item = mWriteQueue.get(queueNdx);
307 if (item instanceof ImageWriteQueueItem) {
308 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800309 if (imageWriteQueueItem.mFilePath.equals(filePath)) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700310 // replace the Bitmap with the new one.
311 imageWriteQueueItem.mImage = image;
312 break;
313 }
314 }
315 }
316 if (queueNdx < 0) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800317 mWriteQueue.add(new ImageWriteQueueItem(filePath, image));
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700318 }
Craig Mautner63f10902014-09-16 23:57:21 -0700319 if (mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
320 mNextWriteTime = FLUSH_QUEUE;
321 } else if (mNextWriteTime == 0) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700322 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
323 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800324 if (DEBUG) Slog.d(TAG, "saveImage: filePath=" + filePath + " now=" +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700325 SystemClock.uptimeMillis() + " mNextWriteTime=" +
326 mNextWriteTime + " Callers=" + Debug.getCallers(4));
327 notifyAll();
328 }
Craig Mautner63f10902014-09-16 23:57:21 -0700329
330 yieldIfQueueTooDeep();
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700331 }
332
Suprabh Shukla23593142015-11-03 17:31:15 -0800333 Bitmap getTaskDescriptionIcon(String filePath) {
Craig Mautner648f69b2014-09-18 14:16:26 -0700334 // See if it is in the write queue
Suprabh Shukla23593142015-11-03 17:31:15 -0800335 final Bitmap icon = getImageFromWriteQueue(filePath);
Craig Mautner648f69b2014-09-18 14:16:26 -0700336 if (icon != null) {
337 return icon;
338 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800339 return restoreImage(filePath);
Craig Mautner648f69b2014-09-18 14:16:26 -0700340 }
341
Suprabh Shukla23593142015-11-03 17:31:15 -0800342 Bitmap getImageFromWriteQueue(String filePath) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700343 synchronized (this) {
344 for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
345 final WriteQueueItem item = mWriteQueue.get(queueNdx);
346 if (item instanceof ImageWriteQueueItem) {
347 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800348 if (imageWriteQueueItem.mFilePath.equals(filePath)) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700349 return imageWriteQueueItem.mImage;
350 }
351 }
352 }
353 return null;
354 }
355 }
356
Craig Mautner21d24a22014-04-23 11:45:37 -0700357 private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700358 if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task);
Craig Mautner21d24a22014-04-23 11:45:37 -0700359 final XmlSerializer xmlSerializer = new FastXmlSerializer();
360 StringWriter stringWriter = new StringWriter();
361 xmlSerializer.setOutput(stringWriter);
362
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700363 if (DEBUG) xmlSerializer.setFeature(
Suprabh Shukla23593142015-11-03 17:31:15 -0800364 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
Craig Mautner21d24a22014-04-23 11:45:37 -0700365
366 // save task
367 xmlSerializer.startDocument(null, true);
368
369 xmlSerializer.startTag(null, TAG_TASK);
370 task.saveToXml(xmlSerializer);
371 xmlSerializer.endTag(null, TAG_TASK);
372
373 xmlSerializer.endDocument();
374 xmlSerializer.flush();
375
376 return stringWriter;
377 }
378
Craig Mautner77b04262014-06-27 15:22:12 -0700379 private String fileToString(File file) {
380 final String newline = System.lineSeparator();
381 try {
382 BufferedReader reader = new BufferedReader(new FileReader(file));
383 StringBuffer sb = new StringBuffer((int) file.length() * 2);
384 String line;
385 while ((line = reader.readLine()) != null) {
386 sb.append(line + newline);
387 }
388 reader.close();
389 return sb.toString();
390 } catch (IOException ioe) {
391 Slog.e(TAG, "Couldn't read file " + file.getName());
392 return null;
393 }
394 }
395
Craig Mautnera228ae92014-07-09 05:44:55 -0700396 private TaskRecord taskIdToTask(int taskId, ArrayList<TaskRecord> tasks) {
397 if (taskId < 0) {
398 return null;
399 }
400 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
401 final TaskRecord task = tasks.get(taskNdx);
402 if (task.taskId == taskId) {
403 return task;
404 }
405 }
406 Slog.e(TAG, "Restore affiliation error looking for taskId=" + taskId);
407 return null;
408 }
409
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800410 List<TaskRecord> restoreTasksForUserLocked(final int userId) {
411 final ArrayList<TaskRecord> tasks = new ArrayList<TaskRecord>();
Craig Mautner21d24a22014-04-23 11:45:37 -0700412 ArraySet<Integer> recoveredTaskIds = new ArraySet<Integer>();
413
Suprabh Shukla23593142015-11-03 17:31:15 -0800414 File userTasksDir = getUserTasksDir(userId);
415
416 File[] recentFiles = userTasksDir.listFiles();
Craig Mautner21d24a22014-04-23 11:45:37 -0700417 if (recentFiles == null) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800418 Slog.e(TAG, "restoreTasksForUserLocked: Unable to list files from " + userTasksDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700419 return tasks;
420 }
421
422 for (int taskNdx = 0; taskNdx < recentFiles.length; ++taskNdx) {
423 File taskFile = recentFiles[taskNdx];
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800424 if (DEBUG) {
425 Slog.d(TAG, "restoreTasksForUserLocked: userId=" + userId
426 + ", taskFile=" + taskFile.getName());
427 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700428 BufferedReader reader = null;
Craig Mautnere0129b32014-05-25 16:41:09 -0700429 boolean deleteFile = false;
Craig Mautner21d24a22014-04-23 11:45:37 -0700430 try {
431 reader = new BufferedReader(new FileReader(taskFile));
432 final XmlPullParser in = Xml.newPullParser();
433 in.setInput(reader);
434
435 int event;
436 while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
437 event != XmlPullParser.END_TAG) {
438 final String name = in.getName();
439 if (event == XmlPullParser.START_TAG) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800440 if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: START_TAG name=" + name);
Craig Mautner21d24a22014-04-23 11:45:37 -0700441 if (TAG_TASK.equals(name)) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800442 final TaskRecord task = TaskRecord.restoreFromXml(in, mStackSupervisor);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800443 if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: restored task="
Suprabh Shukla23593142015-11-03 17:31:15 -0800444 + task);
Craig Mautner21d24a22014-04-23 11:45:37 -0700445 if (task != null) {
Dianne Hackborn852975d2014-08-22 17:42:43 -0700446 // XXX Don't add to write queue... there is no reason to write
447 // out the stuff we just read, if we don't write it we will
448 // read the same thing again.
Suprabh Shukla23593142015-11-03 17:31:15 -0800449 // mWriteQueue.add(new TaskWriteQueueItem(task));
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800450
Craig Mautner21d24a22014-04-23 11:45:37 -0700451 final int taskId = task.taskId;
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800452 if (mStackSupervisor.anyTaskForIdLocked(taskId,
453 /* restoreFromRecents= */ false, 0) != null) {
454 // Should not happen.
455 Slog.wtf(TAG, "Existing task with taskId " + taskId + "found");
456 } else if (userId != task.userId) {
457 // Should not happen.
458 Slog.wtf(TAG, "Task with userId " + task.userId + " found in "
459 + userTasksDir.getAbsolutePath());
460 } else {
461 // Looks fine.
462 mStackSupervisor.setNextTaskIdForUserLocked(taskId, userId);
Amith Yamasani515d4062015-09-28 11:30:06 -0700463 task.isPersistable = true;
464 tasks.add(task);
465 recoveredTaskIds.add(taskId);
466 }
Craig Mautner77b04262014-06-27 15:22:12 -0700467 } else {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800468 Slog.e(TAG, "restoreTasksForUserLocked: Unable to restore taskFile="
Suprabh Shukla23593142015-11-03 17:31:15 -0800469 + taskFile + ": " + fileToString(taskFile));
Craig Mautner21d24a22014-04-23 11:45:37 -0700470 }
471 } else {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800472 Slog.wtf(TAG, "restoreTasksForUserLocked: Unknown xml event=" + event
Suprabh Shukla23593142015-11-03 17:31:15 -0800473 + " name=" + name);
Craig Mautner21d24a22014-04-23 11:45:37 -0700474 }
475 }
476 XmlUtils.skipCurrentTag(in);
477 }
Craig Mautnere0129b32014-05-25 16:41:09 -0700478 } catch (Exception e) {
Craig Mautnera228ae92014-07-09 05:44:55 -0700479 Slog.wtf(TAG, "Unable to parse " + taskFile + ". Error ", e);
Craig Mautner77b04262014-06-27 15:22:12 -0700480 Slog.e(TAG, "Failing file: " + fileToString(taskFile));
Craig Mautnere0129b32014-05-25 16:41:09 -0700481 deleteFile = true;
Craig Mautner21d24a22014-04-23 11:45:37 -0700482 } finally {
Wale Ogunwale18795a22014-12-03 11:38:33 -0800483 IoUtils.closeQuietly(reader);
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700484 if (deleteFile) {
485 if (DEBUG) Slog.d(TAG, "Deleting file=" + taskFile.getName());
Craig Mautnere0129b32014-05-25 16:41:09 -0700486 taskFile.delete();
487 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700488 }
489 }
490
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700491 if (!DEBUG) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800492 removeObsoleteFiles(recoveredTaskIds, userTasksDir.listFiles());
493 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700494
Suprabh Shukla23593142015-11-03 17:31:15 -0800495 // Fix up task affiliation from taskIds
Craig Mautnera228ae92014-07-09 05:44:55 -0700496 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
497 final TaskRecord task = tasks.get(taskNdx);
498 task.setPrevAffiliate(taskIdToTask(task.mPrevAffiliateTaskId, tasks));
499 task.setNextAffiliate(taskIdToTask(task.mNextAffiliateTaskId, tasks));
500 }
501
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800502 Collections.sort(tasks, new Comparator<TaskRecord>() {
Craig Mautner21d24a22014-04-23 11:45:37 -0700503 @Override
504 public int compare(TaskRecord lhs, TaskRecord rhs) {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700505 final long diff = rhs.mLastTimeMoved - lhs.mLastTimeMoved;
Craig Mautner21d24a22014-04-23 11:45:37 -0700506 if (diff < 0) {
507 return -1;
508 } else if (diff > 0) {
509 return +1;
510 } else {
511 return 0;
512 }
513 }
514 });
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800515 return tasks;
Craig Mautner21d24a22014-04-23 11:45:37 -0700516 }
517
Craig Mautnere0129b32014-05-25 16:41:09 -0700518 private static void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds, File[] files) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800519 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: persistentTaskIds=" + persistentTaskIds +
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700520 " files=" + files);
Craig Mautnera5badf02014-09-11 12:47:03 -0700521 if (files == null) {
522 Slog.e(TAG, "File error accessing recents directory (too many files open?).");
523 return;
524 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700525 for (int fileNdx = 0; fileNdx < files.length; ++fileNdx) {
526 File file = files[fileNdx];
527 String filename = file.getName();
Craig Mautnerffcfcaa2014-06-05 09:54:38 -0700528 final int taskIdEnd = filename.indexOf('_');
Craig Mautner21d24a22014-04-23 11:45:37 -0700529 if (taskIdEnd > 0) {
530 final int taskId;
531 try {
532 taskId = Integer.valueOf(filename.substring(0, taskIdEnd));
Suprabh Shukla23593142015-11-03 17:31:15 -0800533 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: Found taskId=" + taskId);
Craig Mautner21d24a22014-04-23 11:45:37 -0700534 } catch (Exception e) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800535 Slog.wtf(TAG, "removeObsoleteFiles: Can't parse file=" + file.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700536 file.delete();
537 continue;
538 }
539 if (!persistentTaskIds.contains(taskId)) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800540 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: deleting file=" + file.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700541 file.delete();
542 }
543 }
544 }
545 }
546
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800547 private void writeTaskIdsFiles() {
548 int candidateUserIds[];
549 synchronized (mService) {
550 candidateUserIds = mRecentTasks.usersWithRecentsLoadedLocked();
551 }
552 SparseBooleanArray taskIdsToSave;
553 for (int userId : candidateUserIds) {
554 synchronized (mService) {
555 taskIdsToSave = mRecentTasks.mPersistedTaskIds.get(userId).clone();
556 }
557 maybeWritePersistedTaskIdsForUser(taskIdsToSave, userId);
558 }
559 }
560
Craig Mautner21d24a22014-04-23 11:45:37 -0700561 private void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800562 int[] candidateUserIds;
563 synchronized (mService) {
564 // Remove only from directories of the users who have recents in memory synchronized
565 // with persistent storage.
566 candidateUserIds = mRecentTasks.usersWithRecentsLoadedLocked();
567 }
568 for (int userId : candidateUserIds) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800569 removeObsoleteFiles(persistentTaskIds, getUserImagesDir(userId).listFiles());
570 removeObsoleteFiles(persistentTaskIds, getUserTasksDir(userId).listFiles());
571 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700572 }
573
574 static Bitmap restoreImage(String filename) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700575 if (DEBUG) Slog.d(TAG, "restoreImage: restoring " + filename);
Suprabh Shukla23593142015-11-03 17:31:15 -0800576 return BitmapFactory.decodeFile(filename);
577 }
578
Suprabh Shuklaf50b4582016-02-23 17:44:22 -0800579 private File getUserPersistedTaskIdsFile(int userId) {
580 File userTaskIdsDir = new File(mTaskIdsDir, String.valueOf(userId));
581 if (!userTaskIdsDir.exists() && !userTaskIdsDir.mkdirs()) {
582 Slog.e(TAG, "Error while creating user directory: " + userTaskIdsDir);
583 }
584 return new File(userTaskIdsDir, PERSISTED_TASK_IDS_FILENAME);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800585 }
586
Suprabh Shukla23593142015-11-03 17:31:15 -0800587 static File getUserTasksDir(int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800588 File userTasksDir = new File(Environment.getDataSystemCeDirectory(userId), TASKS_DIRNAME);
Suprabh Shukla23593142015-11-03 17:31:15 -0800589
590 if (!userTasksDir.exists()) {
591 if (!userTasksDir.mkdir()) {
592 Slog.e(TAG, "Failure creating tasks directory for user " + userId + ": "
593 + userTasksDir);
594 }
595 }
596 return userTasksDir;
597 }
598
599 static File getUserImagesDir(int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800600 File userImagesDir = new File(Environment.getDataSystemCeDirectory(userId), IMAGES_DIRNAME);
Suprabh Shukla23593142015-11-03 17:31:15 -0800601
602 if (!userImagesDir.exists()) {
603 if (!userImagesDir.mkdir()) {
604 Slog.e(TAG, "Failure creating images directory for user " + userId + ": "
605 + userImagesDir);
606 }
607 }
608 return userImagesDir;
Craig Mautner21d24a22014-04-23 11:45:37 -0700609 }
610
611 private class LazyTaskWriterThread extends Thread {
Craig Mautner21d24a22014-04-23 11:45:37 -0700612
613 LazyTaskWriterThread(String name) {
614 super(name);
615 }
616
617 @Override
618 public void run() {
Riley Andrewsf16c2e82015-06-02 18:24:48 -0700619 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Craig Mautner21d24a22014-04-23 11:45:37 -0700620 ArraySet<Integer> persistentTaskIds = new ArraySet<Integer>();
621 while (true) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700622 // We can't lock mService while holding TaskPersister.this, but we don't want to
623 // call removeObsoleteFiles every time through the loop, only the last time before
624 // going to sleep. The risk is that we call removeObsoleteFiles() successively.
625 final boolean probablyDone;
Craig Mautner21d24a22014-04-23 11:45:37 -0700626 synchronized (TaskPersister.this) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700627 probablyDone = mWriteQueue.isEmpty();
628 }
629 if (probablyDone) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700630 if (DEBUG) Slog.d(TAG, "Looking for obsolete files.");
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700631 persistentTaskIds.clear();
632 synchronized (mService) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700633 if (DEBUG) Slog.d(TAG, "mRecents=" + mRecentTasks);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800634 for (int taskNdx = mRecentTasks.size() - 1; taskNdx >= 0; --taskNdx) {
635 final TaskRecord task = mRecentTasks.get(taskNdx);
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700636 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task +
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700637 " persistable=" + task.isPersistable);
638 if ((task.isPersistable || task.inRecents)
Wale Ogunwale18795a22014-12-03 11:38:33 -0800639 && (task.stack == null || !task.stack.isHomeStack())) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700640 if (DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700641 persistentTaskIds.add(task.taskId);
642 } else {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700643 if (DEBUG) Slog.d(TAG,
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700644 "omitting from persistentTaskIds task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700645 }
646 }
647 }
648 removeObsoleteFiles(persistentTaskIds);
649 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800650 writeTaskIdsFiles();
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700651
652 // If mNextWriteTime, then don't delay between each call to saveToXml().
653 final WriteQueueItem item;
654 synchronized (TaskPersister.this) {
Craig Mautner63f10902014-09-16 23:57:21 -0700655 if (mNextWriteTime != FLUSH_QUEUE) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700656 // The next write we don't have to wait so long.
657 mNextWriteTime = SystemClock.uptimeMillis() + INTER_WRITE_DELAY_MS;
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700658 if (DEBUG) Slog.d(TAG, "Next write time may be in " +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700659 INTER_WRITE_DELAY_MS + " msec. (" + mNextWriteTime + ")");
660 }
661
662 while (mWriteQueue.isEmpty()) {
Dianne Hackbornce0fd762014-09-19 12:58:15 -0700663 if (mNextWriteTime != 0) {
664 mNextWriteTime = 0; // idle.
665 TaskPersister.this.notifyAll(); // wake up flush() if needed.
666 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700667 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700668 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting indefinitely.");
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700669 TaskPersister.this.wait();
670 } catch (InterruptedException e) {
671 }
Craig Mautner63f10902014-09-16 23:57:21 -0700672 // Invariant: mNextWriteTime is either FLUSH_QUEUE or PRE_WRITE_DELAY_MS
673 // from now.
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700674 }
675 item = mWriteQueue.remove(0);
676
Craig Mautner21d24a22014-04-23 11:45:37 -0700677 long now = SystemClock.uptimeMillis();
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700678 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: now=" + now + " mNextWriteTime=" +
679 mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size());
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700680 while (now < mNextWriteTime) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700681 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700682 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting " +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700683 (mNextWriteTime - now));
684 TaskPersister.this.wait(mNextWriteTime - now);
Craig Mautner21d24a22014-04-23 11:45:37 -0700685 } catch (InterruptedException e) {
686 }
687 now = SystemClock.uptimeMillis();
688 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700689
690 // Got something to do.
Craig Mautner21d24a22014-04-23 11:45:37 -0700691 }
692
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700693 if (item instanceof ImageWriteQueueItem) {
694 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800695 final String filePath = imageWriteQueueItem.mFilePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700696 final Bitmap bitmap = imageWriteQueueItem.mImage;
Suprabh Shukla23593142015-11-03 17:31:15 -0800697 if (DEBUG) Slog.d(TAG, "writing bitmap: filename=" + filePath);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700698 FileOutputStream imageFile = null;
699 try {
Suprabh Shukla23593142015-11-03 17:31:15 -0800700 imageFile = new FileOutputStream(new File(filePath));
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700701 bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageFile);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700702 } catch (Exception e) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800703 Slog.e(TAG, "saveImage: unable to save " + filePath, e);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700704 } finally {
Wale Ogunwale18795a22014-12-03 11:38:33 -0800705 IoUtils.closeQuietly(imageFile);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700706 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700707 } else if (item instanceof TaskWriteQueueItem) {
708 // Write out one task.
709 StringWriter stringWriter = null;
710 TaskRecord task = ((TaskWriteQueueItem) item).mTask;
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700711 if (DEBUG) Slog.d(TAG, "Writing task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700712 synchronized (mService) {
Craig Mautner63f10902014-09-16 23:57:21 -0700713 if (task.inRecents) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700714 // Still there.
Craig Mautner21d24a22014-04-23 11:45:37 -0700715 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700716 if (DEBUG) Slog.d(TAG, "Saving task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700717 stringWriter = saveToXml(task);
718 } catch (IOException e) {
719 } catch (XmlPullParserException e) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700720 }
721 }
Dianne Hackborn852975d2014-08-22 17:42:43 -0700722 }
723 if (stringWriter != null) {
724 // Write out xml file while not holding mService lock.
725 FileOutputStream file = null;
726 AtomicFile atomicFile = null;
727 try {
Suprabh Shukla23593142015-11-03 17:31:15 -0800728 atomicFile = new AtomicFile(new File(
729 getUserTasksDir(task.userId),
730 String.valueOf(task.taskId) + RECENTS_FILENAME
731 + TASK_EXTENSION));
Dianne Hackborn852975d2014-08-22 17:42:43 -0700732 file = atomicFile.startWrite();
733 file.write(stringWriter.toString().getBytes());
734 file.write('\n');
735 atomicFile.finishWrite(file);
Suprabh Shukla23593142015-11-03 17:31:15 -0800736
Dianne Hackborn852975d2014-08-22 17:42:43 -0700737 } catch (IOException e) {
738 if (file != null) {
739 atomicFile.failWrite(file);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700740 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800741 Slog.e(TAG,
742 "Unable to open " + atomicFile + " for persisting. " + e);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700743 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700744 }
745 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700746 }
747 }
748 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700749}