blob: 3a4c3acc1d974eaf452e6612a53e571ecdcf22d3 [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
247 public synchronized DropBoxEntry getNextEntry(long millis) {
248 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
260 for (EntryFile entry : mAllFiles.contents.tailSet(new EntryFile(millis + 1))) {
261 if (entry.tag == null) continue;
262 try {
263 File file = (entry.flags & DropBoxEntry.IS_EMPTY) != 0 ? null : entry.file;
264 return new DropBoxEntry(entry.tag, entry.timestampMillis, file, entry.flags);
265 } catch (IOException e) {
266 Log.e(TAG, "Can't read: " + entry.file, e);
267 // Continue to next file
268 }
269 }
270
271 return null;
272 }
273
274 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
275 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
276 != PackageManager.PERMISSION_GRANTED) {
277 pw.println("Permission Denial: Can't dump DropBoxService");
278 return;
279 }
280
281 try {
282 init();
283 } catch (IOException e) {
284 pw.println("Can't initialize: " + e);
285 Log.e(TAG, "Can't init", e);
286 return;
287 }
288
289 boolean doPrint = false, doFile = false;
290 ArrayList<String> searchArgs = new ArrayList<String>();
291 for (int i = 0; args != null && i < args.length; i++) {
292 if (args[i].equals("-p") || args[i].equals("--print")) {
293 doPrint = true;
294 } else if (args[i].equals("-f") || args[i].equals("--file")) {
295 doFile = true;
296 } else if (args[i].startsWith("-")) {
297 pw.print("Unknown argument: ");
298 pw.println(args[i]);
299 } else {
300 searchArgs.add(args[i]);
301 }
302 }
303
304 pw.format("Drop box contents: %d entries", mAllFiles.contents.size());
305 pw.println();
306
307 if (!searchArgs.isEmpty()) {
308 pw.print("Searching for:");
309 for (String a : searchArgs) pw.format(" %s", a);
310 pw.println();
311 }
312
313 int numFound = 0;
314 pw.println();
315 for (EntryFile entry : mAllFiles.contents) {
316 String date = new Formatter().format("%s.%03d",
317 DateFormat.format("yyyy-MM-dd kk:mm:ss", entry.timestampMillis),
318 entry.timestampMillis % 1000).toString();
319
320 boolean match = true;
321 for (String a: searchArgs) match = match && (date.contains(a) || a.equals(entry.tag));
322 if (!match) continue;
323
324 numFound++;
325 pw.print(date);
326 pw.print(" ");
327 pw.print(entry.tag == null ? "(no tag)" : entry.tag);
328 if (entry.file == null) {
329 pw.println(" (no file)");
330 continue;
331 } else if ((entry.flags & DropBoxEntry.IS_EMPTY) != 0) {
332 pw.println(" (contents lost)");
333 continue;
334 } else {
335 pw.print((entry.flags & DropBoxEntry.IS_GZIPPED) != 0 ? " (comopressed " : " (");
336 pw.print((entry.flags & DropBoxEntry.IS_TEXT) != 0 ? "text" : "data");
337 pw.format(", %d bytes)", entry.file.length());
338 pw.println();
339 }
340
341 if (doFile || (doPrint && (entry.flags & DropBoxEntry.IS_TEXT) == 0)) {
342 if (!doPrint) pw.print(" ");
343 pw.println(entry.file.getPath());
344 }
345
346 if ((entry.flags & DropBoxEntry.IS_TEXT) != 0 && (doPrint || !doFile)) {
347 DropBoxEntry dbe = null;
348 try {
349 dbe = new DropBoxEntry(
350 entry.tag, entry.timestampMillis, entry.file, entry.flags);
351
352 if (doPrint) {
353 InputStreamReader r = new InputStreamReader(dbe.getInputStream());
354 char[] buf = new char[4096];
355 boolean newline = false;
356 for (;;) {
357 int n = r.read(buf);
358 if (n <= 0) break;
359 pw.write(buf, 0, n);
360 newline = (buf[n - 1] == '\n');
361 }
362 if (!newline) pw.println();
363 } else {
364 String text = dbe.getText(70);
365 boolean truncated = (text.length() == 70);
366 pw.print(" ");
367 pw.print(text.trim().replace('\n', '/'));
368 if (truncated) pw.print(" ...");
369 pw.println();
370 }
371 } catch (IOException e) {
372 pw.print("*** ");
373 pw.println(e.toString());
374 Log.e(TAG, "Can't read: " + entry.file, e);
375 } finally {
376 if (dbe != null) dbe.close();
377 }
378 }
379
380 if (doPrint) pw.println();
381 }
382
383 if (numFound == 0) pw.println("(No entries found.)");
384
385 if (args == null || args.length == 0) {
386 if (!doPrint) pw.println();
387 pw.println("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS.SSS] [tag]");
388 }
389 }
390
391 ///////////////////////////////////////////////////////////////////////////
392
393 /** Chronologically sorted list of {@link #EntryFile} */
394 private static final class FileList implements Comparable<FileList> {
395 public int blocks = 0;
396 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
397
398 /** Sorts bigger FileList instances before smaller ones. */
399 public final int compareTo(FileList o) {
400 if (blocks != o.blocks) return o.blocks - blocks;
401 if (this == o) return 0;
402 if (hashCode() < o.hashCode()) return -1;
403 if (hashCode() > o.hashCode()) return 1;
404 return 0;
405 }
406 }
407
408 /** Metadata describing an on-disk log file. */
409 private static final class EntryFile implements Comparable<EntryFile> {
410 public final String tag;
411 public final long timestampMillis;
412 public final int flags;
413 public final File file;
414 public final int blocks;
415
416 /** Sorts earlier EntryFile instances before later ones. */
417 public final int compareTo(EntryFile o) {
418 if (timestampMillis < o.timestampMillis) return -1;
419 if (timestampMillis > o.timestampMillis) return 1;
420 if (file != null && o.file != null) return file.compareTo(o.file);
421 if (o.file != null) return -1;
422 if (file != null) return 1;
423 if (this == o) return 0;
424 if (hashCode() < o.hashCode()) return -1;
425 if (hashCode() > o.hashCode()) return 1;
426 return 0;
427 }
428
429 /**
430 * Moves an existing temporary file to a new log filename.
431 * @param temp file to rename
432 * @param dir to store file in
433 * @param tag to use for new log file name
434 * @param timestampMillis of log entry
435 * @param flags for the entry data (from {@link DropBoxEntry})
436 * @param blockSize to use for space accounting
437 * @throws IOException if the file can't be moved
438 */
439 public EntryFile(File temp, File dir, String tag,long timestampMillis,
440 int flags, int blockSize) throws IOException {
441 if ((flags & DropBoxEntry.IS_EMPTY) != 0) throw new IllegalArgumentException();
442
443 this.tag = tag;
444 this.timestampMillis = timestampMillis;
445 this.flags = flags;
446 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
447 ((flags & DropBoxEntry.IS_TEXT) != 0 ? ".txt" : ".dat") +
448 ((flags & DropBoxEntry.IS_GZIPPED) != 0 ? ".gz" : ""));
449
450 if (!temp.renameTo(this.file)) {
451 throw new IOException("Can't rename " + temp + " to " + this.file);
452 }
453 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
454 }
455
456 /**
457 * Creates a zero-length tombstone for a file whose contents were lost.
458 * @param dir to store file in
459 * @param tag to use for new log file name
460 * @param timestampMillis of log entry
461 * @throws IOException if the file can't be created.
462 */
463 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
464 this.tag = tag;
465 this.timestampMillis = timestampMillis;
466 this.flags = DropBoxEntry.IS_EMPTY;
467 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
468 this.blocks = 0;
469 new FileOutputStream(this.file).close();
470 }
471
472 /**
473 * Extracts metadata from an existing on-disk log filename.
474 * @param file name of existing log file
475 * @param blockSize to use for space accounting
476 */
477 public EntryFile(File file, int blockSize) {
478 this.file = file;
479 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
480
481 String name = file.getName();
482 int at = name.lastIndexOf('@');
483 if (at < 0) {
484 this.tag = null;
485 this.timestampMillis = 0;
486 this.flags = DropBoxEntry.IS_EMPTY;
487 return;
488 }
489
490 int flags = 0;
491 this.tag = Uri.decode(name.substring(0, at));
492 if (name.endsWith(".gz")) {
493 flags |= DropBoxEntry.IS_GZIPPED;
494 name = name.substring(0, name.length() - 3);
495 }
496 if (name.endsWith(".lost")) {
497 flags |= DropBoxEntry.IS_EMPTY;
498 name = name.substring(at + 1, name.length() - 5);
499 } else if (name.endsWith(".txt")) {
500 flags |= DropBoxEntry.IS_TEXT;
501 name = name.substring(at + 1, name.length() - 4);
502 } else if (name.endsWith(".dat")) {
503 name = name.substring(at + 1, name.length() - 4);
504 } else {
505 this.flags = DropBoxEntry.IS_EMPTY;
506 this.timestampMillis = 0;
507 return;
508 }
509 this.flags = flags;
510
511 long millis;
512 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
513 this.timestampMillis = millis;
514 }
515
516 /**
517 * Creates a EntryFile object with only a timestamp for comparison purposes.
518 * @param timestampMillis to compare with.
519 */
520 public EntryFile(long millis) {
521 this.tag = null;
522 this.timestampMillis = millis;
523 this.flags = DropBoxEntry.IS_EMPTY;
524 this.file = null;
525 this.blocks = 0;
526 }
527 }
528
529 ///////////////////////////////////////////////////////////////////////////
530
531 /** If never run before, scans disk contents to build in-memory tracking data. */
532 private synchronized void init() throws IOException {
533 if (mStatFs == null) {
534 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
535 throw new IOException("Can't mkdir: " + mDropBoxDir);
536 }
537 try {
538 mStatFs = new StatFs(mDropBoxDir.getPath());
539 mBlockSize = mStatFs.getBlockSize();
540 } catch (IllegalArgumentException e) { // StatFs throws this on error
541 throw new IOException("Can't statfs: " + mDropBoxDir);
542 }
543 }
544
545 if (mAllFiles == null) {
546 File[] files = mDropBoxDir.listFiles();
547 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
548
549 mAllFiles = new FileList();
550 mFilesByTag = new HashMap<String, FileList>();
551
552 // Scan pre-existing files.
553 for (File file : files) {
554 if (file.getName().endsWith(".tmp")) {
555 Log.i(TAG, "Cleaning temp file: " + file);
556 file.delete();
557 continue;
558 }
559
560 EntryFile entry = new EntryFile(file, mBlockSize);
561 if (entry.tag == null) {
562 Log.w(TAG, "Unrecognized file: " + file);
563 continue;
564 } else if (entry.timestampMillis == 0) {
565 Log.w(TAG, "Invalid filename: " + file);
566 file.delete();
567 continue;
568 }
569
570 enrollEntry(entry);
571 }
572 }
573 }
574
575 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
576 private synchronized void enrollEntry(EntryFile entry) {
577 mAllFiles.contents.add(entry);
578 mAllFiles.blocks += entry.blocks;
579
580 // mFilesByTag is used for trimming, so don't list empty files.
581 // (Zero-length/lost files are trimmed by date from mAllFiles.)
582
583 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
584 FileList tagFiles = mFilesByTag.get(entry.tag);
585 if (tagFiles == null) {
586 tagFiles = new FileList();
587 mFilesByTag.put(entry.tag, tagFiles);
588 }
589 tagFiles.contents.add(entry);
590 tagFiles.blocks += entry.blocks;
591 }
592 }
593
594 /** Moves a temporary file to a final log filename and enrolls it. */
595 private synchronized void createEntry(File temp, String tag, int flags) throws IOException {
596 long t = System.currentTimeMillis();
597
598 // Require each entry to have a unique timestamp; if there are entries
599 // >10sec in the future (due to clock skew), drag them back to avoid
600 // keeping them around forever.
601
602 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
603 EntryFile[] future = null;
604 if (!tail.isEmpty()) {
605 future = tail.toArray(new EntryFile[tail.size()]);
606 tail.clear(); // Remove from mAllFiles
607 }
608
609 if (!mAllFiles.contents.isEmpty()) {
610 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
611 }
612
613 if (future != null) {
614 for (EntryFile late : future) {
615 mAllFiles.blocks -= late.blocks;
616 FileList tagFiles = mFilesByTag.get(late.tag);
617 if (tagFiles.contents.remove(late)) tagFiles.blocks -= late.blocks;
618 if ((late.flags & DropBoxEntry.IS_EMPTY) == 0) {
619 enrollEntry(new EntryFile(
620 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
621 } else {
622 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
623 }
624 }
625 }
626
627 if (temp == null) {
628 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
629 } else {
630 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
631 }
632 }
633
634 /**
635 * Trims the files on disk to make sure they aren't using too much space.
636 * @return the overall quota for storage (in bytes)
637 */
638 private synchronized long trimToFit() {
639 // Expunge aged items (including tombstones marking deleted data).
640
641 int ageSeconds = Settings.Gservices.getInt(mContentResolver,
642 Settings.Gservices.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
643 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
644 while (!mAllFiles.contents.isEmpty()) {
645 EntryFile entry = mAllFiles.contents.first();
646 if (entry.timestampMillis > cutoffMillis) break;
647
648 FileList tag = mFilesByTag.get(entry.tag);
649 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
650 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
651 if (entry.file != null) entry.file.delete();
652 }
653
654 // Compute overall quota (a fraction of available free space) in blocks.
655 // The quota changes dynamically based on the amount of free space;
656 // that way when lots of data is available we can use it, but we'll get
657 // out of the way if storage starts getting tight.
658
659 long uptimeMillis = SystemClock.uptimeMillis();
660 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
661 int quotaPercent = Settings.Gservices.getInt(mContentResolver,
662 Settings.Gservices.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
663 int reservePercent = Settings.Gservices.getInt(mContentResolver,
664 Settings.Gservices.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
665 int quotaKb = Settings.Gservices.getInt(mContentResolver,
666 Settings.Gservices.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
667
668 mStatFs.restat(mDropBoxDir.getPath());
669 int available = mStatFs.getAvailableBlocks();
670 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
671 int maximum = quotaKb * 1024 / mBlockSize;
672 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
673 mCachedQuotaUptimeMillis = uptimeMillis;
674 }
675
676 // If we're using too much space, delete old items to make room.
677 //
678 // We trim each tag independently (this is why we keep per-tag lists).
679 // Space is "fairly" shared between tags -- they are all squeezed
680 // equally until enough space is reclaimed.
681 //
682 // A single circular buffer (a la logcat) would be simpler, but this
683 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
684 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
685 // well-behaved data // streams (event statistics, profile data, etc).
686 //
687 // Deleted files are replaced with zero-length tombstones to mark what
688 // was lost. Tombstones are expunged by age (see above).
689
690 if (mAllFiles.blocks > mCachedQuotaBlocks) {
691 Log.i(TAG, "Usage (" + mAllFiles.blocks + ") > Quota (" + mCachedQuotaBlocks + ")");
692
693 // Find a fair share amount of space to limit each tag
694 int unsqueezed = mAllFiles.blocks, squeezed = 0;
695 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
696 for (FileList tag : tags) {
697 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
698 break;
699 }
700 unsqueezed -= tag.blocks;
701 squeezed++;
702 }
703 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
704
705 // Remove old items from each tag until it meets the per-tag quota.
706 for (FileList tag : tags) {
707 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
708 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
709 EntryFile entry = tag.contents.first();
710 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
711 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
712
713 try {
714 if (entry.file != null) entry.file.delete();
715 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
716 } catch (IOException e) {
717 Log.e(TAG, "Can't write tombstone file", e);
718 }
719 }
720 }
721 }
722
723 return mCachedQuotaBlocks * mBlockSize;
724 }
725}