blob: 5c878c946231a72730476935e103bf65f4ebef5b [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;
Doug Zongker43866e02010-01-07 12:09:54 -080025import android.database.ContentObserver;
Dan Egnor4410ec82009-09-11 16:40:01 -070026import android.net.Uri;
Dan Egnor3d40df32009-11-17 13:36:31 -080027import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080028import android.os.DropBoxManager;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070029import android.os.FileUtils;
Doug Zongker43866e02010-01-07 12:09:54 -080030import android.os.Handler;
Dan Egnor4410ec82009-09-11 16:40:01 -070031import android.os.ParcelFileDescriptor;
32import android.os.StatFs;
33import android.os.SystemClock;
34import android.provider.Settings;
Dan Egnor3d40df32009-11-17 13:36:31 -080035import android.text.format.Time;
Joe Onorato8a9b2202010-02-26 18:56:32 -080036import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070037
Dan Egnorf18a01c2009-11-12 11:32:50 -080038import com.android.internal.os.IDropBoxManagerService;
Dan Egnor95240272009-10-27 18:23:39 -070039
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070040import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070041import java.io.File;
42import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070043import java.io.FileOutputStream;
44import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070045import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070046import java.io.InputStreamReader;
47import java.io.OutputStream;
48import java.io.OutputStreamWriter;
49import java.io.PrintWriter;
50import java.io.UnsupportedEncodingException;
51import java.util.ArrayList;
52import java.util.Comparator;
Dan Egnor4410ec82009-09-11 16:40:01 -070053import java.util.HashMap;
54import java.util.Iterator;
55import java.util.Map;
56import java.util.SortedSet;
57import java.util.TreeSet;
58import java.util.zip.GZIPOutputStream;
59
60/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080061 * Implementation of {@link IDropBoxManagerService} using the filesystem.
62 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070063 */
Dan Egnorf18a01c2009-11-12 11:32:50 -080064public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
65 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070066 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070067 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;
Dan Egnor4410ec82009-09-11 16:40:01 -070071 private static final int QUOTA_RESCAN_MILLIS = 5000;
72
Dan Egnor3d40df32009-11-17 13:36:31 -080073 private static final boolean PROFILE_DUMP = false;
74
Dan Egnor4410ec82009-09-11 16:40:01 -070075 // TODO: This implementation currently uses one file per entry, which is
76 // inefficient for smallish entries -- consider using a single queue file
77 // per tag (or even globally) instead.
78
79 // The cached context and derived objects
80
81 private final Context mContext;
82 private final ContentResolver mContentResolver;
83 private final File mDropBoxDir;
84
85 // Accounting of all currently written log files (set in init()).
86
87 private FileList mAllFiles = null;
88 private HashMap<String, FileList> mFilesByTag = null;
89
90 // Various bits of disk information
91
92 private StatFs mStatFs = null;
93 private int mBlockSize = 0;
94 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
95 private long mCachedQuotaUptimeMillis = 0;
96
97 // Ensure that all log entries have a unique timestamp
98 private long mLastTimestamp = 0;
99
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800100 private volatile boolean mBooted = false;
101
Dan Egnor4410ec82009-09-11 16:40:01 -0700102 /** Receives events that might indicate a need to clean up files. */
103 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
104 @Override
105 public void onReceive(Context context, Intent intent) {
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800106 if (intent != null && Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
107 mBooted = true;
108 return;
109 }
110
111 // Else, for ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700112 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700113
114 // Run the initialization in the background (not this main thread).
115 // The init() and trimToFit() methods are synchronized, so they still
116 // block other users -- but at least the onReceive() call can finish.
117 new Thread() {
118 public void run() {
119 try {
120 init();
121 trimToFit();
122 } catch (IOException e) {
123 Slog.e(TAG, "Can't init", e);
124 }
125 }
126 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700127 }
128 };
129
130 /**
131 * Creates an instance of managed drop box storage. Normally there is one of these
132 * run by the system, but others can be created for testing and other purposes.
133 *
134 * @param context to use for receiving free space & gservices intents
135 * @param path to store drop box entries in
136 */
Doug Zongker43866e02010-01-07 12:09:54 -0800137 public DropBoxManagerService(final Context context, File path) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700138 mDropBoxDir = path;
139
140 // Set up intent receivers
141 mContext = context;
142 mContentResolver = context.getContentResolver();
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800143
144 IntentFilter filter = new IntentFilter();
145 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
146 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
147 context.registerReceiver(mReceiver, filter);
Doug Zongker43866e02010-01-07 12:09:54 -0800148
149 mContentResolver.registerContentObserver(
150 Settings.Secure.CONTENT_URI, true,
151 new ContentObserver(new Handler()) {
152 public void onChange(boolean selfChange) {
153 mReceiver.onReceive(context, (Intent) null);
154 }
155 });
Dan Egnor4410ec82009-09-11 16:40:01 -0700156
157 // The real work gets done lazily in init() -- that way service creation always
158 // succeeds, and things like disk problems cause individual method failures.
159 }
160
161 /** Unregisters broadcast receivers and any other hooks -- for test instances */
162 public void stop() {
163 mContext.unregisterReceiver(mReceiver);
164 }
165
Dan Egnorf18a01c2009-11-12 11:32:50 -0800166 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700167 File temp = null;
168 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700169 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700170 try {
Dan Egnor95240272009-10-27 18:23:39 -0700171 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800172 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700173
174 init();
175 if (!isTagEnabled(tag)) return;
176 long max = trimToFit();
177 long lastTrim = System.currentTimeMillis();
178
179 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700180 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700181
182 // First, accumulate up to one block worth of data in memory before
183 // deciding whether to compress the data or not.
184
185 int read = 0;
186 while (read < buffer.length) {
187 int n = input.read(buffer, read, buffer.length - read);
188 if (n <= 0) break;
189 read += n;
190 }
191
192 // If we have at least one block, compress it -- otherwise, just write
193 // the data in uncompressed form.
194
195 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700196 int bufferSize = mBlockSize;
197 if (bufferSize > 4096) bufferSize = 4096;
198 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700199 FileOutputStream foutput = new FileOutputStream(temp);
200 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800201 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700202 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800203 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700204 }
205
206 do {
207 output.write(buffer, 0, read);
208
209 long now = System.currentTimeMillis();
210 if (now - lastTrim > 30 * 1000) {
211 max = trimToFit(); // In case data dribbles in slowly
212 lastTrim = now;
213 }
214
215 read = input.read(buffer);
216 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700217 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700218 output.close(); // Get a final size measurement
219 output = null;
220 } else {
221 output.flush(); // So the size measurement is pseudo-reasonable
222 }
223
224 long len = temp.length();
225 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800226 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700227 temp.delete();
228 temp = null; // Pass temp = null to createEntry() to leave a tombstone
229 break;
230 }
231 } while (read > 0);
232
Hakan Stillb2475362010-12-07 14:05:55 +0100233 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700234 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100235
236 Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
237 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
238 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800239 if (!mBooted) {
240 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
241 }
Hakan Stillb2475362010-12-07 14:05:55 +0100242 mContext.sendBroadcast(dropboxIntent, android.Manifest.permission.READ_LOGS);
243
Dan Egnor4410ec82009-09-11 16:40:01 -0700244 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800245 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700246 } finally {
247 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700248 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700249 if (temp != null) temp.delete();
250 }
251 }
252
253 public boolean isTagEnabled(String tag) {
Doug Zongker43866e02010-01-07 12:09:54 -0800254 return !"disabled".equals(Settings.Secure.getString(
255 mContentResolver, Settings.Secure.DROPBOX_TAG_PREFIX + tag));
Dan Egnor4410ec82009-09-11 16:40:01 -0700256 }
257
Dan Egnorf18a01c2009-11-12 11:32:50 -0800258 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700259 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
260 != PackageManager.PERMISSION_GRANTED) {
261 throw new SecurityException("READ_LOGS permission required");
262 }
263
264 try {
265 init();
266 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800267 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700268 return null;
269 }
270
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700271 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
272 if (list == null) return null;
273
274 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700275 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800276 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
277 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700278 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700279 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800280 return new DropBoxManager.Entry(
281 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700282 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800283 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700284 // Continue to next file
285 }
286 }
287
288 return null;
289 }
290
291 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
292 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
293 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800294 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700295 return;
296 }
297
298 try {
299 init();
300 } catch (IOException e) {
301 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800302 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700303 return;
304 }
305
Dan Egnor3d40df32009-11-17 13:36:31 -0800306 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
307
Dan Egnor5ec249a2009-11-25 13:16:47 -0800308 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700309 boolean doPrint = false, doFile = false;
310 ArrayList<String> searchArgs = new ArrayList<String>();
311 for (int i = 0; args != null && i < args.length; i++) {
312 if (args[i].equals("-p") || args[i].equals("--print")) {
313 doPrint = true;
314 } else if (args[i].equals("-f") || args[i].equals("--file")) {
315 doFile = true;
316 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800317 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700318 } else {
319 searchArgs.add(args[i]);
320 }
321 }
322
Dan Egnor5ec249a2009-11-25 13:16:47 -0800323 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700324
325 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800326 out.append("Searching for:");
327 for (String a : searchArgs) out.append(" ").append(a);
328 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700329 }
330
Dan Egnor3d40df32009-11-17 13:36:31 -0800331 int numFound = 0, numArgs = searchArgs.size();
332 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800333 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700334 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800335 time.set(entry.timestampMillis);
336 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700337 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800338 for (int i = 0; i < numArgs && match; i++) {
339 String arg = searchArgs.get(i);
340 match = (date.contains(arg) || arg.equals(entry.tag));
341 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700342 if (!match) continue;
343
344 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800345 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800346 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700347 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800348 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700349 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800350 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800351 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700352 continue;
353 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800354 out.append(" (");
355 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
356 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
357 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700358 }
359
Dan Egnorf18a01c2009-11-12 11:32:50 -0800360 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800361 if (!doPrint) out.append(" ");
362 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700363 }
364
Dan Egnorf18a01c2009-11-12 11:32:50 -0800365 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
366 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800367 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700368 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800369 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700370 entry.tag, entry.timestampMillis, entry.file, entry.flags);
371
372 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800373 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700374 char[] buf = new char[4096];
375 boolean newline = false;
376 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800377 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700378 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800379 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700380 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800381
382 // Flush periodically when printing to avoid out-of-memory.
383 if (out.length() > 65536) {
384 pw.write(out.toString());
385 out.setLength(0);
386 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700387 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800388 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700389 } else {
390 String text = dbe.getText(70);
391 boolean truncated = (text.length() == 70);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800392 out.append(" ").append(text.trim().replace('\n', '/'));
393 if (truncated) out.append(" ...");
394 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700395 }
396 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800397 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800398 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700399 } finally {
400 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800401 if (isr != null) {
402 try {
403 isr.close();
404 } catch (IOException unused) {
405 }
406 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700407 }
408 }
409
Dan Egnor5ec249a2009-11-25 13:16:47 -0800410 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700411 }
412
Dan Egnor5ec249a2009-11-25 13:16:47 -0800413 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700414
415 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800416 if (!doPrint) out.append("\n");
417 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700418 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800419
420 pw.write(out.toString());
421 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700422 }
423
424 ///////////////////////////////////////////////////////////////////////////
425
426 /** Chronologically sorted list of {@link #EntryFile} */
427 private static final class FileList implements Comparable<FileList> {
428 public int blocks = 0;
429 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
430
431 /** Sorts bigger FileList instances before smaller ones. */
432 public final int compareTo(FileList o) {
433 if (blocks != o.blocks) return o.blocks - blocks;
434 if (this == o) return 0;
435 if (hashCode() < o.hashCode()) return -1;
436 if (hashCode() > o.hashCode()) return 1;
437 return 0;
438 }
439 }
440
441 /** Metadata describing an on-disk log file. */
442 private static final class EntryFile implements Comparable<EntryFile> {
443 public final String tag;
444 public final long timestampMillis;
445 public final int flags;
446 public final File file;
447 public final int blocks;
448
449 /** Sorts earlier EntryFile instances before later ones. */
450 public final int compareTo(EntryFile o) {
451 if (timestampMillis < o.timestampMillis) return -1;
452 if (timestampMillis > o.timestampMillis) return 1;
453 if (file != null && o.file != null) return file.compareTo(o.file);
454 if (o.file != null) return -1;
455 if (file != null) return 1;
456 if (this == o) return 0;
457 if (hashCode() < o.hashCode()) return -1;
458 if (hashCode() > o.hashCode()) return 1;
459 return 0;
460 }
461
462 /**
463 * Moves an existing temporary file to a new log filename.
464 * @param temp file to rename
465 * @param dir to store file in
466 * @param tag to use for new log file name
467 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700468 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700469 * @param blockSize to use for space accounting
470 * @throws IOException if the file can't be moved
471 */
472 public EntryFile(File temp, File dir, String tag,long timestampMillis,
473 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800474 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700475
476 this.tag = tag;
477 this.timestampMillis = timestampMillis;
478 this.flags = flags;
479 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800480 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
481 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700482
483 if (!temp.renameTo(this.file)) {
484 throw new IOException("Can't rename " + temp + " to " + this.file);
485 }
486 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
487 }
488
489 /**
490 * Creates a zero-length tombstone for a file whose contents were lost.
491 * @param dir to store file in
492 * @param tag to use for new log file name
493 * @param timestampMillis of log entry
494 * @throws IOException if the file can't be created.
495 */
496 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
497 this.tag = tag;
498 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800499 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700500 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
501 this.blocks = 0;
502 new FileOutputStream(this.file).close();
503 }
504
505 /**
506 * Extracts metadata from an existing on-disk log filename.
507 * @param file name of existing log file
508 * @param blockSize to use for space accounting
509 */
510 public EntryFile(File file, int blockSize) {
511 this.file = file;
512 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
513
514 String name = file.getName();
515 int at = name.lastIndexOf('@');
516 if (at < 0) {
517 this.tag = null;
518 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800519 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700520 return;
521 }
522
523 int flags = 0;
524 this.tag = Uri.decode(name.substring(0, at));
525 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800526 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700527 name = name.substring(0, name.length() - 3);
528 }
529 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800530 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700531 name = name.substring(at + 1, name.length() - 5);
532 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800533 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700534 name = name.substring(at + 1, name.length() - 4);
535 } else if (name.endsWith(".dat")) {
536 name = name.substring(at + 1, name.length() - 4);
537 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800538 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700539 this.timestampMillis = 0;
540 return;
541 }
542 this.flags = flags;
543
544 long millis;
545 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
546 this.timestampMillis = millis;
547 }
548
549 /**
550 * Creates a EntryFile object with only a timestamp for comparison purposes.
551 * @param timestampMillis to compare with.
552 */
553 public EntryFile(long millis) {
554 this.tag = null;
555 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800556 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700557 this.file = null;
558 this.blocks = 0;
559 }
560 }
561
562 ///////////////////////////////////////////////////////////////////////////
563
564 /** If never run before, scans disk contents to build in-memory tracking data. */
565 private synchronized void init() throws IOException {
566 if (mStatFs == null) {
567 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
568 throw new IOException("Can't mkdir: " + mDropBoxDir);
569 }
570 try {
571 mStatFs = new StatFs(mDropBoxDir.getPath());
572 mBlockSize = mStatFs.getBlockSize();
573 } catch (IllegalArgumentException e) { // StatFs throws this on error
574 throw new IOException("Can't statfs: " + mDropBoxDir);
575 }
576 }
577
578 if (mAllFiles == null) {
579 File[] files = mDropBoxDir.listFiles();
580 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
581
582 mAllFiles = new FileList();
583 mFilesByTag = new HashMap<String, FileList>();
584
585 // Scan pre-existing files.
586 for (File file : files) {
587 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800588 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700589 file.delete();
590 continue;
591 }
592
593 EntryFile entry = new EntryFile(file, mBlockSize);
594 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800595 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700596 continue;
597 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800598 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700599 file.delete();
600 continue;
601 }
602
603 enrollEntry(entry);
604 }
605 }
606 }
607
608 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
609 private synchronized void enrollEntry(EntryFile entry) {
610 mAllFiles.contents.add(entry);
611 mAllFiles.blocks += entry.blocks;
612
613 // mFilesByTag is used for trimming, so don't list empty files.
614 // (Zero-length/lost files are trimmed by date from mAllFiles.)
615
616 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
617 FileList tagFiles = mFilesByTag.get(entry.tag);
618 if (tagFiles == null) {
619 tagFiles = new FileList();
620 mFilesByTag.put(entry.tag, tagFiles);
621 }
622 tagFiles.contents.add(entry);
623 tagFiles.blocks += entry.blocks;
624 }
625 }
626
627 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100628 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700629 long t = System.currentTimeMillis();
630
631 // Require each entry to have a unique timestamp; if there are entries
632 // >10sec in the future (due to clock skew), drag them back to avoid
633 // keeping them around forever.
634
635 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
636 EntryFile[] future = null;
637 if (!tail.isEmpty()) {
638 future = tail.toArray(new EntryFile[tail.size()]);
639 tail.clear(); // Remove from mAllFiles
640 }
641
642 if (!mAllFiles.contents.isEmpty()) {
643 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
644 }
645
646 if (future != null) {
647 for (EntryFile late : future) {
648 mAllFiles.blocks -= late.blocks;
649 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800650 if (tagFiles != null && tagFiles.contents.remove(late)) {
651 tagFiles.blocks -= late.blocks;
652 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800653 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700654 enrollEntry(new EntryFile(
655 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
656 } else {
657 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
658 }
659 }
660 }
661
662 if (temp == null) {
663 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
664 } else {
665 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
666 }
Hakan Stillb2475362010-12-07 14:05:55 +0100667 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700668 }
669
670 /**
671 * Trims the files on disk to make sure they aren't using too much space.
672 * @return the overall quota for storage (in bytes)
673 */
674 private synchronized long trimToFit() {
675 // Expunge aged items (including tombstones marking deleted data).
676
Doug Zongker43866e02010-01-07 12:09:54 -0800677 int ageSeconds = Settings.Secure.getInt(mContentResolver,
678 Settings.Secure.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700679 int maxFiles = Settings.Secure.getInt(mContentResolver,
680 Settings.Secure.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700681 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
682 while (!mAllFiles.contents.isEmpty()) {
683 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700684 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700685
686 FileList tag = mFilesByTag.get(entry.tag);
687 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
688 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
689 if (entry.file != null) entry.file.delete();
690 }
691
692 // Compute overall quota (a fraction of available free space) in blocks.
693 // The quota changes dynamically based on the amount of free space;
694 // that way when lots of data is available we can use it, but we'll get
695 // out of the way if storage starts getting tight.
696
697 long uptimeMillis = SystemClock.uptimeMillis();
698 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Doug Zongker43866e02010-01-07 12:09:54 -0800699 int quotaPercent = Settings.Secure.getInt(mContentResolver,
700 Settings.Secure.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
701 int reservePercent = Settings.Secure.getInt(mContentResolver,
702 Settings.Secure.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
703 int quotaKb = Settings.Secure.getInt(mContentResolver,
704 Settings.Secure.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700705
706 mStatFs.restat(mDropBoxDir.getPath());
707 int available = mStatFs.getAvailableBlocks();
708 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
709 int maximum = quotaKb * 1024 / mBlockSize;
710 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
711 mCachedQuotaUptimeMillis = uptimeMillis;
712 }
713
714 // If we're using too much space, delete old items to make room.
715 //
716 // We trim each tag independently (this is why we keep per-tag lists).
717 // Space is "fairly" shared between tags -- they are all squeezed
718 // equally until enough space is reclaimed.
719 //
720 // A single circular buffer (a la logcat) would be simpler, but this
721 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
722 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700723 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700724 //
725 // Deleted files are replaced with zero-length tombstones to mark what
726 // was lost. Tombstones are expunged by age (see above).
727
728 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700729 // Find a fair share amount of space to limit each tag
730 int unsqueezed = mAllFiles.blocks, squeezed = 0;
731 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
732 for (FileList tag : tags) {
733 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
734 break;
735 }
736 unsqueezed -= tag.blocks;
737 squeezed++;
738 }
739 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
740
741 // Remove old items from each tag until it meets the per-tag quota.
742 for (FileList tag : tags) {
743 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
744 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
745 EntryFile entry = tag.contents.first();
746 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
747 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
748
749 try {
750 if (entry.file != null) entry.file.delete();
751 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
752 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800753 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700754 }
755 }
756 }
757 }
758
759 return mCachedQuotaBlocks * mBlockSize;
760 }
761}