blob: 11fd3bc61ca67e6c437b0126ee5d1c99ea42f499 [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<>();
Craig Mautner21d24a22014-04-23 11:45:37 -070091
Suprabh Shukla23593142015-11-03 17:31:15 -080092 /**
93 * Value determines write delay mode as follows: < 0 We are Flushing. No delays between writes
94 * until the image queue is drained and all tasks needing persisting are written to disk. There
95 * is no delay between writes. == 0 We are Idle. Next writes will be delayed by
96 * #PRE_TASK_DELAY_MS. > 0 We are Actively writing. Next write will be at this time. Subsequent
97 * writes will be delayed by #INTER_WRITE_DELAY_MS.
98 */
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070099 private long mNextWriteTime = 0;
Craig Mautner21d24a22014-04-23 11:45:37 -0700100
101 private final LazyTaskWriterThread mLazyTaskWriterThread;
102
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700103 private static class WriteQueueItem {}
Suprabh Shukla23593142015-11-03 17:31:15 -0800104
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700105 private static class TaskWriteQueueItem extends WriteQueueItem {
106 final TaskRecord mTask;
Winsonc809cbb2015-11-02 12:06:15 -0800107
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700108 TaskWriteQueueItem(TaskRecord task) {
109 mTask = task;
110 }
111 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800112
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700113 private static class ImageWriteQueueItem extends WriteQueueItem {
Suprabh Shukla23593142015-11-03 17:31:15 -0800114 final String mFilePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700115 Bitmap mImage;
Winsonc809cbb2015-11-02 12:06:15 -0800116
Suprabh Shukla23593142015-11-03 17:31:15 -0800117 ImageWriteQueueItem(String filePath, Bitmap image) {
118 mFilePath = filePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700119 mImage = image;
120 }
121 }
122
123 ArrayList<WriteQueueItem> mWriteQueue = new ArrayList<WriteQueueItem>();
124
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800125 TaskPersister(File systemDir, ActivityStackSupervisor stackSupervisor,
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800126 ActivityManagerService service, RecentTasks recentTasks) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800127
128 final File legacyImagesDir = new File(systemDir, IMAGES_DIRNAME);
129 if (legacyImagesDir.exists()) {
130 if (!FileUtils.deleteContents(legacyImagesDir) || !legacyImagesDir.delete()) {
131 Slog.i(TAG, "Failure deleting legacy images directory: " + legacyImagesDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700132 }
133 }
134
Suprabh Shukla23593142015-11-03 17:31:15 -0800135 final File legacyTasksDir = new File(systemDir, TASKS_DIRNAME);
136 if (legacyTasksDir.exists()) {
137 if (!FileUtils.deleteContents(legacyTasksDir) || !legacyTasksDir.delete()) {
138 Slog.i(TAG, "Failure deleting legacy tasks directory: " + legacyTasksDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700139 }
140 }
141
142 mStackSupervisor = stackSupervisor;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800143 mService = service;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800144 mRecentTasks = recentTasks;
Craig Mautner21d24a22014-04-23 11:45:37 -0700145 mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThread");
146 }
147
148 void startPersisting() {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800149 if (!mLazyTaskWriterThread.isAlive()) {
150 mLazyTaskWriterThread.start();
151 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700152 }
153
Craig Mautner63f10902014-09-16 23:57:21 -0700154 private void removeThumbnails(TaskRecord task) {
155 final String taskString = Integer.toString(task.taskId);
156 for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
157 final WriteQueueItem item = mWriteQueue.get(queueNdx);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800158 if (item instanceof ImageWriteQueueItem) {
159 final File thumbnailFile = new File(((ImageWriteQueueItem) item).mFilePath);
160 if (thumbnailFile.getName().startsWith(taskString)) {
161 if (DEBUG) {
162 Slog.d(TAG, "Removing " + ((ImageWriteQueueItem) item).mFilePath +
163 " from write queue");
164 }
165 mWriteQueue.remove(queueNdx);
166 }
Craig Mautner63f10902014-09-16 23:57:21 -0700167 }
168 }
169 }
170
171 private void yieldIfQueueTooDeep() {
172 boolean stall = false;
173 synchronized (this) {
174 if (mNextWriteTime == FLUSH_QUEUE) {
175 stall = true;
176 }
177 }
178 if (stall) {
179 Thread.yield();
180 }
181 }
182
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800183 @NonNull
184 SparseBooleanArray loadPersistedTaskIdsForUser(int userId) {
185 if (mTaskIdsInFile.get(userId) != null) {
186 return mTaskIdsInFile.get(userId).clone();
187 }
188 final SparseBooleanArray persistedTaskIds = new SparseBooleanArray();
189 BufferedReader reader = null;
190 String line;
191 try {
192 reader = new BufferedReader(new FileReader(getUserPersistedTaskIdsFile(userId)));
193 while ((line = reader.readLine()) != null) {
194 for (String taskIdString : line.split("\\s+")) {
195 int id = Integer.parseInt(taskIdString);
196 persistedTaskIds.put(id, true);
197 }
198 }
199 } catch (FileNotFoundException e) {
200 // File doesn't exist. Ignore.
201 } catch (Exception e) {
202 Slog.e(TAG, "Error while reading taskIds file for user " + userId, e);
203 } finally {
204 IoUtils.closeQuietly(reader);
205 }
206 mTaskIdsInFile.put(userId, persistedTaskIds);
207 return persistedTaskIds.clone();
208 }
209
210 private void maybeWritePersistedTaskIdsForUser(@NonNull SparseBooleanArray taskIds,
211 int userId) {
212 if (userId < 0) {
213 return;
214 }
215 SparseBooleanArray persistedIdsInFile = mTaskIdsInFile.get(userId);
216 if (persistedIdsInFile != null && persistedIdsInFile.equals(taskIds)) {
217 return;
218 }
219 final File persistedTaskIdsFile = getUserPersistedTaskIdsFile(userId);
220 BufferedWriter writer = null;
221 try {
222 writer = new BufferedWriter(new FileWriter(persistedTaskIdsFile));
223 for (int i = 0; i < taskIds.size(); i++) {
224 if (taskIds.valueAt(i)) {
225 writer.write(String.valueOf(taskIds.keyAt(i)));
226 writer.newLine();
227 }
228 }
229 } catch (Exception e) {
230 Slog.e(TAG, "Error while writing taskIds file for user " + userId, e);
231 } finally {
232 IoUtils.closeQuietly(writer);
233 }
234 mTaskIdsInFile.put(userId, taskIds.clone());
235 }
236
237 void unloadUserDataFromMemory(int userId) {
238 mTaskIdsInFile.delete(userId);
239 }
240
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700241 void wakeup(TaskRecord task, boolean flush) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700242 synchronized (this) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700243 if (task != null) {
244 int queueNdx;
245 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
246 final WriteQueueItem item = mWriteQueue.get(queueNdx);
247 if (item instanceof TaskWriteQueueItem &&
248 ((TaskWriteQueueItem) item).mTask == task) {
Craig Mautner63f10902014-09-16 23:57:21 -0700249 if (!task.inRecents) {
250 // This task is being removed.
251 removeThumbnails(task);
252 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700253 break;
254 }
255 }
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700256 if (queueNdx < 0 && task.isPersistable) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700257 mWriteQueue.add(new TaskWriteQueueItem(task));
258 }
259 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800260 // Dummy. Ensures removeObsoleteFiles is called when LazyTaskThreadWriter is
261 // notified.
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700262 mWriteQueue.add(new WriteQueueItem());
263 }
Craig Mautner63f10902014-09-16 23:57:21 -0700264 if (flush || mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
265 mNextWriteTime = FLUSH_QUEUE;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700266 } else if (mNextWriteTime == 0) {
267 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
268 }
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700269 if (DEBUG) Slog.d(TAG, "wakeup: task=" + task + " flush=" + flush + " mNextWriteTime="
270 + mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size()
271 + " Callers=" + Debug.getCallers(4));
Craig Mautner21d24a22014-04-23 11:45:37 -0700272 notifyAll();
273 }
Craig Mautner63f10902014-09-16 23:57:21 -0700274
275 yieldIfQueueTooDeep();
Craig Mautner21d24a22014-04-23 11:45:37 -0700276 }
277
Dianne Hackbornce0fd762014-09-19 12:58:15 -0700278 void flush() {
279 synchronized (this) {
280 mNextWriteTime = FLUSH_QUEUE;
281 notifyAll();
282 do {
283 try {
284 wait();
285 } catch (InterruptedException e) {
286 }
287 } while (mNextWriteTime == FLUSH_QUEUE);
288 }
289 }
290
Suprabh Shukla23593142015-11-03 17:31:15 -0800291 void saveImage(Bitmap image, String filePath) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700292 synchronized (this) {
293 int queueNdx;
294 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
295 final WriteQueueItem item = mWriteQueue.get(queueNdx);
296 if (item instanceof ImageWriteQueueItem) {
297 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800298 if (imageWriteQueueItem.mFilePath.equals(filePath)) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700299 // replace the Bitmap with the new one.
300 imageWriteQueueItem.mImage = image;
301 break;
302 }
303 }
304 }
305 if (queueNdx < 0) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800306 mWriteQueue.add(new ImageWriteQueueItem(filePath, image));
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700307 }
Craig Mautner63f10902014-09-16 23:57:21 -0700308 if (mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
309 mNextWriteTime = FLUSH_QUEUE;
310 } else if (mNextWriteTime == 0) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700311 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
312 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800313 if (DEBUG) Slog.d(TAG, "saveImage: filePath=" + filePath + " now=" +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700314 SystemClock.uptimeMillis() + " mNextWriteTime=" +
315 mNextWriteTime + " Callers=" + Debug.getCallers(4));
316 notifyAll();
317 }
Craig Mautner63f10902014-09-16 23:57:21 -0700318
319 yieldIfQueueTooDeep();
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700320 }
321
Suprabh Shukla23593142015-11-03 17:31:15 -0800322 Bitmap getTaskDescriptionIcon(String filePath) {
Craig Mautner648f69b2014-09-18 14:16:26 -0700323 // See if it is in the write queue
Suprabh Shukla23593142015-11-03 17:31:15 -0800324 final Bitmap icon = getImageFromWriteQueue(filePath);
Craig Mautner648f69b2014-09-18 14:16:26 -0700325 if (icon != null) {
326 return icon;
327 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800328 return restoreImage(filePath);
Craig Mautner648f69b2014-09-18 14:16:26 -0700329 }
330
Suprabh Shukla23593142015-11-03 17:31:15 -0800331 Bitmap getImageFromWriteQueue(String filePath) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700332 synchronized (this) {
333 for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
334 final WriteQueueItem item = mWriteQueue.get(queueNdx);
335 if (item instanceof ImageWriteQueueItem) {
336 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800337 if (imageWriteQueueItem.mFilePath.equals(filePath)) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700338 return imageWriteQueueItem.mImage;
339 }
340 }
341 }
342 return null;
343 }
344 }
345
Craig Mautner21d24a22014-04-23 11:45:37 -0700346 private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700347 if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task);
Craig Mautner21d24a22014-04-23 11:45:37 -0700348 final XmlSerializer xmlSerializer = new FastXmlSerializer();
349 StringWriter stringWriter = new StringWriter();
350 xmlSerializer.setOutput(stringWriter);
351
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700352 if (DEBUG) xmlSerializer.setFeature(
Suprabh Shukla23593142015-11-03 17:31:15 -0800353 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
Craig Mautner21d24a22014-04-23 11:45:37 -0700354
355 // save task
356 xmlSerializer.startDocument(null, true);
357
358 xmlSerializer.startTag(null, TAG_TASK);
359 task.saveToXml(xmlSerializer);
360 xmlSerializer.endTag(null, TAG_TASK);
361
362 xmlSerializer.endDocument();
363 xmlSerializer.flush();
364
365 return stringWriter;
366 }
367
Craig Mautner77b04262014-06-27 15:22:12 -0700368 private String fileToString(File file) {
369 final String newline = System.lineSeparator();
370 try {
371 BufferedReader reader = new BufferedReader(new FileReader(file));
372 StringBuffer sb = new StringBuffer((int) file.length() * 2);
373 String line;
374 while ((line = reader.readLine()) != null) {
375 sb.append(line + newline);
376 }
377 reader.close();
378 return sb.toString();
379 } catch (IOException ioe) {
380 Slog.e(TAG, "Couldn't read file " + file.getName());
381 return null;
382 }
383 }
384
Craig Mautnera228ae92014-07-09 05:44:55 -0700385 private TaskRecord taskIdToTask(int taskId, ArrayList<TaskRecord> tasks) {
386 if (taskId < 0) {
387 return null;
388 }
389 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
390 final TaskRecord task = tasks.get(taskNdx);
391 if (task.taskId == taskId) {
392 return task;
393 }
394 }
395 Slog.e(TAG, "Restore affiliation error looking for taskId=" + taskId);
396 return null;
397 }
398
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800399 List<TaskRecord> restoreTasksForUserLocked(final int userId) {
400 final ArrayList<TaskRecord> tasks = new ArrayList<TaskRecord>();
Craig Mautner21d24a22014-04-23 11:45:37 -0700401 ArraySet<Integer> recoveredTaskIds = new ArraySet<Integer>();
402
Suprabh Shukla23593142015-11-03 17:31:15 -0800403 File userTasksDir = getUserTasksDir(userId);
404
405 File[] recentFiles = userTasksDir.listFiles();
Craig Mautner21d24a22014-04-23 11:45:37 -0700406 if (recentFiles == null) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800407 Slog.e(TAG, "restoreTasksForUserLocked: Unable to list files from " + userTasksDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700408 return tasks;
409 }
410
411 for (int taskNdx = 0; taskNdx < recentFiles.length; ++taskNdx) {
412 File taskFile = recentFiles[taskNdx];
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800413 if (DEBUG) {
414 Slog.d(TAG, "restoreTasksForUserLocked: userId=" + userId
415 + ", taskFile=" + taskFile.getName());
416 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700417 BufferedReader reader = null;
Craig Mautnere0129b32014-05-25 16:41:09 -0700418 boolean deleteFile = false;
Craig Mautner21d24a22014-04-23 11:45:37 -0700419 try {
420 reader = new BufferedReader(new FileReader(taskFile));
421 final XmlPullParser in = Xml.newPullParser();
422 in.setInput(reader);
423
424 int event;
425 while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
426 event != XmlPullParser.END_TAG) {
427 final String name = in.getName();
428 if (event == XmlPullParser.START_TAG) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800429 if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: START_TAG name=" + name);
Craig Mautner21d24a22014-04-23 11:45:37 -0700430 if (TAG_TASK.equals(name)) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800431 final TaskRecord task = TaskRecord.restoreFromXml(in, mStackSupervisor);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800432 if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: restored task="
Suprabh Shukla23593142015-11-03 17:31:15 -0800433 + task);
Craig Mautner21d24a22014-04-23 11:45:37 -0700434 if (task != null) {
Dianne Hackborn852975d2014-08-22 17:42:43 -0700435 // XXX Don't add to write queue... there is no reason to write
436 // out the stuff we just read, if we don't write it we will
437 // read the same thing again.
Suprabh Shukla23593142015-11-03 17:31:15 -0800438 // mWriteQueue.add(new TaskWriteQueueItem(task));
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800439
Craig Mautner21d24a22014-04-23 11:45:37 -0700440 final int taskId = task.taskId;
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800441 if (mStackSupervisor.anyTaskForIdLocked(taskId,
442 /* restoreFromRecents= */ false, 0) != null) {
443 // Should not happen.
444 Slog.wtf(TAG, "Existing task with taskId " + taskId + "found");
445 } else if (userId != task.userId) {
446 // Should not happen.
447 Slog.wtf(TAG, "Task with userId " + task.userId + " found in "
448 + userTasksDir.getAbsolutePath());
449 } else {
450 // Looks fine.
451 mStackSupervisor.setNextTaskIdForUserLocked(taskId, userId);
Amith Yamasani515d4062015-09-28 11:30:06 -0700452 task.isPersistable = true;
453 tasks.add(task);
454 recoveredTaskIds.add(taskId);
455 }
Craig Mautner77b04262014-06-27 15:22:12 -0700456 } else {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800457 Slog.e(TAG, "restoreTasksForUserLocked: Unable to restore taskFile="
Suprabh Shukla23593142015-11-03 17:31:15 -0800458 + taskFile + ": " + fileToString(taskFile));
Craig Mautner21d24a22014-04-23 11:45:37 -0700459 }
460 } else {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800461 Slog.wtf(TAG, "restoreTasksForUserLocked: Unknown xml event=" + event
Suprabh Shukla23593142015-11-03 17:31:15 -0800462 + " name=" + name);
Craig Mautner21d24a22014-04-23 11:45:37 -0700463 }
464 }
465 XmlUtils.skipCurrentTag(in);
466 }
Craig Mautnere0129b32014-05-25 16:41:09 -0700467 } catch (Exception e) {
Craig Mautnera228ae92014-07-09 05:44:55 -0700468 Slog.wtf(TAG, "Unable to parse " + taskFile + ". Error ", e);
Craig Mautner77b04262014-06-27 15:22:12 -0700469 Slog.e(TAG, "Failing file: " + fileToString(taskFile));
Craig Mautnere0129b32014-05-25 16:41:09 -0700470 deleteFile = true;
Craig Mautner21d24a22014-04-23 11:45:37 -0700471 } finally {
Wale Ogunwale18795a22014-12-03 11:38:33 -0800472 IoUtils.closeQuietly(reader);
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700473 if (deleteFile) {
474 if (DEBUG) Slog.d(TAG, "Deleting file=" + taskFile.getName());
Craig Mautnere0129b32014-05-25 16:41:09 -0700475 taskFile.delete();
476 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700477 }
478 }
479
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700480 if (!DEBUG) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800481 removeObsoleteFiles(recoveredTaskIds, userTasksDir.listFiles());
482 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700483
Suprabh Shukla23593142015-11-03 17:31:15 -0800484 // Fix up task affiliation from taskIds
Craig Mautnera228ae92014-07-09 05:44:55 -0700485 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
486 final TaskRecord task = tasks.get(taskNdx);
487 task.setPrevAffiliate(taskIdToTask(task.mPrevAffiliateTaskId, tasks));
488 task.setNextAffiliate(taskIdToTask(task.mNextAffiliateTaskId, tasks));
489 }
490
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800491 Collections.sort(tasks, new Comparator<TaskRecord>() {
Craig Mautner21d24a22014-04-23 11:45:37 -0700492 @Override
493 public int compare(TaskRecord lhs, TaskRecord rhs) {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700494 final long diff = rhs.mLastTimeMoved - lhs.mLastTimeMoved;
Craig Mautner21d24a22014-04-23 11:45:37 -0700495 if (diff < 0) {
496 return -1;
497 } else if (diff > 0) {
498 return +1;
499 } else {
500 return 0;
501 }
502 }
503 });
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800504 return tasks;
Craig Mautner21d24a22014-04-23 11:45:37 -0700505 }
506
Craig Mautnere0129b32014-05-25 16:41:09 -0700507 private static void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds, File[] files) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800508 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: persistentTaskIds=" + persistentTaskIds +
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700509 " files=" + files);
Craig Mautnera5badf02014-09-11 12:47:03 -0700510 if (files == null) {
511 Slog.e(TAG, "File error accessing recents directory (too many files open?).");
512 return;
513 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700514 for (int fileNdx = 0; fileNdx < files.length; ++fileNdx) {
515 File file = files[fileNdx];
516 String filename = file.getName();
Craig Mautnerffcfcaa2014-06-05 09:54:38 -0700517 final int taskIdEnd = filename.indexOf('_');
Craig Mautner21d24a22014-04-23 11:45:37 -0700518 if (taskIdEnd > 0) {
519 final int taskId;
520 try {
521 taskId = Integer.valueOf(filename.substring(0, taskIdEnd));
Suprabh Shukla23593142015-11-03 17:31:15 -0800522 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: Found taskId=" + taskId);
Craig Mautner21d24a22014-04-23 11:45:37 -0700523 } catch (Exception e) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800524 Slog.wtf(TAG, "removeObsoleteFiles: Can't parse file=" + file.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700525 file.delete();
526 continue;
527 }
528 if (!persistentTaskIds.contains(taskId)) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800529 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: deleting file=" + file.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700530 file.delete();
531 }
532 }
533 }
534 }
535
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800536 private void writeTaskIdsFiles() {
537 int candidateUserIds[];
538 synchronized (mService) {
539 candidateUserIds = mRecentTasks.usersWithRecentsLoadedLocked();
540 }
541 SparseBooleanArray taskIdsToSave;
542 for (int userId : candidateUserIds) {
543 synchronized (mService) {
544 taskIdsToSave = mRecentTasks.mPersistedTaskIds.get(userId).clone();
545 }
546 maybeWritePersistedTaskIdsForUser(taskIdsToSave, userId);
547 }
548 }
549
Craig Mautner21d24a22014-04-23 11:45:37 -0700550 private void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800551 int[] candidateUserIds;
552 synchronized (mService) {
553 // Remove only from directories of the users who have recents in memory synchronized
554 // with persistent storage.
555 candidateUserIds = mRecentTasks.usersWithRecentsLoadedLocked();
556 }
557 for (int userId : candidateUserIds) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800558 removeObsoleteFiles(persistentTaskIds, getUserImagesDir(userId).listFiles());
559 removeObsoleteFiles(persistentTaskIds, getUserTasksDir(userId).listFiles());
560 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700561 }
562
563 static Bitmap restoreImage(String filename) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700564 if (DEBUG) Slog.d(TAG, "restoreImage: restoring " + filename);
Suprabh Shukla23593142015-11-03 17:31:15 -0800565 return BitmapFactory.decodeFile(filename);
566 }
567
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800568 static File getUserPersistedTaskIdsFile(int userId) {
569 return new File(Environment.getDataSystemDeDirectory(userId), PERSISTED_TASK_IDS_FILENAME);
570 }
571
Suprabh Shukla23593142015-11-03 17:31:15 -0800572 static File getUserTasksDir(int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800573 File userTasksDir = new File(Environment.getDataSystemCeDirectory(userId), TASKS_DIRNAME);
Suprabh Shukla23593142015-11-03 17:31:15 -0800574
575 if (!userTasksDir.exists()) {
576 if (!userTasksDir.mkdir()) {
577 Slog.e(TAG, "Failure creating tasks directory for user " + userId + ": "
578 + userTasksDir);
579 }
580 }
581 return userTasksDir;
582 }
583
584 static File getUserImagesDir(int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800585 File userImagesDir = new File(Environment.getDataSystemCeDirectory(userId), IMAGES_DIRNAME);
Suprabh Shukla23593142015-11-03 17:31:15 -0800586
587 if (!userImagesDir.exists()) {
588 if (!userImagesDir.mkdir()) {
589 Slog.e(TAG, "Failure creating images directory for user " + userId + ": "
590 + userImagesDir);
591 }
592 }
593 return userImagesDir;
Craig Mautner21d24a22014-04-23 11:45:37 -0700594 }
595
596 private class LazyTaskWriterThread extends Thread {
Craig Mautner21d24a22014-04-23 11:45:37 -0700597
598 LazyTaskWriterThread(String name) {
599 super(name);
600 }
601
602 @Override
603 public void run() {
Riley Andrewsf16c2e82015-06-02 18:24:48 -0700604 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Craig Mautner21d24a22014-04-23 11:45:37 -0700605 ArraySet<Integer> persistentTaskIds = new ArraySet<Integer>();
606 while (true) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700607 // We can't lock mService while holding TaskPersister.this, but we don't want to
608 // call removeObsoleteFiles every time through the loop, only the last time before
609 // going to sleep. The risk is that we call removeObsoleteFiles() successively.
610 final boolean probablyDone;
Craig Mautner21d24a22014-04-23 11:45:37 -0700611 synchronized (TaskPersister.this) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700612 probablyDone = mWriteQueue.isEmpty();
613 }
614 if (probablyDone) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700615 if (DEBUG) Slog.d(TAG, "Looking for obsolete files.");
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700616 persistentTaskIds.clear();
617 synchronized (mService) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700618 if (DEBUG) Slog.d(TAG, "mRecents=" + mRecentTasks);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800619 for (int taskNdx = mRecentTasks.size() - 1; taskNdx >= 0; --taskNdx) {
620 final TaskRecord task = mRecentTasks.get(taskNdx);
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700621 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task +
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700622 " persistable=" + task.isPersistable);
623 if ((task.isPersistable || task.inRecents)
Wale Ogunwale18795a22014-12-03 11:38:33 -0800624 && (task.stack == null || !task.stack.isHomeStack())) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700625 if (DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700626 persistentTaskIds.add(task.taskId);
627 } else {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700628 if (DEBUG) Slog.d(TAG,
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700629 "omitting from persistentTaskIds task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700630 }
631 }
632 }
633 removeObsoleteFiles(persistentTaskIds);
634 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800635 writeTaskIdsFiles();
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700636
637 // If mNextWriteTime, then don't delay between each call to saveToXml().
638 final WriteQueueItem item;
639 synchronized (TaskPersister.this) {
Craig Mautner63f10902014-09-16 23:57:21 -0700640 if (mNextWriteTime != FLUSH_QUEUE) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700641 // The next write we don't have to wait so long.
642 mNextWriteTime = SystemClock.uptimeMillis() + INTER_WRITE_DELAY_MS;
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700643 if (DEBUG) Slog.d(TAG, "Next write time may be in " +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700644 INTER_WRITE_DELAY_MS + " msec. (" + mNextWriteTime + ")");
645 }
646
647 while (mWriteQueue.isEmpty()) {
Dianne Hackbornce0fd762014-09-19 12:58:15 -0700648 if (mNextWriteTime != 0) {
649 mNextWriteTime = 0; // idle.
650 TaskPersister.this.notifyAll(); // wake up flush() if needed.
651 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700652 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700653 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting indefinitely.");
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700654 TaskPersister.this.wait();
655 } catch (InterruptedException e) {
656 }
Craig Mautner63f10902014-09-16 23:57:21 -0700657 // Invariant: mNextWriteTime is either FLUSH_QUEUE or PRE_WRITE_DELAY_MS
658 // from now.
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700659 }
660 item = mWriteQueue.remove(0);
661
Craig Mautner21d24a22014-04-23 11:45:37 -0700662 long now = SystemClock.uptimeMillis();
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700663 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: now=" + now + " mNextWriteTime=" +
664 mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size());
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700665 while (now < mNextWriteTime) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700666 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700667 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting " +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700668 (mNextWriteTime - now));
669 TaskPersister.this.wait(mNextWriteTime - now);
Craig Mautner21d24a22014-04-23 11:45:37 -0700670 } catch (InterruptedException e) {
671 }
672 now = SystemClock.uptimeMillis();
673 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700674
675 // Got something to do.
Craig Mautner21d24a22014-04-23 11:45:37 -0700676 }
677
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700678 if (item instanceof ImageWriteQueueItem) {
679 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800680 final String filePath = imageWriteQueueItem.mFilePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700681 final Bitmap bitmap = imageWriteQueueItem.mImage;
Suprabh Shukla23593142015-11-03 17:31:15 -0800682 if (DEBUG) Slog.d(TAG, "writing bitmap: filename=" + filePath);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700683 FileOutputStream imageFile = null;
684 try {
Suprabh Shukla23593142015-11-03 17:31:15 -0800685 imageFile = new FileOutputStream(new File(filePath));
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700686 bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageFile);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700687 } catch (Exception e) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800688 Slog.e(TAG, "saveImage: unable to save " + filePath, e);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700689 } finally {
Wale Ogunwale18795a22014-12-03 11:38:33 -0800690 IoUtils.closeQuietly(imageFile);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700691 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700692 } else if (item instanceof TaskWriteQueueItem) {
693 // Write out one task.
694 StringWriter stringWriter = null;
695 TaskRecord task = ((TaskWriteQueueItem) item).mTask;
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700696 if (DEBUG) Slog.d(TAG, "Writing task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700697 synchronized (mService) {
Craig Mautner63f10902014-09-16 23:57:21 -0700698 if (task.inRecents) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700699 // Still there.
Craig Mautner21d24a22014-04-23 11:45:37 -0700700 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700701 if (DEBUG) Slog.d(TAG, "Saving task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700702 stringWriter = saveToXml(task);
703 } catch (IOException e) {
704 } catch (XmlPullParserException e) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700705 }
706 }
Dianne Hackborn852975d2014-08-22 17:42:43 -0700707 }
708 if (stringWriter != null) {
709 // Write out xml file while not holding mService lock.
710 FileOutputStream file = null;
711 AtomicFile atomicFile = null;
712 try {
Suprabh Shukla23593142015-11-03 17:31:15 -0800713 atomicFile = new AtomicFile(new File(
714 getUserTasksDir(task.userId),
715 String.valueOf(task.taskId) + RECENTS_FILENAME
716 + TASK_EXTENSION));
Dianne Hackborn852975d2014-08-22 17:42:43 -0700717 file = atomicFile.startWrite();
718 file.write(stringWriter.toString().getBytes());
719 file.write('\n');
720 atomicFile.finishWrite(file);
Suprabh Shukla23593142015-11-03 17:31:15 -0800721
Dianne Hackborn852975d2014-08-22 17:42:43 -0700722 } catch (IOException e) {
723 if (file != null) {
724 atomicFile.failWrite(file);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700725 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800726 Slog.e(TAG,
727 "Unable to open " + atomicFile + " for persisting. " + e);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700728 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700729 }
730 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700731 }
732 }
733 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700734}