blob: 9829f9ab66b2660e95e0f4e7ba2bd18f93d66a9c [file] [log] [blame]
Dan Egnor4410ec82009-09-11 16:40:01 -07001/*
2 * Copyright (C) 2009 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;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.pm.PackageManager;
Doug Zongker43866e02010-01-07 12:09:54 -080025import android.database.ContentObserver;
Dan Egnor4410ec82009-09-11 16:40:01 -070026import android.net.Uri;
Dan Egnor3d40df32009-11-17 13:36:31 -080027import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080028import android.os.DropBoxManager;
Doug Zongker43866e02010-01-07 12:09:54 -080029import android.os.Handler;
Dan Egnor4410ec82009-09-11 16:40:01 -070030import android.os.ParcelFileDescriptor;
31import android.os.StatFs;
32import android.os.SystemClock;
33import android.provider.Settings;
Dan Egnor3d40df32009-11-17 13:36:31 -080034import android.text.format.Time;
Joe Onorato8a9b2202010-02-26 18:56:32 -080035import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070036
Dan Egnorf18a01c2009-11-12 11:32:50 -080037import com.android.internal.os.IDropBoxManagerService;
Dan Egnor95240272009-10-27 18:23:39 -070038
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070039import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070040import java.io.File;
41import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070042import java.io.FileOutputStream;
43import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070044import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070045import java.io.InputStreamReader;
46import java.io.OutputStream;
47import java.io.OutputStreamWriter;
48import java.io.PrintWriter;
49import java.io.UnsupportedEncodingException;
50import java.util.ArrayList;
51import java.util.Comparator;
Dan Egnor4410ec82009-09-11 16:40:01 -070052import java.util.HashMap;
53import java.util.Iterator;
54import java.util.Map;
55import java.util.SortedSet;
56import java.util.TreeSet;
57import java.util.zip.GZIPOutputStream;
58
59/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080060 * Implementation of {@link IDropBoxManagerService} using the filesystem.
61 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070062 */
Dan Egnorf18a01c2009-11-12 11:32:50 -080063public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
64 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070065 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070066 private static final int DEFAULT_MAX_FILES = 1000;
67 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
68 private static final int DEFAULT_QUOTA_PERCENT = 10;
69 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070070 private static final int QUOTA_RESCAN_MILLIS = 5000;
71
Dan Egnor3d40df32009-11-17 13:36:31 -080072 private static final boolean PROFILE_DUMP = false;
73
Dan Egnor4410ec82009-09-11 16:40:01 -070074 // TODO: This implementation currently uses one file per entry, which is
75 // inefficient for smallish entries -- consider using a single queue file
76 // per tag (or even globally) instead.
77
78 // The cached context and derived objects
79
80 private final Context mContext;
81 private final ContentResolver mContentResolver;
82 private final File mDropBoxDir;
83
84 // Accounting of all currently written log files (set in init()).
85
86 private FileList mAllFiles = null;
87 private HashMap<String, FileList> mFilesByTag = null;
88
89 // Various bits of disk information
90
91 private StatFs mStatFs = null;
92 private int mBlockSize = 0;
93 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
94 private long mCachedQuotaUptimeMillis = 0;
95
96 // Ensure that all log entries have a unique timestamp
97 private long mLastTimestamp = 0;
98
99 /** Receives events that might indicate a need to clean up files. */
100 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
101 @Override
102 public void onReceive(Context context, Intent intent) {
103 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700104
105 // Run the initialization in the background (not this main thread).
106 // The init() and trimToFit() methods are synchronized, so they still
107 // block other users -- but at least the onReceive() call can finish.
108 new Thread() {
109 public void run() {
110 try {
111 init();
112 trimToFit();
113 } catch (IOException e) {
114 Slog.e(TAG, "Can't init", e);
115 }
116 }
117 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700118 }
119 };
120
121 /**
122 * Creates an instance of managed drop box storage. Normally there is one of these
123 * run by the system, but others can be created for testing and other purposes.
124 *
125 * @param context to use for receiving free space & gservices intents
126 * @param path to store drop box entries in
127 */
Doug Zongker43866e02010-01-07 12:09:54 -0800128 public DropBoxManagerService(final Context context, File path) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700129 mDropBoxDir = path;
130
131 // Set up intent receivers
132 mContext = context;
133 mContentResolver = context.getContentResolver();
134 context.registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW));
Doug Zongker43866e02010-01-07 12:09:54 -0800135
136 mContentResolver.registerContentObserver(
137 Settings.Secure.CONTENT_URI, true,
138 new ContentObserver(new Handler()) {
139 public void onChange(boolean selfChange) {
140 mReceiver.onReceive(context, (Intent) null);
141 }
142 });
Dan Egnor4410ec82009-09-11 16:40:01 -0700143
144 // The real work gets done lazily in init() -- that way service creation always
145 // succeeds, and things like disk problems cause individual method failures.
146 }
147
148 /** Unregisters broadcast receivers and any other hooks -- for test instances */
149 public void stop() {
150 mContext.unregisterReceiver(mReceiver);
151 }
152
Dan Egnorf18a01c2009-11-12 11:32:50 -0800153 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700154 File temp = null;
155 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700156 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700157 try {
Dan Egnor95240272009-10-27 18:23:39 -0700158 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800159 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700160
161 init();
162 if (!isTagEnabled(tag)) return;
163 long max = trimToFit();
164 long lastTrim = System.currentTimeMillis();
165
166 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700167 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700168
169 // First, accumulate up to one block worth of data in memory before
170 // deciding whether to compress the data or not.
171
172 int read = 0;
173 while (read < buffer.length) {
174 int n = input.read(buffer, read, buffer.length - read);
175 if (n <= 0) break;
176 read += n;
177 }
178
179 // If we have at least one block, compress it -- otherwise, just write
180 // the data in uncompressed form.
181
182 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700183 int bufferSize = mBlockSize;
184 if (bufferSize > 4096) bufferSize = 4096;
185 if (bufferSize < 512) bufferSize = 512;
186 output = new BufferedOutputStream(new FileOutputStream(temp), bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800187 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700188 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800189 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700190 }
191
192 do {
193 output.write(buffer, 0, read);
194
195 long now = System.currentTimeMillis();
196 if (now - lastTrim > 30 * 1000) {
197 max = trimToFit(); // In case data dribbles in slowly
198 lastTrim = now;
199 }
200
201 read = input.read(buffer);
202 if (read <= 0) {
203 output.close(); // Get a final size measurement
204 output = null;
205 } else {
206 output.flush(); // So the size measurement is pseudo-reasonable
207 }
208
209 long len = temp.length();
210 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800211 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700212 temp.delete();
213 temp = null; // Pass temp = null to createEntry() to leave a tombstone
214 break;
215 }
216 } while (read > 0);
217
218 createEntry(temp, tag, flags);
219 temp = null;
220 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800221 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700222 } finally {
223 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700224 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700225 if (temp != null) temp.delete();
226 }
227 }
228
229 public boolean isTagEnabled(String tag) {
Doug Zongker43866e02010-01-07 12:09:54 -0800230 return !"disabled".equals(Settings.Secure.getString(
231 mContentResolver, Settings.Secure.DROPBOX_TAG_PREFIX + tag));
Dan Egnor4410ec82009-09-11 16:40:01 -0700232 }
233
Dan Egnorf18a01c2009-11-12 11:32:50 -0800234 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700235 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
236 != PackageManager.PERMISSION_GRANTED) {
237 throw new SecurityException("READ_LOGS permission required");
238 }
239
240 try {
241 init();
242 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800243 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700244 return null;
245 }
246
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700247 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
248 if (list == null) return null;
249
250 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700251 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800252 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
253 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700254 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700255 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800256 return new DropBoxManager.Entry(
257 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700258 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800259 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700260 // Continue to next file
261 }
262 }
263
264 return null;
265 }
266
267 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
268 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
269 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800270 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700271 return;
272 }
273
274 try {
275 init();
276 } catch (IOException e) {
277 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800278 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700279 return;
280 }
281
Dan Egnor3d40df32009-11-17 13:36:31 -0800282 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
283
Dan Egnor5ec249a2009-11-25 13:16:47 -0800284 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700285 boolean doPrint = false, doFile = false;
286 ArrayList<String> searchArgs = new ArrayList<String>();
287 for (int i = 0; args != null && i < args.length; i++) {
288 if (args[i].equals("-p") || args[i].equals("--print")) {
289 doPrint = true;
290 } else if (args[i].equals("-f") || args[i].equals("--file")) {
291 doFile = true;
292 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800293 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700294 } else {
295 searchArgs.add(args[i]);
296 }
297 }
298
Dan Egnor5ec249a2009-11-25 13:16:47 -0800299 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700300
301 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800302 out.append("Searching for:");
303 for (String a : searchArgs) out.append(" ").append(a);
304 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700305 }
306
Dan Egnor3d40df32009-11-17 13:36:31 -0800307 int numFound = 0, numArgs = searchArgs.size();
308 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800309 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700310 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800311 time.set(entry.timestampMillis);
312 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700313 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800314 for (int i = 0; i < numArgs && match; i++) {
315 String arg = searchArgs.get(i);
316 match = (date.contains(arg) || arg.equals(entry.tag));
317 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700318 if (!match) continue;
319
320 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800321 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800322 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700323 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800324 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700325 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800326 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800327 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700328 continue;
329 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800330 out.append(" (");
331 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
332 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
333 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700334 }
335
Dan Egnorf18a01c2009-11-12 11:32:50 -0800336 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800337 if (!doPrint) out.append(" ");
338 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700339 }
340
Dan Egnorf18a01c2009-11-12 11:32:50 -0800341 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
342 DropBoxManager.Entry dbe = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700343 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800344 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700345 entry.tag, entry.timestampMillis, entry.file, entry.flags);
346
347 if (doPrint) {
348 InputStreamReader r = new InputStreamReader(dbe.getInputStream());
349 char[] buf = new char[4096];
350 boolean newline = false;
351 for (;;) {
352 int n = r.read(buf);
353 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800354 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700355 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800356
357 // Flush periodically when printing to avoid out-of-memory.
358 if (out.length() > 65536) {
359 pw.write(out.toString());
360 out.setLength(0);
361 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700362 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800363 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700364 } else {
365 String text = dbe.getText(70);
366 boolean truncated = (text.length() == 70);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800367 out.append(" ").append(text.trim().replace('\n', '/'));
368 if (truncated) out.append(" ...");
369 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700370 }
371 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800372 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800373 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700374 } finally {
375 if (dbe != null) dbe.close();
376 }
377 }
378
Dan Egnor5ec249a2009-11-25 13:16:47 -0800379 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700380 }
381
Dan Egnor5ec249a2009-11-25 13:16:47 -0800382 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700383
384 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800385 if (!doPrint) out.append("\n");
386 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700387 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800388
389 pw.write(out.toString());
390 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700391 }
392
393 ///////////////////////////////////////////////////////////////////////////
394
395 /** Chronologically sorted list of {@link #EntryFile} */
396 private static final class FileList implements Comparable<FileList> {
397 public int blocks = 0;
398 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
399
400 /** Sorts bigger FileList instances before smaller ones. */
401 public final int compareTo(FileList o) {
402 if (blocks != o.blocks) return o.blocks - blocks;
403 if (this == o) return 0;
404 if (hashCode() < o.hashCode()) return -1;
405 if (hashCode() > o.hashCode()) return 1;
406 return 0;
407 }
408 }
409
410 /** Metadata describing an on-disk log file. */
411 private static final class EntryFile implements Comparable<EntryFile> {
412 public final String tag;
413 public final long timestampMillis;
414 public final int flags;
415 public final File file;
416 public final int blocks;
417
418 /** Sorts earlier EntryFile instances before later ones. */
419 public final int compareTo(EntryFile o) {
420 if (timestampMillis < o.timestampMillis) return -1;
421 if (timestampMillis > o.timestampMillis) return 1;
422 if (file != null && o.file != null) return file.compareTo(o.file);
423 if (o.file != null) return -1;
424 if (file != null) return 1;
425 if (this == o) return 0;
426 if (hashCode() < o.hashCode()) return -1;
427 if (hashCode() > o.hashCode()) return 1;
428 return 0;
429 }
430
431 /**
432 * Moves an existing temporary file to a new log filename.
433 * @param temp file to rename
434 * @param dir to store file in
435 * @param tag to use for new log file name
436 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700437 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700438 * @param blockSize to use for space accounting
439 * @throws IOException if the file can't be moved
440 */
441 public EntryFile(File temp, File dir, String tag,long timestampMillis,
442 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800443 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700444
445 this.tag = tag;
446 this.timestampMillis = timestampMillis;
447 this.flags = flags;
448 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800449 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
450 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700451
452 if (!temp.renameTo(this.file)) {
453 throw new IOException("Can't rename " + temp + " to " + this.file);
454 }
455 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
456 }
457
458 /**
459 * Creates a zero-length tombstone for a file whose contents were lost.
460 * @param dir to store file in
461 * @param tag to use for new log file name
462 * @param timestampMillis of log entry
463 * @throws IOException if the file can't be created.
464 */
465 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
466 this.tag = tag;
467 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800468 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700469 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
470 this.blocks = 0;
471 new FileOutputStream(this.file).close();
472 }
473
474 /**
475 * Extracts metadata from an existing on-disk log filename.
476 * @param file name of existing log file
477 * @param blockSize to use for space accounting
478 */
479 public EntryFile(File file, int blockSize) {
480 this.file = file;
481 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
482
483 String name = file.getName();
484 int at = name.lastIndexOf('@');
485 if (at < 0) {
486 this.tag = null;
487 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800488 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700489 return;
490 }
491
492 int flags = 0;
493 this.tag = Uri.decode(name.substring(0, at));
494 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800495 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700496 name = name.substring(0, name.length() - 3);
497 }
498 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800499 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700500 name = name.substring(at + 1, name.length() - 5);
501 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800502 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700503 name = name.substring(at + 1, name.length() - 4);
504 } else if (name.endsWith(".dat")) {
505 name = name.substring(at + 1, name.length() - 4);
506 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800507 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700508 this.timestampMillis = 0;
509 return;
510 }
511 this.flags = flags;
512
513 long millis;
514 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
515 this.timestampMillis = millis;
516 }
517
518 /**
519 * Creates a EntryFile object with only a timestamp for comparison purposes.
520 * @param timestampMillis to compare with.
521 */
522 public EntryFile(long millis) {
523 this.tag = null;
524 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800525 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700526 this.file = null;
527 this.blocks = 0;
528 }
529 }
530
531 ///////////////////////////////////////////////////////////////////////////
532
533 /** If never run before, scans disk contents to build in-memory tracking data. */
534 private synchronized void init() throws IOException {
535 if (mStatFs == null) {
536 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
537 throw new IOException("Can't mkdir: " + mDropBoxDir);
538 }
539 try {
540 mStatFs = new StatFs(mDropBoxDir.getPath());
541 mBlockSize = mStatFs.getBlockSize();
542 } catch (IllegalArgumentException e) { // StatFs throws this on error
543 throw new IOException("Can't statfs: " + mDropBoxDir);
544 }
545 }
546
547 if (mAllFiles == null) {
548 File[] files = mDropBoxDir.listFiles();
549 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
550
551 mAllFiles = new FileList();
552 mFilesByTag = new HashMap<String, FileList>();
553
554 // Scan pre-existing files.
555 for (File file : files) {
556 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800557 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700558 file.delete();
559 continue;
560 }
561
562 EntryFile entry = new EntryFile(file, mBlockSize);
563 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800564 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700565 continue;
566 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800567 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700568 file.delete();
569 continue;
570 }
571
572 enrollEntry(entry);
573 }
574 }
575 }
576
577 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
578 private synchronized void enrollEntry(EntryFile entry) {
579 mAllFiles.contents.add(entry);
580 mAllFiles.blocks += entry.blocks;
581
582 // mFilesByTag is used for trimming, so don't list empty files.
583 // (Zero-length/lost files are trimmed by date from mAllFiles.)
584
585 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
586 FileList tagFiles = mFilesByTag.get(entry.tag);
587 if (tagFiles == null) {
588 tagFiles = new FileList();
589 mFilesByTag.put(entry.tag, tagFiles);
590 }
591 tagFiles.contents.add(entry);
592 tagFiles.blocks += entry.blocks;
593 }
594 }
595
596 /** Moves a temporary file to a final log filename and enrolls it. */
597 private synchronized void createEntry(File temp, String tag, int flags) throws IOException {
598 long t = System.currentTimeMillis();
599
600 // Require each entry to have a unique timestamp; if there are entries
601 // >10sec in the future (due to clock skew), drag them back to avoid
602 // keeping them around forever.
603
604 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
605 EntryFile[] future = null;
606 if (!tail.isEmpty()) {
607 future = tail.toArray(new EntryFile[tail.size()]);
608 tail.clear(); // Remove from mAllFiles
609 }
610
611 if (!mAllFiles.contents.isEmpty()) {
612 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
613 }
614
615 if (future != null) {
616 for (EntryFile late : future) {
617 mAllFiles.blocks -= late.blocks;
618 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800619 if (tagFiles != null && tagFiles.contents.remove(late)) {
620 tagFiles.blocks -= late.blocks;
621 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800622 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700623 enrollEntry(new EntryFile(
624 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
625 } else {
626 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
627 }
628 }
629 }
630
631 if (temp == null) {
632 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
633 } else {
634 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
635 }
636 }
637
638 /**
639 * Trims the files on disk to make sure they aren't using too much space.
640 * @return the overall quota for storage (in bytes)
641 */
642 private synchronized long trimToFit() {
643 // Expunge aged items (including tombstones marking deleted data).
644
Doug Zongker43866e02010-01-07 12:09:54 -0800645 int ageSeconds = Settings.Secure.getInt(mContentResolver,
646 Settings.Secure.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700647 int maxFiles = Settings.Secure.getInt(mContentResolver,
648 Settings.Secure.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700649 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
650 while (!mAllFiles.contents.isEmpty()) {
651 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700652 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700653
654 FileList tag = mFilesByTag.get(entry.tag);
655 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
656 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
657 if (entry.file != null) entry.file.delete();
658 }
659
660 // Compute overall quota (a fraction of available free space) in blocks.
661 // The quota changes dynamically based on the amount of free space;
662 // that way when lots of data is available we can use it, but we'll get
663 // out of the way if storage starts getting tight.
664
665 long uptimeMillis = SystemClock.uptimeMillis();
666 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Doug Zongker43866e02010-01-07 12:09:54 -0800667 int quotaPercent = Settings.Secure.getInt(mContentResolver,
668 Settings.Secure.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
669 int reservePercent = Settings.Secure.getInt(mContentResolver,
670 Settings.Secure.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
671 int quotaKb = Settings.Secure.getInt(mContentResolver,
672 Settings.Secure.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700673
674 mStatFs.restat(mDropBoxDir.getPath());
675 int available = mStatFs.getAvailableBlocks();
676 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
677 int maximum = quotaKb * 1024 / mBlockSize;
678 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
679 mCachedQuotaUptimeMillis = uptimeMillis;
680 }
681
682 // If we're using too much space, delete old items to make room.
683 //
684 // We trim each tag independently (this is why we keep per-tag lists).
685 // Space is "fairly" shared between tags -- they are all squeezed
686 // equally until enough space is reclaimed.
687 //
688 // A single circular buffer (a la logcat) would be simpler, but this
689 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
690 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700691 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700692 //
693 // Deleted files are replaced with zero-length tombstones to mark what
694 // was lost. Tombstones are expunged by age (see above).
695
696 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700697 // Find a fair share amount of space to limit each tag
698 int unsqueezed = mAllFiles.blocks, squeezed = 0;
699 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
700 for (FileList tag : tags) {
701 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
702 break;
703 }
704 unsqueezed -= tag.blocks;
705 squeezed++;
706 }
707 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
708
709 // Remove old items from each tag until it meets the per-tag quota.
710 for (FileList tag : tags) {
711 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
712 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
713 EntryFile entry = tag.contents.first();
714 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
715 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
716
717 try {
718 if (entry.file != null) entry.file.delete();
719 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
720 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800721 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700722 }
723 }
724 }
725 }
726
727 return mCachedQuotaBlocks * mBlockSize;
728 }
729}