Home | History | Annotate | Download | only in server
      1 /*
      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 
     17 package com.android.server;
     18 
     19 import android.content.BroadcastReceiver;
     20 import android.content.ContentResolver;
     21 import android.content.Context;
     22 import android.content.Intent;
     23 import android.content.IntentFilter;
     24 import android.content.pm.PackageManager;
     25 import android.database.ContentObserver;
     26 import android.net.Uri;
     27 import android.os.Binder;
     28 import android.os.Debug;
     29 import android.os.DropBoxManager;
     30 import android.os.FileUtils;
     31 import android.os.Handler;
     32 import android.os.Message;
     33 import android.os.StatFs;
     34 import android.os.SystemClock;
     35 import android.os.UserHandle;
     36 import android.provider.Settings;
     37 import android.text.format.Time;
     38 import android.util.Slog;
     39 
     40 import libcore.io.IoUtils;
     41 
     42 import com.android.internal.os.IDropBoxManagerService;
     43 import com.android.internal.util.DumpUtils;
     44 
     45 import java.io.BufferedOutputStream;
     46 import java.io.File;
     47 import java.io.FileDescriptor;
     48 import java.io.FileOutputStream;
     49 import java.io.IOException;
     50 import java.io.InputStream;
     51 import java.io.InputStreamReader;
     52 import java.io.OutputStream;
     53 import java.io.PrintWriter;
     54 import java.util.ArrayList;
     55 import java.util.HashMap;
     56 import java.util.SortedSet;
     57 import java.util.TreeSet;
     58 import java.util.zip.GZIPOutputStream;
     59 
     60 /**
     61  * Implementation of {@link IDropBoxManagerService} using the filesystem.
     62  * Clients use {@link DropBoxManager} to access this service.
     63  */
     64 public final class DropBoxManagerService extends SystemService {
     65     private static final String TAG = "DropBoxManagerService";
     66     private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
     67     private static final int DEFAULT_MAX_FILES = 1000;
     68     private static final int DEFAULT_QUOTA_KB = 5 * 1024;
     69     private static final int DEFAULT_QUOTA_PERCENT = 10;
     70     private static final int DEFAULT_RESERVE_PERCENT = 10;
     71     private static final int QUOTA_RESCAN_MILLIS = 5000;
     72 
     73     // mHandler 'what' value.
     74     private static final int MSG_SEND_BROADCAST = 1;
     75 
     76     private static final boolean PROFILE_DUMP = false;
     77 
     78     // TODO: This implementation currently uses one file per entry, which is
     79     // inefficient for smallish entries -- consider using a single queue file
     80     // per tag (or even globally) instead.
     81 
     82     // The cached context and derived objects
     83 
     84     private final ContentResolver mContentResolver;
     85     private final File mDropBoxDir;
     86 
     87     // Accounting of all currently written log files (set in init()).
     88 
     89     private FileList mAllFiles = null;
     90     private HashMap<String, FileList> mFilesByTag = null;
     91 
     92     // Various bits of disk information
     93 
     94     private StatFs mStatFs = null;
     95     private int mBlockSize = 0;
     96     private int mCachedQuotaBlocks = 0;  // Space we can use: computed from free space, etc.
     97     private long mCachedQuotaUptimeMillis = 0;
     98 
     99     private volatile boolean mBooted = false;
    100 
    101     // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
    102     private final Handler mHandler;
    103 
    104     /** Receives events that might indicate a need to clean up files. */
    105     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    106         @Override
    107         public void onReceive(Context context, Intent intent) {
    108             // For ACTION_DEVICE_STORAGE_LOW:
    109             mCachedQuotaUptimeMillis = 0;  // Force a re-check of quota size
    110 
    111             // Run the initialization in the background (not this main thread).
    112             // The init() and trimToFit() methods are synchronized, so they still
    113             // block other users -- but at least the onReceive() call can finish.
    114             new Thread() {
    115                 public void run() {
    116                     try {
    117                         init();
    118                         trimToFit();
    119                     } catch (IOException e) {
    120                         Slog.e(TAG, "Can't init", e);
    121                     }
    122                 }
    123             }.start();
    124         }
    125     };
    126 
    127     private final IDropBoxManagerService.Stub mStub = new IDropBoxManagerService.Stub() {
    128         @Override
    129         public void add(DropBoxManager.Entry entry) {
    130             DropBoxManagerService.this.add(entry);
    131         }
    132 
    133         @Override
    134         public boolean isTagEnabled(String tag) {
    135             return DropBoxManagerService.this.isTagEnabled(tag);
    136         }
    137 
    138         @Override
    139         public DropBoxManager.Entry getNextEntry(String tag, long millis) {
    140             return DropBoxManagerService.this.getNextEntry(tag, millis);
    141         }
    142 
    143         @Override
    144         public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
    145             DropBoxManagerService.this.dump(fd, pw, args);
    146         }
    147     };
    148 
    149     /**
    150      * Creates an instance of managed drop box storage using the default dropbox
    151      * directory.
    152      *
    153      * @param context to use for receiving free space & gservices intents
    154      */
    155     public DropBoxManagerService(final Context context) {
    156         this(context, new File("/data/system/dropbox"));
    157     }
    158 
    159     /**
    160      * Creates an instance of managed drop box storage.  Normally there is one of these
    161      * run by the system, but others can be created for testing and other purposes.
    162      *
    163      * @param context to use for receiving free space & gservices intents
    164      * @param path to store drop box entries in
    165      */
    166     public DropBoxManagerService(final Context context, File path) {
    167         super(context);
    168         mDropBoxDir = path;
    169         mContentResolver = getContext().getContentResolver();
    170         mHandler = new Handler() {
    171             @Override
    172             public void handleMessage(Message msg) {
    173                 if (msg.what == MSG_SEND_BROADCAST) {
    174                     getContext().sendBroadcastAsUser((Intent)msg.obj, UserHandle.SYSTEM,
    175                             android.Manifest.permission.READ_LOGS);
    176                 }
    177             }
    178         };
    179     }
    180 
    181     @Override
    182     public void onStart() {
    183         publishBinderService(Context.DROPBOX_SERVICE, mStub);
    184 
    185         // The real work gets done lazily in init() -- that way service creation always
    186         // succeeds, and things like disk problems cause individual method failures.
    187     }
    188 
    189     @Override
    190     public void onBootPhase(int phase) {
    191         switch (phase) {
    192             case PHASE_SYSTEM_SERVICES_READY:
    193                 IntentFilter filter = new IntentFilter();
    194                 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    195                 getContext().registerReceiver(mReceiver, filter);
    196 
    197                 mContentResolver.registerContentObserver(
    198                     Settings.Global.CONTENT_URI, true,
    199                     new ContentObserver(new Handler()) {
    200                         @Override
    201                         public void onChange(boolean selfChange) {
    202                             mReceiver.onReceive(getContext(), (Intent) null);
    203                         }
    204                     });
    205                 break;
    206 
    207             case PHASE_BOOT_COMPLETED:
    208                 mBooted = true;
    209                 break;
    210         }
    211     }
    212 
    213     /** Retrieves the binder stub -- for test instances */
    214     public IDropBoxManagerService getServiceStub() {
    215         return mStub;
    216     }
    217 
    218     public void add(DropBoxManager.Entry entry) {
    219         File temp = null;
    220         InputStream input = null;
    221         OutputStream output = null;
    222         final String tag = entry.getTag();
    223         try {
    224             int flags = entry.getFlags();
    225             if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
    226 
    227             init();
    228             if (!isTagEnabled(tag)) return;
    229             long max = trimToFit();
    230             long lastTrim = System.currentTimeMillis();
    231 
    232             byte[] buffer = new byte[mBlockSize];
    233             input = entry.getInputStream();
    234 
    235             // First, accumulate up to one block worth of data in memory before
    236             // deciding whether to compress the data or not.
    237 
    238             int read = 0;
    239             while (read < buffer.length) {
    240                 int n = input.read(buffer, read, buffer.length - read);
    241                 if (n <= 0) break;
    242                 read += n;
    243             }
    244 
    245             // If we have at least one block, compress it -- otherwise, just write
    246             // the data in uncompressed form.
    247 
    248             temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
    249             int bufferSize = mBlockSize;
    250             if (bufferSize > 4096) bufferSize = 4096;
    251             if (bufferSize < 512) bufferSize = 512;
    252             FileOutputStream foutput = new FileOutputStream(temp);
    253             output = new BufferedOutputStream(foutput, bufferSize);
    254             if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
    255                 output = new GZIPOutputStream(output);
    256                 flags = flags | DropBoxManager.IS_GZIPPED;
    257             }
    258 
    259             do {
    260                 output.write(buffer, 0, read);
    261 
    262                 long now = System.currentTimeMillis();
    263                 if (now - lastTrim > 30 * 1000) {
    264                     max = trimToFit();  // In case data dribbles in slowly
    265                     lastTrim = now;
    266                 }
    267 
    268                 read = input.read(buffer);
    269                 if (read <= 0) {
    270                     FileUtils.sync(foutput);
    271                     output.close();  // Get a final size measurement
    272                     output = null;
    273                 } else {
    274                     output.flush();  // So the size measurement is pseudo-reasonable
    275                 }
    276 
    277                 long len = temp.length();
    278                 if (len > max) {
    279                     Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
    280                     temp.delete();
    281                     temp = null;  // Pass temp = null to createEntry() to leave a tombstone
    282                     break;
    283                 }
    284             } while (read > 0);
    285 
    286             long time = createEntry(temp, tag, flags);
    287             temp = null;
    288 
    289             final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
    290             dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
    291             dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
    292             if (!mBooted) {
    293                 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
    294             }
    295             // Call sendBroadcast after returning from this call to avoid deadlock. In particular
    296             // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
    297             // lock in ActivityManagerService. ActivityManagerService has been caught holding that
    298             // very lock while waiting for the WindowManagerService lock.
    299             mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
    300         } catch (IOException e) {
    301             Slog.e(TAG, "Can't write: " + tag, e);
    302         } finally {
    303             IoUtils.closeQuietly(output);
    304             IoUtils.closeQuietly(input);
    305             entry.close();
    306             if (temp != null) temp.delete();
    307         }
    308     }
    309 
    310     public boolean isTagEnabled(String tag) {
    311         final long token = Binder.clearCallingIdentity();
    312         try {
    313             return !"disabled".equals(Settings.Global.getString(
    314                     mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
    315         } finally {
    316             Binder.restoreCallingIdentity(token);
    317         }
    318     }
    319 
    320     public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
    321         if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
    322                 != PackageManager.PERMISSION_GRANTED) {
    323             throw new SecurityException("READ_LOGS permission required");
    324         }
    325 
    326         try {
    327             init();
    328         } catch (IOException e) {
    329             Slog.e(TAG, "Can't init", e);
    330             return null;
    331         }
    332 
    333         FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
    334         if (list == null) return null;
    335 
    336         for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
    337             if (entry.tag == null) continue;
    338             if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
    339                 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
    340             }
    341             try {
    342                 return new DropBoxManager.Entry(
    343                         entry.tag, entry.timestampMillis, entry.file, entry.flags);
    344             } catch (IOException e) {
    345                 Slog.e(TAG, "Can't read: " + entry.file, e);
    346                 // Continue to next file
    347             }
    348         }
    349 
    350         return null;
    351     }
    352 
    353     public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
    354         if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
    355 
    356         try {
    357             init();
    358         } catch (IOException e) {
    359             pw.println("Can't initialize: " + e);
    360             Slog.e(TAG, "Can't init", e);
    361             return;
    362         }
    363 
    364         if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
    365 
    366         StringBuilder out = new StringBuilder();
    367         boolean doPrint = false, doFile = false;
    368         ArrayList<String> searchArgs = new ArrayList<String>();
    369         for (int i = 0; args != null && i < args.length; i++) {
    370             if (args[i].equals("-p") || args[i].equals("--print")) {
    371                 doPrint = true;
    372             } else if (args[i].equals("-f") || args[i].equals("--file")) {
    373                 doFile = true;
    374             } else if (args[i].equals("-h") || args[i].equals("--help")) {
    375                 pw.println("Dropbox (dropbox) dump options:");
    376                 pw.println("  [-h|--help] [-p|--print] [-f|--file] [timestamp]");
    377                 pw.println("    -h|--help: print this help");
    378                 pw.println("    -p|--print: print full contents of each entry");
    379                 pw.println("    -f|--file: print path of each entry's file");
    380                 pw.println("  [timestamp] optionally filters to only those entries.");
    381                 return;
    382             } else if (args[i].startsWith("-")) {
    383                 out.append("Unknown argument: ").append(args[i]).append("\n");
    384             } else {
    385                 searchArgs.add(args[i]);
    386             }
    387         }
    388 
    389         out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
    390 
    391         if (!searchArgs.isEmpty()) {
    392             out.append("Searching for:");
    393             for (String a : searchArgs) out.append(" ").append(a);
    394             out.append("\n");
    395         }
    396 
    397         int numFound = 0, numArgs = searchArgs.size();
    398         Time time = new Time();
    399         out.append("\n");
    400         for (EntryFile entry : mAllFiles.contents) {
    401             time.set(entry.timestampMillis);
    402             String date = time.format("%Y-%m-%d %H:%M:%S");
    403             boolean match = true;
    404             for (int i = 0; i < numArgs && match; i++) {
    405                 String arg = searchArgs.get(i);
    406                 match = (date.contains(arg) || arg.equals(entry.tag));
    407             }
    408             if (!match) continue;
    409 
    410             numFound++;
    411             if (doPrint) out.append("========================================\n");
    412             out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
    413             if (entry.file == null) {
    414                 out.append(" (no file)\n");
    415                 continue;
    416             } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
    417                 out.append(" (contents lost)\n");
    418                 continue;
    419             } else {
    420                 out.append(" (");
    421                 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
    422                 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
    423                 out.append(", ").append(entry.file.length()).append(" bytes)\n");
    424             }
    425 
    426             if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
    427                 if (!doPrint) out.append("    ");
    428                 out.append(entry.file.getPath()).append("\n");
    429             }
    430 
    431             if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
    432                 DropBoxManager.Entry dbe = null;
    433                 InputStreamReader isr = null;
    434                 try {
    435                     dbe = new DropBoxManager.Entry(
    436                              entry.tag, entry.timestampMillis, entry.file, entry.flags);
    437 
    438                     if (doPrint) {
    439                         isr = new InputStreamReader(dbe.getInputStream());
    440                         char[] buf = new char[4096];
    441                         boolean newline = false;
    442                         for (;;) {
    443                             int n = isr.read(buf);
    444                             if (n <= 0) break;
    445                             out.append(buf, 0, n);
    446                             newline = (buf[n - 1] == '\n');
    447 
    448                             // Flush periodically when printing to avoid out-of-memory.
    449                             if (out.length() > 65536) {
    450                                 pw.write(out.toString());
    451                                 out.setLength(0);
    452                             }
    453                         }
    454                         if (!newline) out.append("\n");
    455                     } else {
    456                         String text = dbe.getText(70);
    457                         out.append("    ");
    458                         if (text == null) {
    459                             out.append("[null]");
    460                         } else {
    461                             boolean truncated = (text.length() == 70);
    462                             out.append(text.trim().replace('\n', '/'));
    463                             if (truncated) out.append(" ...");
    464                         }
    465                         out.append("\n");
    466                     }
    467                 } catch (IOException e) {
    468                     out.append("*** ").append(e.toString()).append("\n");
    469                     Slog.e(TAG, "Can't read: " + entry.file, e);
    470                 } finally {
    471                     if (dbe != null) dbe.close();
    472                     if (isr != null) {
    473                         try {
    474                             isr.close();
    475                         } catch (IOException unused) {
    476                         }
    477                     }
    478                 }
    479             }
    480 
    481             if (doPrint) out.append("\n");
    482         }
    483 
    484         if (numFound == 0) out.append("(No entries found.)\n");
    485 
    486         if (args == null || args.length == 0) {
    487             if (!doPrint) out.append("\n");
    488             out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
    489         }
    490 
    491         pw.write(out.toString());
    492         if (PROFILE_DUMP) Debug.stopMethodTracing();
    493     }
    494 
    495     ///////////////////////////////////////////////////////////////////////////
    496 
    497     /** Chronologically sorted list of {@link EntryFile} */
    498     private static final class FileList implements Comparable<FileList> {
    499         public int blocks = 0;
    500         public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
    501 
    502         /** Sorts bigger FileList instances before smaller ones. */
    503         public final int compareTo(FileList o) {
    504             if (blocks != o.blocks) return o.blocks - blocks;
    505             if (this == o) return 0;
    506             if (hashCode() < o.hashCode()) return -1;
    507             if (hashCode() > o.hashCode()) return 1;
    508             return 0;
    509         }
    510     }
    511 
    512     /** Metadata describing an on-disk log file. */
    513     private static final class EntryFile implements Comparable<EntryFile> {
    514         public final String tag;
    515         public final long timestampMillis;
    516         public final int flags;
    517         public final File file;
    518         public final int blocks;
    519 
    520         /** Sorts earlier EntryFile instances before later ones. */
    521         public final int compareTo(EntryFile o) {
    522             if (timestampMillis < o.timestampMillis) return -1;
    523             if (timestampMillis > o.timestampMillis) return 1;
    524             if (file != null && o.file != null) return file.compareTo(o.file);
    525             if (o.file != null) return -1;
    526             if (file != null) return 1;
    527             if (this == o) return 0;
    528             if (hashCode() < o.hashCode()) return -1;
    529             if (hashCode() > o.hashCode()) return 1;
    530             return 0;
    531         }
    532 
    533         /**
    534          * Moves an existing temporary file to a new log filename.
    535          * @param temp file to rename
    536          * @param dir to store file in
    537          * @param tag to use for new log file name
    538          * @param timestampMillis of log entry
    539          * @param flags for the entry data
    540          * @param blockSize to use for space accounting
    541          * @throws IOException if the file can't be moved
    542          */
    543         public EntryFile(File temp, File dir, String tag,long timestampMillis,
    544                          int flags, int blockSize) throws IOException {
    545             if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
    546 
    547             this.tag = tag;
    548             this.timestampMillis = timestampMillis;
    549             this.flags = flags;
    550             this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
    551                     ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
    552                     ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
    553 
    554             if (!temp.renameTo(this.file)) {
    555                 throw new IOException("Can't rename " + temp + " to " + this.file);
    556             }
    557             this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
    558         }
    559 
    560         /**
    561          * Creates a zero-length tombstone for a file whose contents were lost.
    562          * @param dir to store file in
    563          * @param tag to use for new log file name
    564          * @param timestampMillis of log entry
    565          * @throws IOException if the file can't be created.
    566          */
    567         public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
    568             this.tag = tag;
    569             this.timestampMillis = timestampMillis;
    570             this.flags = DropBoxManager.IS_EMPTY;
    571             this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
    572             this.blocks = 0;
    573             new FileOutputStream(this.file).close();
    574         }
    575 
    576         /**
    577          * Extracts metadata from an existing on-disk log filename.
    578          * @param file name of existing log file
    579          * @param blockSize to use for space accounting
    580          */
    581         public EntryFile(File file, int blockSize) {
    582             this.file = file;
    583             this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
    584 
    585             String name = file.getName();
    586             int at = name.lastIndexOf('@');
    587             if (at < 0) {
    588                 this.tag = null;
    589                 this.timestampMillis = 0;
    590                 this.flags = DropBoxManager.IS_EMPTY;
    591                 return;
    592             }
    593 
    594             int flags = 0;
    595             this.tag = Uri.decode(name.substring(0, at));
    596             if (name.endsWith(".gz")) {
    597                 flags |= DropBoxManager.IS_GZIPPED;
    598                 name = name.substring(0, name.length() - 3);
    599             }
    600             if (name.endsWith(".lost")) {
    601                 flags |= DropBoxManager.IS_EMPTY;
    602                 name = name.substring(at + 1, name.length() - 5);
    603             } else if (name.endsWith(".txt")) {
    604                 flags |= DropBoxManager.IS_TEXT;
    605                 name = name.substring(at + 1, name.length() - 4);
    606             } else if (name.endsWith(".dat")) {
    607                 name = name.substring(at + 1, name.length() - 4);
    608             } else {
    609                 this.flags = DropBoxManager.IS_EMPTY;
    610                 this.timestampMillis = 0;
    611                 return;
    612             }
    613             this.flags = flags;
    614 
    615             long millis;
    616             try { millis = Long.parseLong(name); } catch (NumberFormatException e) { millis = 0; }
    617             this.timestampMillis = millis;
    618         }
    619 
    620         /**
    621          * Creates a EntryFile object with only a timestamp for comparison purposes.
    622          * @param millis to compare with.
    623          */
    624         public EntryFile(long millis) {
    625             this.tag = null;
    626             this.timestampMillis = millis;
    627             this.flags = DropBoxManager.IS_EMPTY;
    628             this.file = null;
    629             this.blocks = 0;
    630         }
    631     }
    632 
    633     ///////////////////////////////////////////////////////////////////////////
    634 
    635     /** If never run before, scans disk contents to build in-memory tracking data. */
    636     private synchronized void init() throws IOException {
    637         if (mStatFs == null) {
    638             if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
    639                 throw new IOException("Can't mkdir: " + mDropBoxDir);
    640             }
    641             try {
    642                 mStatFs = new StatFs(mDropBoxDir.getPath());
    643                 mBlockSize = mStatFs.getBlockSize();
    644             } catch (IllegalArgumentException e) {  // StatFs throws this on error
    645                 throw new IOException("Can't statfs: " + mDropBoxDir);
    646             }
    647         }
    648 
    649         if (mAllFiles == null) {
    650             File[] files = mDropBoxDir.listFiles();
    651             if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
    652 
    653             mAllFiles = new FileList();
    654             mFilesByTag = new HashMap<String, FileList>();
    655 
    656             // Scan pre-existing files.
    657             for (File file : files) {
    658                 if (file.getName().endsWith(".tmp")) {
    659                     Slog.i(TAG, "Cleaning temp file: " + file);
    660                     file.delete();
    661                     continue;
    662                 }
    663 
    664                 EntryFile entry = new EntryFile(file, mBlockSize);
    665                 if (entry.tag == null) {
    666                     Slog.w(TAG, "Unrecognized file: " + file);
    667                     continue;
    668                 } else if (entry.timestampMillis == 0) {
    669                     Slog.w(TAG, "Invalid filename: " + file);
    670                     file.delete();
    671                     continue;
    672                 }
    673 
    674                 enrollEntry(entry);
    675             }
    676         }
    677     }
    678 
    679     /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
    680     private synchronized void enrollEntry(EntryFile entry) {
    681         mAllFiles.contents.add(entry);
    682         mAllFiles.blocks += entry.blocks;
    683 
    684         // mFilesByTag is used for trimming, so don't list empty files.
    685         // (Zero-length/lost files are trimmed by date from mAllFiles.)
    686 
    687         if (entry.tag != null && entry.file != null && entry.blocks > 0) {
    688             FileList tagFiles = mFilesByTag.get(entry.tag);
    689             if (tagFiles == null) {
    690                 tagFiles = new FileList();
    691                 mFilesByTag.put(entry.tag, tagFiles);
    692             }
    693             tagFiles.contents.add(entry);
    694             tagFiles.blocks += entry.blocks;
    695         }
    696     }
    697 
    698     /** Moves a temporary file to a final log filename and enrolls it. */
    699     private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
    700         long t = System.currentTimeMillis();
    701 
    702         // Require each entry to have a unique timestamp; if there are entries
    703         // >10sec in the future (due to clock skew), drag them back to avoid
    704         // keeping them around forever.
    705 
    706         SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
    707         EntryFile[] future = null;
    708         if (!tail.isEmpty()) {
    709             future = tail.toArray(new EntryFile[tail.size()]);
    710             tail.clear();  // Remove from mAllFiles
    711         }
    712 
    713         if (!mAllFiles.contents.isEmpty()) {
    714             t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
    715         }
    716 
    717         if (future != null) {
    718             for (EntryFile late : future) {
    719                 mAllFiles.blocks -= late.blocks;
    720                 FileList tagFiles = mFilesByTag.get(late.tag);
    721                 if (tagFiles != null && tagFiles.contents.remove(late)) {
    722                     tagFiles.blocks -= late.blocks;
    723                 }
    724                 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
    725                     enrollEntry(new EntryFile(
    726                             late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
    727                 } else {
    728                     enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
    729                 }
    730             }
    731         }
    732 
    733         if (temp == null) {
    734             enrollEntry(new EntryFile(mDropBoxDir, tag, t));
    735         } else {
    736             enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
    737         }
    738         return t;
    739     }
    740 
    741     /**
    742      * Trims the files on disk to make sure they aren't using too much space.
    743      * @return the overall quota for storage (in bytes)
    744      */
    745     private synchronized long trimToFit() throws IOException {
    746         // Expunge aged items (including tombstones marking deleted data).
    747 
    748         int ageSeconds = Settings.Global.getInt(mContentResolver,
    749                 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
    750         int maxFiles = Settings.Global.getInt(mContentResolver,
    751                 Settings.Global.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
    752         long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
    753         while (!mAllFiles.contents.isEmpty()) {
    754             EntryFile entry = mAllFiles.contents.first();
    755             if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
    756 
    757             FileList tag = mFilesByTag.get(entry.tag);
    758             if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
    759             if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
    760             if (entry.file != null) entry.file.delete();
    761         }
    762 
    763         // Compute overall quota (a fraction of available free space) in blocks.
    764         // The quota changes dynamically based on the amount of free space;
    765         // that way when lots of data is available we can use it, but we'll get
    766         // out of the way if storage starts getting tight.
    767 
    768         long uptimeMillis = SystemClock.uptimeMillis();
    769         if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
    770             int quotaPercent = Settings.Global.getInt(mContentResolver,
    771                     Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
    772             int reservePercent = Settings.Global.getInt(mContentResolver,
    773                     Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
    774             int quotaKb = Settings.Global.getInt(mContentResolver,
    775                     Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
    776 
    777             String dirPath = mDropBoxDir.getPath();
    778             try {
    779                 mStatFs.restat(dirPath);
    780             } catch (IllegalArgumentException e) {  // restat throws this on error
    781                 throw new IOException("Can't restat: " + mDropBoxDir);
    782             }
    783             int available = mStatFs.getAvailableBlocks();
    784             int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
    785             int maximum = quotaKb * 1024 / mBlockSize;
    786             mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
    787             mCachedQuotaUptimeMillis = uptimeMillis;
    788         }
    789 
    790         // If we're using too much space, delete old items to make room.
    791         //
    792         // We trim each tag independently (this is why we keep per-tag lists).
    793         // Space is "fairly" shared between tags -- they are all squeezed
    794         // equally until enough space is reclaimed.
    795         //
    796         // A single circular buffer (a la logcat) would be simpler, but this
    797         // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
    798         // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
    799         // well-behaved data streams (event statistics, profile data, etc).
    800         //
    801         // Deleted files are replaced with zero-length tombstones to mark what
    802         // was lost.  Tombstones are expunged by age (see above).
    803 
    804         if (mAllFiles.blocks > mCachedQuotaBlocks) {
    805             // Find a fair share amount of space to limit each tag
    806             int unsqueezed = mAllFiles.blocks, squeezed = 0;
    807             TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
    808             for (FileList tag : tags) {
    809                 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
    810                     break;
    811                 }
    812                 unsqueezed -= tag.blocks;
    813                 squeezed++;
    814             }
    815             int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
    816 
    817             // Remove old items from each tag until it meets the per-tag quota.
    818             for (FileList tag : tags) {
    819                 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
    820                 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
    821                     EntryFile entry = tag.contents.first();
    822                     if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
    823                     if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
    824 
    825                     try {
    826                         if (entry.file != null) entry.file.delete();
    827                         enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
    828                     } catch (IOException e) {
    829                         Slog.e(TAG, "Can't write tombstone file", e);
    830                     }
    831                 }
    832             }
    833         }
    834 
    835         return mCachedQuotaBlocks * mBlockSize;
    836     }
    837 }
    838