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