blob: 932cba121e367a0822dbc3cef048b298f481cb17 [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;
Craig Mautner26caf7a2012-03-04 17:17:59 -080031import android.os.Message;
Dan Egnor4410ec82009-09-11 16:40:01 -070032import 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;
Dan Egnor4410ec82009-09-11 16:40:01 -070048import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070049import java.util.ArrayList;
Dan Egnor4410ec82009-09-11 16:40:01 -070050import java.util.HashMap;
Dan Egnor4410ec82009-09-11 16:40:01 -070051import java.util.SortedSet;
52import java.util.TreeSet;
53import java.util.zip.GZIPOutputStream;
54
55/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080056 * Implementation of {@link IDropBoxManagerService} using the filesystem.
57 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070058 */
Dan Egnorf18a01c2009-11-12 11:32:50 -080059public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
60 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070061 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070062 private static final int DEFAULT_MAX_FILES = 1000;
63 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
64 private static final int DEFAULT_QUOTA_PERCENT = 10;
65 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070066 private static final int QUOTA_RESCAN_MILLIS = 5000;
67
Craig Mautner26caf7a2012-03-04 17:17:59 -080068 // mHandler 'what' value.
69 private static final int MSG_SEND_BROADCAST = 1;
70
Dan Egnor3d40df32009-11-17 13:36:31 -080071 private static final boolean PROFILE_DUMP = false;
72
Dan Egnor4410ec82009-09-11 16:40:01 -070073 // TODO: This implementation currently uses one file per entry, which is
74 // inefficient for smallish entries -- consider using a single queue file
75 // per tag (or even globally) instead.
76
77 // The cached context and derived objects
78
79 private final Context mContext;
80 private final ContentResolver mContentResolver;
81 private final File mDropBoxDir;
82
83 // Accounting of all currently written log files (set in init()).
84
85 private FileList mAllFiles = null;
86 private HashMap<String, FileList> mFilesByTag = null;
87
88 // Various bits of disk information
89
90 private StatFs mStatFs = null;
91 private int mBlockSize = 0;
92 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
93 private long mCachedQuotaUptimeMillis = 0;
94
Brad Fitzpatrick34165c62011-01-17 18:14:18 -080095 private volatile boolean mBooted = false;
96
Craig Mautner26caf7a2012-03-04 17:17:59 -080097 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
98 private final Handler mHandler;
99
Dan Egnor4410ec82009-09-11 16:40:01 -0700100 /** Receives events that might indicate a need to clean up files. */
101 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
102 @Override
103 public void onReceive(Context context, Intent intent) {
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800104 if (intent != null && Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
105 mBooted = true;
106 return;
107 }
108
109 // Else, for ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700110 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700111
112 // Run the initialization in the background (not this main thread).
113 // The init() and trimToFit() methods are synchronized, so they still
114 // block other users -- but at least the onReceive() call can finish.
115 new Thread() {
116 public void run() {
117 try {
118 init();
119 trimToFit();
120 } catch (IOException e) {
121 Slog.e(TAG, "Can't init", e);
122 }
123 }
124 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700125 }
126 };
127
128 /**
129 * Creates an instance of managed drop box storage. Normally there is one of these
130 * run by the system, but others can be created for testing and other purposes.
131 *
132 * @param context to use for receiving free space & gservices intents
133 * @param path to store drop box entries in
134 */
Doug Zongker43866e02010-01-07 12:09:54 -0800135 public DropBoxManagerService(final Context context, File path) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700136 mDropBoxDir = path;
137
138 // Set up intent receivers
139 mContext = context;
140 mContentResolver = context.getContentResolver();
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800141
142 IntentFilter filter = new IntentFilter();
143 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
144 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
145 context.registerReceiver(mReceiver, filter);
Doug Zongker43866e02010-01-07 12:09:54 -0800146
147 mContentResolver.registerContentObserver(
148 Settings.Secure.CONTENT_URI, true,
149 new ContentObserver(new Handler()) {
Craig Mautner26caf7a2012-03-04 17:17:59 -0800150 @Override
Doug Zongker43866e02010-01-07 12:09:54 -0800151 public void onChange(boolean selfChange) {
152 mReceiver.onReceive(context, (Intent) null);
153 }
154 });
Dan Egnor4410ec82009-09-11 16:40:01 -0700155
Craig Mautner26caf7a2012-03-04 17:17:59 -0800156 mHandler = new Handler() {
157 @Override
158 public void handleMessage(Message msg) {
159 if (msg.what == MSG_SEND_BROADCAST) {
160 mContext.sendBroadcast((Intent)msg.obj, android.Manifest.permission.READ_LOGS);
161 }
162 }
163 };
164
Dan Egnor4410ec82009-09-11 16:40:01 -0700165 // The real work gets done lazily in init() -- that way service creation always
166 // succeeds, and things like disk problems cause individual method failures.
167 }
168
169 /** Unregisters broadcast receivers and any other hooks -- for test instances */
170 public void stop() {
171 mContext.unregisterReceiver(mReceiver);
172 }
173
Craig Mautner26caf7a2012-03-04 17:17:59 -0800174 @Override
Dan Egnorf18a01c2009-11-12 11:32:50 -0800175 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700176 File temp = null;
177 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700178 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700179 try {
Dan Egnor95240272009-10-27 18:23:39 -0700180 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800181 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700182
183 init();
184 if (!isTagEnabled(tag)) return;
185 long max = trimToFit();
186 long lastTrim = System.currentTimeMillis();
187
188 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700189 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700190
191 // First, accumulate up to one block worth of data in memory before
192 // deciding whether to compress the data or not.
193
194 int read = 0;
195 while (read < buffer.length) {
196 int n = input.read(buffer, read, buffer.length - read);
197 if (n <= 0) break;
198 read += n;
199 }
200
201 // If we have at least one block, compress it -- otherwise, just write
202 // the data in uncompressed form.
203
204 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700205 int bufferSize = mBlockSize;
206 if (bufferSize > 4096) bufferSize = 4096;
207 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700208 FileOutputStream foutput = new FileOutputStream(temp);
209 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800210 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700211 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800212 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700213 }
214
215 do {
216 output.write(buffer, 0, read);
217
218 long now = System.currentTimeMillis();
219 if (now - lastTrim > 30 * 1000) {
220 max = trimToFit(); // In case data dribbles in slowly
221 lastTrim = now;
222 }
223
224 read = input.read(buffer);
225 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700226 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700227 output.close(); // Get a final size measurement
228 output = null;
229 } else {
230 output.flush(); // So the size measurement is pseudo-reasonable
231 }
232
233 long len = temp.length();
234 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800235 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700236 temp.delete();
237 temp = null; // Pass temp = null to createEntry() to leave a tombstone
238 break;
239 }
240 } while (read > 0);
241
Hakan Stillb2475362010-12-07 14:05:55 +0100242 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700243 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100244
Craig Mautner26caf7a2012-03-04 17:17:59 -0800245 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
Hakan Stillb2475362010-12-07 14:05:55 +0100246 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
247 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800248 if (!mBooted) {
249 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
250 }
Craig Mautner26caf7a2012-03-04 17:17:59 -0800251 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
252 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
253 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
254 // very lock while waiting for the WindowManagerService lock.
255 mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
Dan Egnor4410ec82009-09-11 16:40:01 -0700256 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800257 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700258 } finally {
259 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700260 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700261 if (temp != null) temp.delete();
262 }
263 }
264
265 public boolean isTagEnabled(String tag) {
Doug Zongker43866e02010-01-07 12:09:54 -0800266 return !"disabled".equals(Settings.Secure.getString(
267 mContentResolver, Settings.Secure.DROPBOX_TAG_PREFIX + tag));
Dan Egnor4410ec82009-09-11 16:40:01 -0700268 }
269
Dan Egnorf18a01c2009-11-12 11:32:50 -0800270 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700271 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
272 != PackageManager.PERMISSION_GRANTED) {
273 throw new SecurityException("READ_LOGS permission required");
274 }
275
276 try {
277 init();
278 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800279 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700280 return null;
281 }
282
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700283 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
284 if (list == null) return null;
285
286 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700287 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800288 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
289 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700290 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700291 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800292 return new DropBoxManager.Entry(
293 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700294 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800295 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700296 // Continue to next file
297 }
298 }
299
300 return null;
301 }
302
303 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
304 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
305 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800306 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700307 return;
308 }
309
310 try {
311 init();
312 } catch (IOException e) {
313 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800314 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700315 return;
316 }
317
Dan Egnor3d40df32009-11-17 13:36:31 -0800318 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
319
Dan Egnor5ec249a2009-11-25 13:16:47 -0800320 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700321 boolean doPrint = false, doFile = false;
322 ArrayList<String> searchArgs = new ArrayList<String>();
323 for (int i = 0; args != null && i < args.length; i++) {
324 if (args[i].equals("-p") || args[i].equals("--print")) {
325 doPrint = true;
326 } else if (args[i].equals("-f") || args[i].equals("--file")) {
327 doFile = true;
328 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800329 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700330 } else {
331 searchArgs.add(args[i]);
332 }
333 }
334
Dan Egnor5ec249a2009-11-25 13:16:47 -0800335 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700336
337 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800338 out.append("Searching for:");
339 for (String a : searchArgs) out.append(" ").append(a);
340 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700341 }
342
Dan Egnor3d40df32009-11-17 13:36:31 -0800343 int numFound = 0, numArgs = searchArgs.size();
344 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800345 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700346 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800347 time.set(entry.timestampMillis);
348 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700349 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800350 for (int i = 0; i < numArgs && match; i++) {
351 String arg = searchArgs.get(i);
352 match = (date.contains(arg) || arg.equals(entry.tag));
353 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700354 if (!match) continue;
355
356 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800357 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800358 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700359 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800360 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700361 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800362 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800363 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700364 continue;
365 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800366 out.append(" (");
367 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
368 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
369 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700370 }
371
Dan Egnorf18a01c2009-11-12 11:32:50 -0800372 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800373 if (!doPrint) out.append(" ");
374 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700375 }
376
Dan Egnorf18a01c2009-11-12 11:32:50 -0800377 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
378 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800379 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700380 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800381 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700382 entry.tag, entry.timestampMillis, entry.file, entry.flags);
383
384 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800385 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700386 char[] buf = new char[4096];
387 boolean newline = false;
388 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800389 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700390 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800391 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700392 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800393
394 // Flush periodically when printing to avoid out-of-memory.
395 if (out.length() > 65536) {
396 pw.write(out.toString());
397 out.setLength(0);
398 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700399 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800400 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700401 } else {
402 String text = dbe.getText(70);
403 boolean truncated = (text.length() == 70);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800404 out.append(" ").append(text.trim().replace('\n', '/'));
405 if (truncated) out.append(" ...");
406 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700407 }
408 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800409 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800410 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700411 } finally {
412 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800413 if (isr != null) {
414 try {
415 isr.close();
416 } catch (IOException unused) {
417 }
418 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700419 }
420 }
421
Dan Egnor5ec249a2009-11-25 13:16:47 -0800422 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700423 }
424
Dan Egnor5ec249a2009-11-25 13:16:47 -0800425 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700426
427 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800428 if (!doPrint) out.append("\n");
429 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700430 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800431
432 pw.write(out.toString());
433 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700434 }
435
436 ///////////////////////////////////////////////////////////////////////////
437
438 /** Chronologically sorted list of {@link #EntryFile} */
439 private static final class FileList implements Comparable<FileList> {
440 public int blocks = 0;
441 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
442
443 /** Sorts bigger FileList instances before smaller ones. */
444 public final int compareTo(FileList o) {
445 if (blocks != o.blocks) return o.blocks - blocks;
446 if (this == o) return 0;
447 if (hashCode() < o.hashCode()) return -1;
448 if (hashCode() > o.hashCode()) return 1;
449 return 0;
450 }
451 }
452
453 /** Metadata describing an on-disk log file. */
454 private static final class EntryFile implements Comparable<EntryFile> {
455 public final String tag;
456 public final long timestampMillis;
457 public final int flags;
458 public final File file;
459 public final int blocks;
460
461 /** Sorts earlier EntryFile instances before later ones. */
462 public final int compareTo(EntryFile o) {
463 if (timestampMillis < o.timestampMillis) return -1;
464 if (timestampMillis > o.timestampMillis) return 1;
465 if (file != null && o.file != null) return file.compareTo(o.file);
466 if (o.file != null) return -1;
467 if (file != null) return 1;
468 if (this == o) return 0;
469 if (hashCode() < o.hashCode()) return -1;
470 if (hashCode() > o.hashCode()) return 1;
471 return 0;
472 }
473
474 /**
475 * Moves an existing temporary file to a new log filename.
476 * @param temp file to rename
477 * @param dir to store file in
478 * @param tag to use for new log file name
479 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700480 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700481 * @param blockSize to use for space accounting
482 * @throws IOException if the file can't be moved
483 */
484 public EntryFile(File temp, File dir, String tag,long timestampMillis,
485 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800486 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700487
488 this.tag = tag;
489 this.timestampMillis = timestampMillis;
490 this.flags = flags;
491 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800492 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
493 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700494
495 if (!temp.renameTo(this.file)) {
496 throw new IOException("Can't rename " + temp + " to " + this.file);
497 }
498 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
499 }
500
501 /**
502 * Creates a zero-length tombstone for a file whose contents were lost.
503 * @param dir to store file in
504 * @param tag to use for new log file name
505 * @param timestampMillis of log entry
506 * @throws IOException if the file can't be created.
507 */
508 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
509 this.tag = tag;
510 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800511 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700512 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
513 this.blocks = 0;
514 new FileOutputStream(this.file).close();
515 }
516
517 /**
518 * Extracts metadata from an existing on-disk log filename.
519 * @param file name of existing log file
520 * @param blockSize to use for space accounting
521 */
522 public EntryFile(File file, int blockSize) {
523 this.file = file;
524 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
525
526 String name = file.getName();
527 int at = name.lastIndexOf('@');
528 if (at < 0) {
529 this.tag = null;
530 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800531 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700532 return;
533 }
534
535 int flags = 0;
536 this.tag = Uri.decode(name.substring(0, at));
537 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800538 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700539 name = name.substring(0, name.length() - 3);
540 }
541 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800542 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700543 name = name.substring(at + 1, name.length() - 5);
544 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800545 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700546 name = name.substring(at + 1, name.length() - 4);
547 } else if (name.endsWith(".dat")) {
548 name = name.substring(at + 1, name.length() - 4);
549 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800550 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700551 this.timestampMillis = 0;
552 return;
553 }
554 this.flags = flags;
555
556 long millis;
557 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
558 this.timestampMillis = millis;
559 }
560
561 /**
562 * Creates a EntryFile object with only a timestamp for comparison purposes.
563 * @param timestampMillis to compare with.
564 */
565 public EntryFile(long millis) {
566 this.tag = null;
567 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800568 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700569 this.file = null;
570 this.blocks = 0;
571 }
572 }
573
574 ///////////////////////////////////////////////////////////////////////////
575
576 /** If never run before, scans disk contents to build in-memory tracking data. */
577 private synchronized void init() throws IOException {
578 if (mStatFs == null) {
579 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
580 throw new IOException("Can't mkdir: " + mDropBoxDir);
581 }
582 try {
583 mStatFs = new StatFs(mDropBoxDir.getPath());
584 mBlockSize = mStatFs.getBlockSize();
585 } catch (IllegalArgumentException e) { // StatFs throws this on error
586 throw new IOException("Can't statfs: " + mDropBoxDir);
587 }
588 }
589
590 if (mAllFiles == null) {
591 File[] files = mDropBoxDir.listFiles();
592 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
593
594 mAllFiles = new FileList();
595 mFilesByTag = new HashMap<String, FileList>();
596
597 // Scan pre-existing files.
598 for (File file : files) {
599 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800600 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700601 file.delete();
602 continue;
603 }
604
605 EntryFile entry = new EntryFile(file, mBlockSize);
606 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800607 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700608 continue;
609 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800610 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700611 file.delete();
612 continue;
613 }
614
615 enrollEntry(entry);
616 }
617 }
618 }
619
620 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
621 private synchronized void enrollEntry(EntryFile entry) {
622 mAllFiles.contents.add(entry);
623 mAllFiles.blocks += entry.blocks;
624
625 // mFilesByTag is used for trimming, so don't list empty files.
626 // (Zero-length/lost files are trimmed by date from mAllFiles.)
627
628 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
629 FileList tagFiles = mFilesByTag.get(entry.tag);
630 if (tagFiles == null) {
631 tagFiles = new FileList();
632 mFilesByTag.put(entry.tag, tagFiles);
633 }
634 tagFiles.contents.add(entry);
635 tagFiles.blocks += entry.blocks;
636 }
637 }
638
639 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100640 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700641 long t = System.currentTimeMillis();
642
643 // Require each entry to have a unique timestamp; if there are entries
644 // >10sec in the future (due to clock skew), drag them back to avoid
645 // keeping them around forever.
646
647 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
648 EntryFile[] future = null;
649 if (!tail.isEmpty()) {
650 future = tail.toArray(new EntryFile[tail.size()]);
651 tail.clear(); // Remove from mAllFiles
652 }
653
654 if (!mAllFiles.contents.isEmpty()) {
655 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
656 }
657
658 if (future != null) {
659 for (EntryFile late : future) {
660 mAllFiles.blocks -= late.blocks;
661 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800662 if (tagFiles != null && tagFiles.contents.remove(late)) {
663 tagFiles.blocks -= late.blocks;
664 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800665 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700666 enrollEntry(new EntryFile(
667 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
668 } else {
669 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
670 }
671 }
672 }
673
674 if (temp == null) {
675 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
676 } else {
677 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
678 }
Hakan Stillb2475362010-12-07 14:05:55 +0100679 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700680 }
681
682 /**
683 * Trims the files on disk to make sure they aren't using too much space.
684 * @return the overall quota for storage (in bytes)
685 */
686 private synchronized long trimToFit() {
687 // Expunge aged items (including tombstones marking deleted data).
688
Doug Zongker43866e02010-01-07 12:09:54 -0800689 int ageSeconds = Settings.Secure.getInt(mContentResolver,
690 Settings.Secure.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700691 int maxFiles = Settings.Secure.getInt(mContentResolver,
692 Settings.Secure.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700693 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
694 while (!mAllFiles.contents.isEmpty()) {
695 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700696 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700697
698 FileList tag = mFilesByTag.get(entry.tag);
699 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
700 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
701 if (entry.file != null) entry.file.delete();
702 }
703
704 // Compute overall quota (a fraction of available free space) in blocks.
705 // The quota changes dynamically based on the amount of free space;
706 // that way when lots of data is available we can use it, but we'll get
707 // out of the way if storage starts getting tight.
708
709 long uptimeMillis = SystemClock.uptimeMillis();
710 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Doug Zongker43866e02010-01-07 12:09:54 -0800711 int quotaPercent = Settings.Secure.getInt(mContentResolver,
712 Settings.Secure.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
713 int reservePercent = Settings.Secure.getInt(mContentResolver,
714 Settings.Secure.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
715 int quotaKb = Settings.Secure.getInt(mContentResolver,
716 Settings.Secure.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700717
718 mStatFs.restat(mDropBoxDir.getPath());
719 int available = mStatFs.getAvailableBlocks();
720 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
721 int maximum = quotaKb * 1024 / mBlockSize;
722 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
723 mCachedQuotaUptimeMillis = uptimeMillis;
724 }
725
726 // If we're using too much space, delete old items to make room.
727 //
728 // We trim each tag independently (this is why we keep per-tag lists).
729 // Space is "fairly" shared between tags -- they are all squeezed
730 // equally until enough space is reclaimed.
731 //
732 // A single circular buffer (a la logcat) would be simpler, but this
733 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
734 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700735 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700736 //
737 // Deleted files are replaced with zero-length tombstones to mark what
738 // was lost. Tombstones are expunged by age (see above).
739
740 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700741 // Find a fair share amount of space to limit each tag
742 int unsqueezed = mAllFiles.blocks, squeezed = 0;
743 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
744 for (FileList tag : tags) {
745 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
746 break;
747 }
748 unsqueezed -= tag.blocks;
749 squeezed++;
750 }
751 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
752
753 // Remove old items from each tag until it meets the per-tag quota.
754 for (FileList tag : tags) {
755 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
756 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
757 EntryFile entry = tag.contents.first();
758 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
759 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
760
761 try {
762 if (entry.file != null) entry.file.delete();
763 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
764 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800765 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700766 }
767 }
768 }
769 }
770
771 return mCachedQuotaBlocks * mBlockSize;
772 }
773}