blob: 7a708f9d2f035f9e7f2487541711fc6fc14611b7 [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;
Dan Egnor4410ec82009-09-11 16:40:01 -070035import android.util.Log;
36
Dan Egnorf18a01c2009-11-12 11:32:50 -080037import com.android.internal.os.IDropBoxManagerService;
Dan Egnor95240272009-10-27 18:23:39 -070038
Dan Egnor4410ec82009-09-11 16:40:01 -070039import java.io.File;
40import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070041import java.io.FileOutputStream;
42import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070043import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070044import java.io.InputStreamReader;
45import java.io.OutputStream;
46import java.io.OutputStreamWriter;
47import java.io.PrintWriter;
48import java.io.UnsupportedEncodingException;
49import java.util.ArrayList;
50import java.util.Comparator;
Dan Egnor4410ec82009-09-11 16:40:01 -070051import java.util.HashMap;
52import java.util.Iterator;
53import java.util.Map;
54import java.util.SortedSet;
55import java.util.TreeSet;
56import java.util.zip.GZIPOutputStream;
57
58/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080059 * Implementation of {@link IDropBoxManagerService} using the filesystem.
60 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070061 */
Dan Egnorf18a01c2009-11-12 11:32:50 -080062public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
63 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070064 private static final int DEFAULT_RESERVE_PERCENT = 10;
65 private static final int DEFAULT_QUOTA_PERCENT = 10;
66 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
67 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
68 private static final int QUOTA_RESCAN_MILLIS = 5000;
69
Dan Egnor3d40df32009-11-17 13:36:31 -080070 private static final boolean PROFILE_DUMP = false;
71
Dan Egnor4410ec82009-09-11 16:40:01 -070072 // TODO: This implementation currently uses one file per entry, which is
73 // inefficient for smallish entries -- consider using a single queue file
74 // per tag (or even globally) instead.
75
76 // The cached context and derived objects
77
78 private final Context mContext;
79 private final ContentResolver mContentResolver;
80 private final File mDropBoxDir;
81
82 // Accounting of all currently written log files (set in init()).
83
84 private FileList mAllFiles = null;
85 private HashMap<String, FileList> mFilesByTag = null;
86
87 // Various bits of disk information
88
89 private StatFs mStatFs = null;
90 private int mBlockSize = 0;
91 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
92 private long mCachedQuotaUptimeMillis = 0;
93
94 // Ensure that all log entries have a unique timestamp
95 private long mLastTimestamp = 0;
96
97 /** Receives events that might indicate a need to clean up files. */
98 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
99 @Override
100 public void onReceive(Context context, Intent intent) {
101 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
102 try {
103 init();
104 trimToFit();
105 } catch (IOException e) {
106 Log.e(TAG, "Can't init", e);
107 }
108 }
109 };
110
111 /**
112 * Creates an instance of managed drop box storage. Normally there is one of these
113 * run by the system, but others can be created for testing and other purposes.
114 *
115 * @param context to use for receiving free space & gservices intents
116 * @param path to store drop box entries in
117 */
Doug Zongker43866e02010-01-07 12:09:54 -0800118 public DropBoxManagerService(final Context context, File path) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700119 mDropBoxDir = path;
120
121 // Set up intent receivers
122 mContext = context;
123 mContentResolver = context.getContentResolver();
124 context.registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW));
Doug Zongker43866e02010-01-07 12:09:54 -0800125
126 mContentResolver.registerContentObserver(
127 Settings.Secure.CONTENT_URI, true,
128 new ContentObserver(new Handler()) {
129 public void onChange(boolean selfChange) {
130 mReceiver.onReceive(context, (Intent) null);
131 }
132 });
Dan Egnor4410ec82009-09-11 16:40:01 -0700133
134 // The real work gets done lazily in init() -- that way service creation always
135 // succeeds, and things like disk problems cause individual method failures.
136 }
137
138 /** Unregisters broadcast receivers and any other hooks -- for test instances */
139 public void stop() {
140 mContext.unregisterReceiver(mReceiver);
141 }
142
Dan Egnorf18a01c2009-11-12 11:32:50 -0800143 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700144 File temp = null;
145 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700146 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700147 try {
Dan Egnor95240272009-10-27 18:23:39 -0700148 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800149 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700150
151 init();
152 if (!isTagEnabled(tag)) return;
153 long max = trimToFit();
154 long lastTrim = System.currentTimeMillis();
155
156 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700157 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700158
159 // First, accumulate up to one block worth of data in memory before
160 // deciding whether to compress the data or not.
161
162 int read = 0;
163 while (read < buffer.length) {
164 int n = input.read(buffer, read, buffer.length - read);
165 if (n <= 0) break;
166 read += n;
167 }
168
169 // If we have at least one block, compress it -- otherwise, just write
170 // the data in uncompressed form.
171
172 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
173 output = new FileOutputStream(temp);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800174 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700175 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800176 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700177 }
178
179 do {
180 output.write(buffer, 0, read);
181
182 long now = System.currentTimeMillis();
183 if (now - lastTrim > 30 * 1000) {
184 max = trimToFit(); // In case data dribbles in slowly
185 lastTrim = now;
186 }
187
188 read = input.read(buffer);
189 if (read <= 0) {
190 output.close(); // Get a final size measurement
191 output = null;
192 } else {
193 output.flush(); // So the size measurement is pseudo-reasonable
194 }
195
196 long len = temp.length();
197 if (len > max) {
198 Log.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
199 temp.delete();
200 temp = null; // Pass temp = null to createEntry() to leave a tombstone
201 break;
202 }
203 } while (read > 0);
204
205 createEntry(temp, tag, flags);
206 temp = null;
207 } catch (IOException e) {
208 Log.e(TAG, "Can't write: " + tag, e);
209 } finally {
210 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700211 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700212 if (temp != null) temp.delete();
213 }
214 }
215
216 public boolean isTagEnabled(String tag) {
Doug Zongker43866e02010-01-07 12:09:54 -0800217 return !"disabled".equals(Settings.Secure.getString(
218 mContentResolver, Settings.Secure.DROPBOX_TAG_PREFIX + tag));
Dan Egnor4410ec82009-09-11 16:40:01 -0700219 }
220
Dan Egnorf18a01c2009-11-12 11:32:50 -0800221 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700222 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
223 != PackageManager.PERMISSION_GRANTED) {
224 throw new SecurityException("READ_LOGS permission required");
225 }
226
227 try {
228 init();
229 } catch (IOException e) {
230 Log.e(TAG, "Can't init", e);
231 return null;
232 }
233
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700234 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
235 if (list == null) return null;
236
237 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700238 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800239 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
240 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700241 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700242 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800243 return new DropBoxManager.Entry(
244 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700245 } catch (IOException e) {
246 Log.e(TAG, "Can't read: " + entry.file, e);
247 // Continue to next file
248 }
249 }
250
251 return null;
252 }
253
254 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
255 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
256 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800257 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700258 return;
259 }
260
261 try {
262 init();
263 } catch (IOException e) {
264 pw.println("Can't initialize: " + e);
265 Log.e(TAG, "Can't init", e);
266 return;
267 }
268
Dan Egnor3d40df32009-11-17 13:36:31 -0800269 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
270
Dan Egnor5ec249a2009-11-25 13:16:47 -0800271 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700272 boolean doPrint = false, doFile = false;
273 ArrayList<String> searchArgs = new ArrayList<String>();
274 for (int i = 0; args != null && i < args.length; i++) {
275 if (args[i].equals("-p") || args[i].equals("--print")) {
276 doPrint = true;
277 } else if (args[i].equals("-f") || args[i].equals("--file")) {
278 doFile = true;
279 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800280 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700281 } else {
282 searchArgs.add(args[i]);
283 }
284 }
285
Dan Egnor5ec249a2009-11-25 13:16:47 -0800286 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700287
288 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800289 out.append("Searching for:");
290 for (String a : searchArgs) out.append(" ").append(a);
291 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700292 }
293
Dan Egnor3d40df32009-11-17 13:36:31 -0800294 int numFound = 0, numArgs = searchArgs.size();
295 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800296 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700297 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800298 time.set(entry.timestampMillis);
299 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700300 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800301 for (int i = 0; i < numArgs && match; i++) {
302 String arg = searchArgs.get(i);
303 match = (date.contains(arg) || arg.equals(entry.tag));
304 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700305 if (!match) continue;
306
307 numFound++;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800308 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700309 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800310 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700311 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800312 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800313 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700314 continue;
315 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800316 out.append(" (");
317 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
318 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
319 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700320 }
321
Dan Egnorf18a01c2009-11-12 11:32:50 -0800322 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800323 if (!doPrint) out.append(" ");
324 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700325 }
326
Dan Egnorf18a01c2009-11-12 11:32:50 -0800327 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
328 DropBoxManager.Entry dbe = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700329 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800330 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700331 entry.tag, entry.timestampMillis, entry.file, entry.flags);
332
333 if (doPrint) {
334 InputStreamReader r = new InputStreamReader(dbe.getInputStream());
335 char[] buf = new char[4096];
336 boolean newline = false;
337 for (;;) {
338 int n = r.read(buf);
339 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800340 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700341 newline = (buf[n - 1] == '\n');
342 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800343 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700344 } else {
345 String text = dbe.getText(70);
346 boolean truncated = (text.length() == 70);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800347 out.append(" ").append(text.trim().replace('\n', '/'));
348 if (truncated) out.append(" ...");
349 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700350 }
351 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800352 out.append("*** ").append(e.toString()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700353 Log.e(TAG, "Can't read: " + entry.file, e);
354 } finally {
355 if (dbe != null) dbe.close();
356 }
357 }
358
Dan Egnor5ec249a2009-11-25 13:16:47 -0800359 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700360 }
361
Dan Egnor5ec249a2009-11-25 13:16:47 -0800362 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700363
364 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800365 if (!doPrint) out.append("\n");
366 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700367 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800368
369 pw.write(out.toString());
370 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700371 }
372
373 ///////////////////////////////////////////////////////////////////////////
374
375 /** Chronologically sorted list of {@link #EntryFile} */
376 private static final class FileList implements Comparable<FileList> {
377 public int blocks = 0;
378 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
379
380 /** Sorts bigger FileList instances before smaller ones. */
381 public final int compareTo(FileList o) {
382 if (blocks != o.blocks) return o.blocks - blocks;
383 if (this == o) return 0;
384 if (hashCode() < o.hashCode()) return -1;
385 if (hashCode() > o.hashCode()) return 1;
386 return 0;
387 }
388 }
389
390 /** Metadata describing an on-disk log file. */
391 private static final class EntryFile implements Comparable<EntryFile> {
392 public final String tag;
393 public final long timestampMillis;
394 public final int flags;
395 public final File file;
396 public final int blocks;
397
398 /** Sorts earlier EntryFile instances before later ones. */
399 public final int compareTo(EntryFile o) {
400 if (timestampMillis < o.timestampMillis) return -1;
401 if (timestampMillis > o.timestampMillis) return 1;
402 if (file != null && o.file != null) return file.compareTo(o.file);
403 if (o.file != null) return -1;
404 if (file != null) return 1;
405 if (this == o) return 0;
406 if (hashCode() < o.hashCode()) return -1;
407 if (hashCode() > o.hashCode()) return 1;
408 return 0;
409 }
410
411 /**
412 * Moves an existing temporary file to a new log filename.
413 * @param temp file to rename
414 * @param dir to store file in
415 * @param tag to use for new log file name
416 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700417 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700418 * @param blockSize to use for space accounting
419 * @throws IOException if the file can't be moved
420 */
421 public EntryFile(File temp, File dir, String tag,long timestampMillis,
422 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800423 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700424
425 this.tag = tag;
426 this.timestampMillis = timestampMillis;
427 this.flags = flags;
428 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800429 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
430 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700431
432 if (!temp.renameTo(this.file)) {
433 throw new IOException("Can't rename " + temp + " to " + this.file);
434 }
435 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
436 }
437
438 /**
439 * Creates a zero-length tombstone for a file whose contents were lost.
440 * @param dir to store file in
441 * @param tag to use for new log file name
442 * @param timestampMillis of log entry
443 * @throws IOException if the file can't be created.
444 */
445 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
446 this.tag = tag;
447 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800448 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700449 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
450 this.blocks = 0;
451 new FileOutputStream(this.file).close();
452 }
453
454 /**
455 * Extracts metadata from an existing on-disk log filename.
456 * @param file name of existing log file
457 * @param blockSize to use for space accounting
458 */
459 public EntryFile(File file, int blockSize) {
460 this.file = file;
461 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
462
463 String name = file.getName();
464 int at = name.lastIndexOf('@');
465 if (at < 0) {
466 this.tag = null;
467 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800468 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700469 return;
470 }
471
472 int flags = 0;
473 this.tag = Uri.decode(name.substring(0, at));
474 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800475 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700476 name = name.substring(0, name.length() - 3);
477 }
478 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800479 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700480 name = name.substring(at + 1, name.length() - 5);
481 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800482 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700483 name = name.substring(at + 1, name.length() - 4);
484 } else if (name.endsWith(".dat")) {
485 name = name.substring(at + 1, name.length() - 4);
486 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800487 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700488 this.timestampMillis = 0;
489 return;
490 }
491 this.flags = flags;
492
493 long millis;
494 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
495 this.timestampMillis = millis;
496 }
497
498 /**
499 * Creates a EntryFile object with only a timestamp for comparison purposes.
500 * @param timestampMillis to compare with.
501 */
502 public EntryFile(long millis) {
503 this.tag = null;
504 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800505 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700506 this.file = null;
507 this.blocks = 0;
508 }
509 }
510
511 ///////////////////////////////////////////////////////////////////////////
512
513 /** If never run before, scans disk contents to build in-memory tracking data. */
514 private synchronized void init() throws IOException {
515 if (mStatFs == null) {
516 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
517 throw new IOException("Can't mkdir: " + mDropBoxDir);
518 }
519 try {
520 mStatFs = new StatFs(mDropBoxDir.getPath());
521 mBlockSize = mStatFs.getBlockSize();
522 } catch (IllegalArgumentException e) { // StatFs throws this on error
523 throw new IOException("Can't statfs: " + mDropBoxDir);
524 }
525 }
526
527 if (mAllFiles == null) {
528 File[] files = mDropBoxDir.listFiles();
529 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
530
531 mAllFiles = new FileList();
532 mFilesByTag = new HashMap<String, FileList>();
533
534 // Scan pre-existing files.
535 for (File file : files) {
536 if (file.getName().endsWith(".tmp")) {
537 Log.i(TAG, "Cleaning temp file: " + file);
538 file.delete();
539 continue;
540 }
541
542 EntryFile entry = new EntryFile(file, mBlockSize);
543 if (entry.tag == null) {
544 Log.w(TAG, "Unrecognized file: " + file);
545 continue;
546 } else if (entry.timestampMillis == 0) {
547 Log.w(TAG, "Invalid filename: " + file);
548 file.delete();
549 continue;
550 }
551
552 enrollEntry(entry);
553 }
554 }
555 }
556
557 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
558 private synchronized void enrollEntry(EntryFile entry) {
559 mAllFiles.contents.add(entry);
560 mAllFiles.blocks += entry.blocks;
561
562 // mFilesByTag is used for trimming, so don't list empty files.
563 // (Zero-length/lost files are trimmed by date from mAllFiles.)
564
565 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
566 FileList tagFiles = mFilesByTag.get(entry.tag);
567 if (tagFiles == null) {
568 tagFiles = new FileList();
569 mFilesByTag.put(entry.tag, tagFiles);
570 }
571 tagFiles.contents.add(entry);
572 tagFiles.blocks += entry.blocks;
573 }
574 }
575
576 /** Moves a temporary file to a final log filename and enrolls it. */
577 private synchronized void createEntry(File temp, String tag, int flags) throws IOException {
578 long t = System.currentTimeMillis();
579
580 // Require each entry to have a unique timestamp; if there are entries
581 // >10sec in the future (due to clock skew), drag them back to avoid
582 // keeping them around forever.
583
584 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
585 EntryFile[] future = null;
586 if (!tail.isEmpty()) {
587 future = tail.toArray(new EntryFile[tail.size()]);
588 tail.clear(); // Remove from mAllFiles
589 }
590
591 if (!mAllFiles.contents.isEmpty()) {
592 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
593 }
594
595 if (future != null) {
596 for (EntryFile late : future) {
597 mAllFiles.blocks -= late.blocks;
598 FileList tagFiles = mFilesByTag.get(late.tag);
599 if (tagFiles.contents.remove(late)) tagFiles.blocks -= late.blocks;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800600 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700601 enrollEntry(new EntryFile(
602 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
603 } else {
604 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
605 }
606 }
607 }
608
609 if (temp == null) {
610 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
611 } else {
612 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
613 }
614 }
615
616 /**
617 * Trims the files on disk to make sure they aren't using too much space.
618 * @return the overall quota for storage (in bytes)
619 */
620 private synchronized long trimToFit() {
621 // Expunge aged items (including tombstones marking deleted data).
622
Doug Zongker43866e02010-01-07 12:09:54 -0800623 int ageSeconds = Settings.Secure.getInt(mContentResolver,
624 Settings.Secure.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Dan Egnor4410ec82009-09-11 16:40:01 -0700625 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
626 while (!mAllFiles.contents.isEmpty()) {
627 EntryFile entry = mAllFiles.contents.first();
628 if (entry.timestampMillis > cutoffMillis) break;
629
630 FileList tag = mFilesByTag.get(entry.tag);
631 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
632 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
633 if (entry.file != null) entry.file.delete();
634 }
635
636 // Compute overall quota (a fraction of available free space) in blocks.
637 // The quota changes dynamically based on the amount of free space;
638 // that way when lots of data is available we can use it, but we'll get
639 // out of the way if storage starts getting tight.
640
641 long uptimeMillis = SystemClock.uptimeMillis();
642 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Doug Zongker43866e02010-01-07 12:09:54 -0800643 int quotaPercent = Settings.Secure.getInt(mContentResolver,
644 Settings.Secure.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
645 int reservePercent = Settings.Secure.getInt(mContentResolver,
646 Settings.Secure.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
647 int quotaKb = Settings.Secure.getInt(mContentResolver,
648 Settings.Secure.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700649
650 mStatFs.restat(mDropBoxDir.getPath());
651 int available = mStatFs.getAvailableBlocks();
652 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
653 int maximum = quotaKb * 1024 / mBlockSize;
654 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
655 mCachedQuotaUptimeMillis = uptimeMillis;
656 }
657
658 // If we're using too much space, delete old items to make room.
659 //
660 // We trim each tag independently (this is why we keep per-tag lists).
661 // Space is "fairly" shared between tags -- they are all squeezed
662 // equally until enough space is reclaimed.
663 //
664 // A single circular buffer (a la logcat) would be simpler, but this
665 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
666 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
667 // well-behaved data // streams (event statistics, profile data, etc).
668 //
669 // Deleted files are replaced with zero-length tombstones to mark what
670 // was lost. Tombstones are expunged by age (see above).
671
672 if (mAllFiles.blocks > mCachedQuotaBlocks) {
673 Log.i(TAG, "Usage (" + mAllFiles.blocks + ") > Quota (" + mCachedQuotaBlocks + ")");
674
675 // Find a fair share amount of space to limit each tag
676 int unsqueezed = mAllFiles.blocks, squeezed = 0;
677 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
678 for (FileList tag : tags) {
679 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
680 break;
681 }
682 unsqueezed -= tag.blocks;
683 squeezed++;
684 }
685 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
686
687 // Remove old items from each tag until it meets the per-tag quota.
688 for (FileList tag : tags) {
689 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
690 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
691 EntryFile entry = tag.contents.first();
692 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
693 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
694
695 try {
696 if (entry.file != null) entry.file.delete();
697 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
698 } catch (IOException e) {
699 Log.e(TAG, "Can't write tombstone file", e);
700 }
701 }
702 }
703 }
704
705 return mCachedQuotaBlocks * mBlockSize;
706 }
707}