blob: 48d455d3ca19ae057886b206e1f733c7e40f51a3 [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;
25import android.net.Uri;
Dan Egnorf18a01c2009-11-12 11:32:50 -080026import android.os.DropBoxManager;
Dan Egnor4410ec82009-09-11 16:40:01 -070027import android.os.ParcelFileDescriptor;
28import android.os.StatFs;
29import android.os.SystemClock;
30import android.provider.Settings;
31import android.text.format.DateFormat;
32import android.util.Log;
33
Dan Egnorf18a01c2009-11-12 11:32:50 -080034import com.android.internal.os.IDropBoxManagerService;
Dan Egnor95240272009-10-27 18:23:39 -070035
Dan Egnor4410ec82009-09-11 16:40:01 -070036import java.io.File;
37import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070038import java.io.FileOutputStream;
39import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070040import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070041import java.io.InputStreamReader;
42import java.io.OutputStream;
43import java.io.OutputStreamWriter;
44import java.io.PrintWriter;
45import java.io.UnsupportedEncodingException;
46import java.util.ArrayList;
47import java.util.Comparator;
48import java.util.Formatter;
49import java.util.HashMap;
50import java.util.Iterator;
51import java.util.Map;
52import java.util.SortedSet;
53import java.util.TreeSet;
54import java.util.zip.GZIPOutputStream;
55
56/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080057 * Implementation of {@link IDropBoxManagerService} using the filesystem.
58 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070059 *
60 * {@hide}
61 */
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
70 // TODO: This implementation currently uses one file per entry, which is
71 // inefficient for smallish entries -- consider using a single queue file
72 // per tag (or even globally) instead.
73
74 // The cached context and derived objects
75
76 private final Context mContext;
77 private final ContentResolver mContentResolver;
78 private final File mDropBoxDir;
79
80 // Accounting of all currently written log files (set in init()).
81
82 private FileList mAllFiles = null;
83 private HashMap<String, FileList> mFilesByTag = null;
84
85 // Various bits of disk information
86
87 private StatFs mStatFs = null;
88 private int mBlockSize = 0;
89 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
90 private long mCachedQuotaUptimeMillis = 0;
91
92 // Ensure that all log entries have a unique timestamp
93 private long mLastTimestamp = 0;
94
95 /** Receives events that might indicate a need to clean up files. */
96 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
97 @Override
98 public void onReceive(Context context, Intent intent) {
99 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
100 try {
101 init();
102 trimToFit();
103 } catch (IOException e) {
104 Log.e(TAG, "Can't init", e);
105 }
106 }
107 };
108
109 /**
110 * Creates an instance of managed drop box storage. Normally there is one of these
111 * run by the system, but others can be created for testing and other purposes.
112 *
113 * @param context to use for receiving free space & gservices intents
114 * @param path to store drop box entries in
115 */
Dan Egnorf18a01c2009-11-12 11:32:50 -0800116 public DropBoxManagerService(Context context, File path) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700117 mDropBoxDir = path;
118
119 // Set up intent receivers
120 mContext = context;
121 mContentResolver = context.getContentResolver();
122 context.registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW));
123 context.registerReceiver(mReceiver, new IntentFilter(Settings.Gservices.CHANGED_ACTION));
124
125 // The real work gets done lazily in init() -- that way service creation always
126 // succeeds, and things like disk problems cause individual method failures.
127 }
128
129 /** Unregisters broadcast receivers and any other hooks -- for test instances */
130 public void stop() {
131 mContext.unregisterReceiver(mReceiver);
132 }
133
Dan Egnorf18a01c2009-11-12 11:32:50 -0800134 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700135 File temp = null;
136 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700137 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700138 try {
Dan Egnor95240272009-10-27 18:23:39 -0700139 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800140 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700141
142 init();
143 if (!isTagEnabled(tag)) return;
144 long max = trimToFit();
145 long lastTrim = System.currentTimeMillis();
146
147 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700148 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700149
150 // First, accumulate up to one block worth of data in memory before
151 // deciding whether to compress the data or not.
152
153 int read = 0;
154 while (read < buffer.length) {
155 int n = input.read(buffer, read, buffer.length - read);
156 if (n <= 0) break;
157 read += n;
158 }
159
160 // If we have at least one block, compress it -- otherwise, just write
161 // the data in uncompressed form.
162
163 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
164 output = new FileOutputStream(temp);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800165 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700166 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800167 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700168 }
169
170 do {
171 output.write(buffer, 0, read);
172
173 long now = System.currentTimeMillis();
174 if (now - lastTrim > 30 * 1000) {
175 max = trimToFit(); // In case data dribbles in slowly
176 lastTrim = now;
177 }
178
179 read = input.read(buffer);
180 if (read <= 0) {
181 output.close(); // Get a final size measurement
182 output = null;
183 } else {
184 output.flush(); // So the size measurement is pseudo-reasonable
185 }
186
187 long len = temp.length();
188 if (len > max) {
189 Log.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
190 temp.delete();
191 temp = null; // Pass temp = null to createEntry() to leave a tombstone
192 break;
193 }
194 } while (read > 0);
195
196 createEntry(temp, tag, flags);
197 temp = null;
198 } catch (IOException e) {
199 Log.e(TAG, "Can't write: " + tag, e);
200 } finally {
201 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700202 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700203 if (temp != null) temp.delete();
204 }
205 }
206
207 public boolean isTagEnabled(String tag) {
208 return !"disabled".equals(Settings.Gservices.getString(
209 mContentResolver, Settings.Gservices.DROPBOX_TAG_PREFIX + tag));
210 }
211
Dan Egnorf18a01c2009-11-12 11:32:50 -0800212 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700213 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
214 != PackageManager.PERMISSION_GRANTED) {
215 throw new SecurityException("READ_LOGS permission required");
216 }
217
218 try {
219 init();
220 } catch (IOException e) {
221 Log.e(TAG, "Can't init", e);
222 return null;
223 }
224
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700225 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
226 if (list == null) return null;
227
228 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700229 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800230 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
231 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700232 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700233 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800234 return new DropBoxManager.Entry(
235 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700236 } catch (IOException e) {
237 Log.e(TAG, "Can't read: " + entry.file, e);
238 // Continue to next file
239 }
240 }
241
242 return null;
243 }
244
245 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
246 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
247 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800248 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700249 return;
250 }
251
252 try {
253 init();
254 } catch (IOException e) {
255 pw.println("Can't initialize: " + e);
256 Log.e(TAG, "Can't init", e);
257 return;
258 }
259
260 boolean doPrint = false, doFile = false;
261 ArrayList<String> searchArgs = new ArrayList<String>();
262 for (int i = 0; args != null && i < args.length; i++) {
263 if (args[i].equals("-p") || args[i].equals("--print")) {
264 doPrint = true;
265 } else if (args[i].equals("-f") || args[i].equals("--file")) {
266 doFile = true;
267 } else if (args[i].startsWith("-")) {
268 pw.print("Unknown argument: ");
269 pw.println(args[i]);
270 } else {
271 searchArgs.add(args[i]);
272 }
273 }
274
275 pw.format("Drop box contents: %d entries", mAllFiles.contents.size());
276 pw.println();
277
278 if (!searchArgs.isEmpty()) {
279 pw.print("Searching for:");
280 for (String a : searchArgs) pw.format(" %s", a);
281 pw.println();
282 }
283
284 int numFound = 0;
285 pw.println();
286 for (EntryFile entry : mAllFiles.contents) {
287 String date = new Formatter().format("%s.%03d",
288 DateFormat.format("yyyy-MM-dd kk:mm:ss", entry.timestampMillis),
289 entry.timestampMillis % 1000).toString();
290
291 boolean match = true;
292 for (String a: searchArgs) match = match && (date.contains(a) || a.equals(entry.tag));
293 if (!match) continue;
294
295 numFound++;
296 pw.print(date);
297 pw.print(" ");
298 pw.print(entry.tag == null ? "(no tag)" : entry.tag);
299 if (entry.file == null) {
300 pw.println(" (no file)");
301 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800302 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700303 pw.println(" (contents lost)");
304 continue;
305 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800306 pw.print((entry.flags & DropBoxManager.IS_GZIPPED) != 0 ? " (comopressed " : " (");
307 pw.print((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
Dan Egnor4410ec82009-09-11 16:40:01 -0700308 pw.format(", %d bytes)", entry.file.length());
309 pw.println();
310 }
311
Dan Egnorf18a01c2009-11-12 11:32:50 -0800312 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700313 if (!doPrint) pw.print(" ");
314 pw.println(entry.file.getPath());
315 }
316
Dan Egnorf18a01c2009-11-12 11:32:50 -0800317 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
318 DropBoxManager.Entry dbe = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700319 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800320 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700321 entry.tag, entry.timestampMillis, entry.file, entry.flags);
322
323 if (doPrint) {
324 InputStreamReader r = new InputStreamReader(dbe.getInputStream());
325 char[] buf = new char[4096];
326 boolean newline = false;
327 for (;;) {
328 int n = r.read(buf);
329 if (n <= 0) break;
330 pw.write(buf, 0, n);
331 newline = (buf[n - 1] == '\n');
332 }
333 if (!newline) pw.println();
334 } else {
335 String text = dbe.getText(70);
336 boolean truncated = (text.length() == 70);
337 pw.print(" ");
338 pw.print(text.trim().replace('\n', '/'));
339 if (truncated) pw.print(" ...");
340 pw.println();
341 }
342 } catch (IOException e) {
343 pw.print("*** ");
344 pw.println(e.toString());
345 Log.e(TAG, "Can't read: " + entry.file, e);
346 } finally {
347 if (dbe != null) dbe.close();
348 }
349 }
350
351 if (doPrint) pw.println();
352 }
353
354 if (numFound == 0) pw.println("(No entries found.)");
355
356 if (args == null || args.length == 0) {
357 if (!doPrint) pw.println();
358 pw.println("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS.SSS] [tag]");
359 }
360 }
361
362 ///////////////////////////////////////////////////////////////////////////
363
364 /** Chronologically sorted list of {@link #EntryFile} */
365 private static final class FileList implements Comparable<FileList> {
366 public int blocks = 0;
367 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
368
369 /** Sorts bigger FileList instances before smaller ones. */
370 public final int compareTo(FileList o) {
371 if (blocks != o.blocks) return o.blocks - blocks;
372 if (this == o) return 0;
373 if (hashCode() < o.hashCode()) return -1;
374 if (hashCode() > o.hashCode()) return 1;
375 return 0;
376 }
377 }
378
379 /** Metadata describing an on-disk log file. */
380 private static final class EntryFile implements Comparable<EntryFile> {
381 public final String tag;
382 public final long timestampMillis;
383 public final int flags;
384 public final File file;
385 public final int blocks;
386
387 /** Sorts earlier EntryFile instances before later ones. */
388 public final int compareTo(EntryFile o) {
389 if (timestampMillis < o.timestampMillis) return -1;
390 if (timestampMillis > o.timestampMillis) return 1;
391 if (file != null && o.file != null) return file.compareTo(o.file);
392 if (o.file != null) return -1;
393 if (file != null) return 1;
394 if (this == o) return 0;
395 if (hashCode() < o.hashCode()) return -1;
396 if (hashCode() > o.hashCode()) return 1;
397 return 0;
398 }
399
400 /**
401 * Moves an existing temporary file to a new log filename.
402 * @param temp file to rename
403 * @param dir to store file in
404 * @param tag to use for new log file name
405 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700406 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700407 * @param blockSize to use for space accounting
408 * @throws IOException if the file can't be moved
409 */
410 public EntryFile(File temp, File dir, String tag,long timestampMillis,
411 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800412 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700413
414 this.tag = tag;
415 this.timestampMillis = timestampMillis;
416 this.flags = flags;
417 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800418 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
419 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700420
421 if (!temp.renameTo(this.file)) {
422 throw new IOException("Can't rename " + temp + " to " + this.file);
423 }
424 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
425 }
426
427 /**
428 * Creates a zero-length tombstone for a file whose contents were lost.
429 * @param dir to store file in
430 * @param tag to use for new log file name
431 * @param timestampMillis of log entry
432 * @throws IOException if the file can't be created.
433 */
434 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
435 this.tag = tag;
436 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800437 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700438 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
439 this.blocks = 0;
440 new FileOutputStream(this.file).close();
441 }
442
443 /**
444 * Extracts metadata from an existing on-disk log filename.
445 * @param file name of existing log file
446 * @param blockSize to use for space accounting
447 */
448 public EntryFile(File file, int blockSize) {
449 this.file = file;
450 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
451
452 String name = file.getName();
453 int at = name.lastIndexOf('@');
454 if (at < 0) {
455 this.tag = null;
456 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800457 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700458 return;
459 }
460
461 int flags = 0;
462 this.tag = Uri.decode(name.substring(0, at));
463 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800464 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700465 name = name.substring(0, name.length() - 3);
466 }
467 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800468 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700469 name = name.substring(at + 1, name.length() - 5);
470 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800471 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700472 name = name.substring(at + 1, name.length() - 4);
473 } else if (name.endsWith(".dat")) {
474 name = name.substring(at + 1, name.length() - 4);
475 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800476 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700477 this.timestampMillis = 0;
478 return;
479 }
480 this.flags = flags;
481
482 long millis;
483 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
484 this.timestampMillis = millis;
485 }
486
487 /**
488 * Creates a EntryFile object with only a timestamp for comparison purposes.
489 * @param timestampMillis to compare with.
490 */
491 public EntryFile(long millis) {
492 this.tag = null;
493 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800494 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700495 this.file = null;
496 this.blocks = 0;
497 }
498 }
499
500 ///////////////////////////////////////////////////////////////////////////
501
502 /** If never run before, scans disk contents to build in-memory tracking data. */
503 private synchronized void init() throws IOException {
504 if (mStatFs == null) {
505 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
506 throw new IOException("Can't mkdir: " + mDropBoxDir);
507 }
508 try {
509 mStatFs = new StatFs(mDropBoxDir.getPath());
510 mBlockSize = mStatFs.getBlockSize();
511 } catch (IllegalArgumentException e) { // StatFs throws this on error
512 throw new IOException("Can't statfs: " + mDropBoxDir);
513 }
514 }
515
516 if (mAllFiles == null) {
517 File[] files = mDropBoxDir.listFiles();
518 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
519
520 mAllFiles = new FileList();
521 mFilesByTag = new HashMap<String, FileList>();
522
523 // Scan pre-existing files.
524 for (File file : files) {
525 if (file.getName().endsWith(".tmp")) {
526 Log.i(TAG, "Cleaning temp file: " + file);
527 file.delete();
528 continue;
529 }
530
531 EntryFile entry = new EntryFile(file, mBlockSize);
532 if (entry.tag == null) {
533 Log.w(TAG, "Unrecognized file: " + file);
534 continue;
535 } else if (entry.timestampMillis == 0) {
536 Log.w(TAG, "Invalid filename: " + file);
537 file.delete();
538 continue;
539 }
540
541 enrollEntry(entry);
542 }
543 }
544 }
545
546 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
547 private synchronized void enrollEntry(EntryFile entry) {
548 mAllFiles.contents.add(entry);
549 mAllFiles.blocks += entry.blocks;
550
551 // mFilesByTag is used for trimming, so don't list empty files.
552 // (Zero-length/lost files are trimmed by date from mAllFiles.)
553
554 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
555 FileList tagFiles = mFilesByTag.get(entry.tag);
556 if (tagFiles == null) {
557 tagFiles = new FileList();
558 mFilesByTag.put(entry.tag, tagFiles);
559 }
560 tagFiles.contents.add(entry);
561 tagFiles.blocks += entry.blocks;
562 }
563 }
564
565 /** Moves a temporary file to a final log filename and enrolls it. */
566 private synchronized void createEntry(File temp, String tag, int flags) throws IOException {
567 long t = System.currentTimeMillis();
568
569 // Require each entry to have a unique timestamp; if there are entries
570 // >10sec in the future (due to clock skew), drag them back to avoid
571 // keeping them around forever.
572
573 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
574 EntryFile[] future = null;
575 if (!tail.isEmpty()) {
576 future = tail.toArray(new EntryFile[tail.size()]);
577 tail.clear(); // Remove from mAllFiles
578 }
579
580 if (!mAllFiles.contents.isEmpty()) {
581 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
582 }
583
584 if (future != null) {
585 for (EntryFile late : future) {
586 mAllFiles.blocks -= late.blocks;
587 FileList tagFiles = mFilesByTag.get(late.tag);
588 if (tagFiles.contents.remove(late)) tagFiles.blocks -= late.blocks;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800589 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700590 enrollEntry(new EntryFile(
591 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
592 } else {
593 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
594 }
595 }
596 }
597
598 if (temp == null) {
599 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
600 } else {
601 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
602 }
603 }
604
605 /**
606 * Trims the files on disk to make sure they aren't using too much space.
607 * @return the overall quota for storage (in bytes)
608 */
609 private synchronized long trimToFit() {
610 // Expunge aged items (including tombstones marking deleted data).
611
612 int ageSeconds = Settings.Gservices.getInt(mContentResolver,
613 Settings.Gservices.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
614 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
615 while (!mAllFiles.contents.isEmpty()) {
616 EntryFile entry = mAllFiles.contents.first();
617 if (entry.timestampMillis > cutoffMillis) break;
618
619 FileList tag = mFilesByTag.get(entry.tag);
620 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
621 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
622 if (entry.file != null) entry.file.delete();
623 }
624
625 // Compute overall quota (a fraction of available free space) in blocks.
626 // The quota changes dynamically based on the amount of free space;
627 // that way when lots of data is available we can use it, but we'll get
628 // out of the way if storage starts getting tight.
629
630 long uptimeMillis = SystemClock.uptimeMillis();
631 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
632 int quotaPercent = Settings.Gservices.getInt(mContentResolver,
633 Settings.Gservices.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
634 int reservePercent = Settings.Gservices.getInt(mContentResolver,
635 Settings.Gservices.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
636 int quotaKb = Settings.Gservices.getInt(mContentResolver,
637 Settings.Gservices.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
638
639 mStatFs.restat(mDropBoxDir.getPath());
640 int available = mStatFs.getAvailableBlocks();
641 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
642 int maximum = quotaKb * 1024 / mBlockSize;
643 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
644 mCachedQuotaUptimeMillis = uptimeMillis;
645 }
646
647 // If we're using too much space, delete old items to make room.
648 //
649 // We trim each tag independently (this is why we keep per-tag lists).
650 // Space is "fairly" shared between tags -- they are all squeezed
651 // equally until enough space is reclaimed.
652 //
653 // A single circular buffer (a la logcat) would be simpler, but this
654 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
655 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
656 // well-behaved data // streams (event statistics, profile data, etc).
657 //
658 // Deleted files are replaced with zero-length tombstones to mark what
659 // was lost. Tombstones are expunged by age (see above).
660
661 if (mAllFiles.blocks > mCachedQuotaBlocks) {
662 Log.i(TAG, "Usage (" + mAllFiles.blocks + ") > Quota (" + mCachedQuotaBlocks + ")");
663
664 // Find a fair share amount of space to limit each tag
665 int unsqueezed = mAllFiles.blocks, squeezed = 0;
666 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
667 for (FileList tag : tags) {
668 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
669 break;
670 }
671 unsqueezed -= tag.blocks;
672 squeezed++;
673 }
674 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
675
676 // Remove old items from each tag until it meets the per-tag quota.
677 for (FileList tag : tags) {
678 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
679 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
680 EntryFile entry = tag.contents.first();
681 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
682 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
683
684 try {
685 if (entry.file != null) entry.file.delete();
686 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
687 } catch (IOException e) {
688 Log.e(TAG, "Can't write tombstone file", e);
689 }
690 }
691 }
692 }
693
694 return mCachedQuotaBlocks * mBlockSize;
695 }
696}