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