blob: 0b12410251f47cf41c3db813b37038e3839bc7c3 [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;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070034import android.os.UserHandle;
Dan Egnor4410ec82009-09-11 16:40:01 -070035import android.provider.Settings;
Dan Egnor3d40df32009-11-17 13:36:31 -080036import android.text.format.Time;
Joe Onorato8a9b2202010-02-26 18:56:32 -080037import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070038
Dan Egnorf18a01c2009-11-12 11:32:50 -080039import com.android.internal.os.IDropBoxManagerService;
Dan Egnor95240272009-10-27 18:23:39 -070040
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070041import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070042import java.io.File;
43import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070044import java.io.FileOutputStream;
45import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070046import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070047import java.io.InputStreamReader;
48import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070049import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070050import java.util.ArrayList;
Dan Egnor4410ec82009-09-11 16:40:01 -070051import java.util.HashMap;
Dan Egnor4410ec82009-09-11 16:40:01 -070052import java.util.SortedSet;
53import java.util.TreeSet;
54import java.util.zip.GZIPOutputStream;
55
56/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080057 * Implementation of {@link IDropBoxManagerService} using the filesystem.
58 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070059 */
Dan Egnorf18a01c2009-11-12 11:32:50 -080060public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
61 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070062 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070063 private static final int DEFAULT_MAX_FILES = 1000;
64 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
65 private static final int DEFAULT_QUOTA_PERCENT = 10;
66 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070067 private static final int QUOTA_RESCAN_MILLIS = 5000;
68
Craig Mautner26caf7a2012-03-04 17:17:59 -080069 // mHandler 'what' value.
70 private static final int MSG_SEND_BROADCAST = 1;
71
Dan Egnor3d40df32009-11-17 13:36:31 -080072 private static final boolean PROFILE_DUMP = false;
73
Dan Egnor4410ec82009-09-11 16:40:01 -070074 // TODO: This implementation currently uses one file per entry, which is
75 // inefficient for smallish entries -- consider using a single queue file
76 // per tag (or even globally) instead.
77
78 // The cached context and derived objects
79
80 private final Context mContext;
81 private final ContentResolver mContentResolver;
82 private final File mDropBoxDir;
83
84 // Accounting of all currently written log files (set in init()).
85
86 private FileList mAllFiles = null;
87 private HashMap<String, FileList> mFilesByTag = null;
88
89 // Various bits of disk information
90
91 private StatFs mStatFs = null;
92 private int mBlockSize = 0;
93 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
94 private long mCachedQuotaUptimeMillis = 0;
95
Brad Fitzpatrick34165c62011-01-17 18:14:18 -080096 private volatile boolean mBooted = false;
97
Craig Mautner26caf7a2012-03-04 17:17:59 -080098 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
99 private final Handler mHandler;
100
Dan Egnor4410ec82009-09-11 16:40:01 -0700101 /** Receives events that might indicate a need to clean up files. */
102 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
103 @Override
104 public void onReceive(Context context, Intent intent) {
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800105 if (intent != null && Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
106 mBooted = true;
107 return;
108 }
109
110 // Else, for ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700111 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700112
113 // Run the initialization in the background (not this main thread).
114 // The init() and trimToFit() methods are synchronized, so they still
115 // block other users -- but at least the onReceive() call can finish.
116 new Thread() {
117 public void run() {
118 try {
119 init();
120 trimToFit();
121 } catch (IOException e) {
122 Slog.e(TAG, "Can't init", e);
123 }
124 }
125 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700126 }
127 };
128
129 /**
130 * Creates an instance of managed drop box storage. Normally there is one of these
131 * run by the system, but others can be created for testing and other purposes.
132 *
133 * @param context to use for receiving free space & gservices intents
134 * @param path to store drop box entries in
135 */
Doug Zongker43866e02010-01-07 12:09:54 -0800136 public DropBoxManagerService(final Context context, File path) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700137 mDropBoxDir = path;
138
139 // Set up intent receivers
140 mContext = context;
141 mContentResolver = context.getContentResolver();
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800142
143 IntentFilter filter = new IntentFilter();
144 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
145 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
146 context.registerReceiver(mReceiver, filter);
Doug Zongker43866e02010-01-07 12:09:54 -0800147
148 mContentResolver.registerContentObserver(
149 Settings.Secure.CONTENT_URI, true,
150 new ContentObserver(new Handler()) {
Craig Mautner26caf7a2012-03-04 17:17:59 -0800151 @Override
Doug Zongker43866e02010-01-07 12:09:54 -0800152 public void onChange(boolean selfChange) {
153 mReceiver.onReceive(context, (Intent) null);
154 }
155 });
Dan Egnor4410ec82009-09-11 16:40:01 -0700156
Craig Mautner26caf7a2012-03-04 17:17:59 -0800157 mHandler = new Handler() {
158 @Override
159 public void handleMessage(Message msg) {
160 if (msg.what == MSG_SEND_BROADCAST) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700161 mContext.sendBroadcastAsUser((Intent)msg.obj, UserHandle.OWNER,
162 android.Manifest.permission.READ_LOGS);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800163 }
164 }
165 };
166
Dan Egnor4410ec82009-09-11 16:40:01 -0700167 // The real work gets done lazily in init() -- that way service creation always
168 // succeeds, and things like disk problems cause individual method failures.
169 }
170
171 /** Unregisters broadcast receivers and any other hooks -- for test instances */
172 public void stop() {
173 mContext.unregisterReceiver(mReceiver);
174 }
175
Craig Mautner26caf7a2012-03-04 17:17:59 -0800176 @Override
Dan Egnorf18a01c2009-11-12 11:32:50 -0800177 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700178 File temp = null;
179 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700180 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700181 try {
Dan Egnor95240272009-10-27 18:23:39 -0700182 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800183 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700184
185 init();
186 if (!isTagEnabled(tag)) return;
187 long max = trimToFit();
188 long lastTrim = System.currentTimeMillis();
189
190 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700191 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700192
193 // First, accumulate up to one block worth of data in memory before
194 // deciding whether to compress the data or not.
195
196 int read = 0;
197 while (read < buffer.length) {
198 int n = input.read(buffer, read, buffer.length - read);
199 if (n <= 0) break;
200 read += n;
201 }
202
203 // If we have at least one block, compress it -- otherwise, just write
204 // the data in uncompressed form.
205
206 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700207 int bufferSize = mBlockSize;
208 if (bufferSize > 4096) bufferSize = 4096;
209 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700210 FileOutputStream foutput = new FileOutputStream(temp);
211 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800212 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700213 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800214 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700215 }
216
217 do {
218 output.write(buffer, 0, read);
219
220 long now = System.currentTimeMillis();
221 if (now - lastTrim > 30 * 1000) {
222 max = trimToFit(); // In case data dribbles in slowly
223 lastTrim = now;
224 }
225
226 read = input.read(buffer);
227 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700228 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700229 output.close(); // Get a final size measurement
230 output = null;
231 } else {
232 output.flush(); // So the size measurement is pseudo-reasonable
233 }
234
235 long len = temp.length();
236 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800237 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700238 temp.delete();
239 temp = null; // Pass temp = null to createEntry() to leave a tombstone
240 break;
241 }
242 } while (read > 0);
243
Hakan Stillb2475362010-12-07 14:05:55 +0100244 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700245 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100246
Craig Mautner26caf7a2012-03-04 17:17:59 -0800247 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
Hakan Stillb2475362010-12-07 14:05:55 +0100248 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
249 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800250 if (!mBooted) {
251 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
252 }
Craig Mautner26caf7a2012-03-04 17:17:59 -0800253 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
254 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
255 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
256 // very lock while waiting for the WindowManagerService lock.
257 mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
Dan Egnor4410ec82009-09-11 16:40:01 -0700258 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800259 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700260 } finally {
261 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700262 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700263 if (temp != null) temp.delete();
264 }
265 }
266
267 public boolean isTagEnabled(String tag) {
Doug Zongker43866e02010-01-07 12:09:54 -0800268 return !"disabled".equals(Settings.Secure.getString(
269 mContentResolver, Settings.Secure.DROPBOX_TAG_PREFIX + tag));
Dan Egnor4410ec82009-09-11 16:40:01 -0700270 }
271
Dan Egnorf18a01c2009-11-12 11:32:50 -0800272 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700273 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
274 != PackageManager.PERMISSION_GRANTED) {
275 throw new SecurityException("READ_LOGS permission required");
276 }
277
278 try {
279 init();
280 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800281 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700282 return null;
283 }
284
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700285 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
286 if (list == null) return null;
287
288 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700289 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800290 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
291 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700292 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700293 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800294 return new DropBoxManager.Entry(
295 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700296 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800297 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700298 // Continue to next file
299 }
300 }
301
302 return null;
303 }
304
305 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
306 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
307 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800308 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700309 return;
310 }
311
312 try {
313 init();
314 } catch (IOException e) {
315 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800316 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700317 return;
318 }
319
Dan Egnor3d40df32009-11-17 13:36:31 -0800320 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
321
Dan Egnor5ec249a2009-11-25 13:16:47 -0800322 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700323 boolean doPrint = false, doFile = false;
324 ArrayList<String> searchArgs = new ArrayList<String>();
325 for (int i = 0; args != null && i < args.length; i++) {
326 if (args[i].equals("-p") || args[i].equals("--print")) {
327 doPrint = true;
328 } else if (args[i].equals("-f") || args[i].equals("--file")) {
329 doFile = true;
330 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800331 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700332 } else {
333 searchArgs.add(args[i]);
334 }
335 }
336
Dan Egnor5ec249a2009-11-25 13:16:47 -0800337 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700338
339 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800340 out.append("Searching for:");
341 for (String a : searchArgs) out.append(" ").append(a);
342 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700343 }
344
Dan Egnor3d40df32009-11-17 13:36:31 -0800345 int numFound = 0, numArgs = searchArgs.size();
346 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800347 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700348 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800349 time.set(entry.timestampMillis);
350 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700351 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800352 for (int i = 0; i < numArgs && match; i++) {
353 String arg = searchArgs.get(i);
354 match = (date.contains(arg) || arg.equals(entry.tag));
355 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700356 if (!match) continue;
357
358 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800359 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800360 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700361 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800362 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700363 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800364 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800365 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700366 continue;
367 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800368 out.append(" (");
369 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
370 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
371 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700372 }
373
Dan Egnorf18a01c2009-11-12 11:32:50 -0800374 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800375 if (!doPrint) out.append(" ");
376 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700377 }
378
Dan Egnorf18a01c2009-11-12 11:32:50 -0800379 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
380 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800381 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700382 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800383 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700384 entry.tag, entry.timestampMillis, entry.file, entry.flags);
385
386 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800387 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700388 char[] buf = new char[4096];
389 boolean newline = false;
390 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800391 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700392 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800393 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700394 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800395
396 // Flush periodically when printing to avoid out-of-memory.
397 if (out.length() > 65536) {
398 pw.write(out.toString());
399 out.setLength(0);
400 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700401 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800402 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700403 } else {
404 String text = dbe.getText(70);
405 boolean truncated = (text.length() == 70);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800406 out.append(" ").append(text.trim().replace('\n', '/'));
407 if (truncated) out.append(" ...");
408 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700409 }
410 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800411 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800412 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700413 } finally {
414 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800415 if (isr != null) {
416 try {
417 isr.close();
418 } catch (IOException unused) {
419 }
420 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700421 }
422 }
423
Dan Egnor5ec249a2009-11-25 13:16:47 -0800424 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700425 }
426
Dan Egnor5ec249a2009-11-25 13:16:47 -0800427 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700428
429 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800430 if (!doPrint) out.append("\n");
431 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700432 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800433
434 pw.write(out.toString());
435 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700436 }
437
438 ///////////////////////////////////////////////////////////////////////////
439
440 /** Chronologically sorted list of {@link #EntryFile} */
441 private static final class FileList implements Comparable<FileList> {
442 public int blocks = 0;
443 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
444
445 /** Sorts bigger FileList instances before smaller ones. */
446 public final int compareTo(FileList o) {
447 if (blocks != o.blocks) return o.blocks - blocks;
448 if (this == o) return 0;
449 if (hashCode() < o.hashCode()) return -1;
450 if (hashCode() > o.hashCode()) return 1;
451 return 0;
452 }
453 }
454
455 /** Metadata describing an on-disk log file. */
456 private static final class EntryFile implements Comparable<EntryFile> {
457 public final String tag;
458 public final long timestampMillis;
459 public final int flags;
460 public final File file;
461 public final int blocks;
462
463 /** Sorts earlier EntryFile instances before later ones. */
464 public final int compareTo(EntryFile o) {
465 if (timestampMillis < o.timestampMillis) return -1;
466 if (timestampMillis > o.timestampMillis) return 1;
467 if (file != null && o.file != null) return file.compareTo(o.file);
468 if (o.file != null) return -1;
469 if (file != null) return 1;
470 if (this == o) return 0;
471 if (hashCode() < o.hashCode()) return -1;
472 if (hashCode() > o.hashCode()) return 1;
473 return 0;
474 }
475
476 /**
477 * Moves an existing temporary file to a new log filename.
478 * @param temp file to rename
479 * @param dir to store file in
480 * @param tag to use for new log file name
481 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700482 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700483 * @param blockSize to use for space accounting
484 * @throws IOException if the file can't be moved
485 */
486 public EntryFile(File temp, File dir, String tag,long timestampMillis,
487 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800488 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700489
490 this.tag = tag;
491 this.timestampMillis = timestampMillis;
492 this.flags = flags;
493 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800494 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
495 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700496
497 if (!temp.renameTo(this.file)) {
498 throw new IOException("Can't rename " + temp + " to " + this.file);
499 }
500 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
501 }
502
503 /**
504 * Creates a zero-length tombstone for a file whose contents were lost.
505 * @param dir to store file in
506 * @param tag to use for new log file name
507 * @param timestampMillis of log entry
508 * @throws IOException if the file can't be created.
509 */
510 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
511 this.tag = tag;
512 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800513 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700514 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
515 this.blocks = 0;
516 new FileOutputStream(this.file).close();
517 }
518
519 /**
520 * Extracts metadata from an existing on-disk log filename.
521 * @param file name of existing log file
522 * @param blockSize to use for space accounting
523 */
524 public EntryFile(File file, int blockSize) {
525 this.file = file;
526 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
527
528 String name = file.getName();
529 int at = name.lastIndexOf('@');
530 if (at < 0) {
531 this.tag = null;
532 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800533 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700534 return;
535 }
536
537 int flags = 0;
538 this.tag = Uri.decode(name.substring(0, at));
539 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800540 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700541 name = name.substring(0, name.length() - 3);
542 }
543 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800544 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700545 name = name.substring(at + 1, name.length() - 5);
546 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800547 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700548 name = name.substring(at + 1, name.length() - 4);
549 } else if (name.endsWith(".dat")) {
550 name = name.substring(at + 1, name.length() - 4);
551 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800552 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700553 this.timestampMillis = 0;
554 return;
555 }
556 this.flags = flags;
557
558 long millis;
559 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
560 this.timestampMillis = millis;
561 }
562
563 /**
564 * Creates a EntryFile object with only a timestamp for comparison purposes.
565 * @param timestampMillis to compare with.
566 */
567 public EntryFile(long millis) {
568 this.tag = null;
569 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800570 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700571 this.file = null;
572 this.blocks = 0;
573 }
574 }
575
576 ///////////////////////////////////////////////////////////////////////////
577
578 /** If never run before, scans disk contents to build in-memory tracking data. */
579 private synchronized void init() throws IOException {
580 if (mStatFs == null) {
581 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
582 throw new IOException("Can't mkdir: " + mDropBoxDir);
583 }
584 try {
585 mStatFs = new StatFs(mDropBoxDir.getPath());
586 mBlockSize = mStatFs.getBlockSize();
587 } catch (IllegalArgumentException e) { // StatFs throws this on error
588 throw new IOException("Can't statfs: " + mDropBoxDir);
589 }
590 }
591
592 if (mAllFiles == null) {
593 File[] files = mDropBoxDir.listFiles();
594 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
595
596 mAllFiles = new FileList();
597 mFilesByTag = new HashMap<String, FileList>();
598
599 // Scan pre-existing files.
600 for (File file : files) {
601 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800602 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700603 file.delete();
604 continue;
605 }
606
607 EntryFile entry = new EntryFile(file, mBlockSize);
608 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800609 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700610 continue;
611 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800612 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700613 file.delete();
614 continue;
615 }
616
617 enrollEntry(entry);
618 }
619 }
620 }
621
622 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
623 private synchronized void enrollEntry(EntryFile entry) {
624 mAllFiles.contents.add(entry);
625 mAllFiles.blocks += entry.blocks;
626
627 // mFilesByTag is used for trimming, so don't list empty files.
628 // (Zero-length/lost files are trimmed by date from mAllFiles.)
629
630 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
631 FileList tagFiles = mFilesByTag.get(entry.tag);
632 if (tagFiles == null) {
633 tagFiles = new FileList();
634 mFilesByTag.put(entry.tag, tagFiles);
635 }
636 tagFiles.contents.add(entry);
637 tagFiles.blocks += entry.blocks;
638 }
639 }
640
641 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100642 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700643 long t = System.currentTimeMillis();
644
645 // Require each entry to have a unique timestamp; if there are entries
646 // >10sec in the future (due to clock skew), drag them back to avoid
647 // keeping them around forever.
648
649 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
650 EntryFile[] future = null;
651 if (!tail.isEmpty()) {
652 future = tail.toArray(new EntryFile[tail.size()]);
653 tail.clear(); // Remove from mAllFiles
654 }
655
656 if (!mAllFiles.contents.isEmpty()) {
657 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
658 }
659
660 if (future != null) {
661 for (EntryFile late : future) {
662 mAllFiles.blocks -= late.blocks;
663 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800664 if (tagFiles != null && tagFiles.contents.remove(late)) {
665 tagFiles.blocks -= late.blocks;
666 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800667 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700668 enrollEntry(new EntryFile(
669 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
670 } else {
671 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
672 }
673 }
674 }
675
676 if (temp == null) {
677 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
678 } else {
679 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
680 }
Hakan Stillb2475362010-12-07 14:05:55 +0100681 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700682 }
683
684 /**
685 * Trims the files on disk to make sure they aren't using too much space.
686 * @return the overall quota for storage (in bytes)
687 */
688 private synchronized long trimToFit() {
689 // Expunge aged items (including tombstones marking deleted data).
690
Doug Zongker43866e02010-01-07 12:09:54 -0800691 int ageSeconds = Settings.Secure.getInt(mContentResolver,
692 Settings.Secure.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700693 int maxFiles = Settings.Secure.getInt(mContentResolver,
694 Settings.Secure.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700695 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
696 while (!mAllFiles.contents.isEmpty()) {
697 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700698 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700699
700 FileList tag = mFilesByTag.get(entry.tag);
701 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
702 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
703 if (entry.file != null) entry.file.delete();
704 }
705
706 // Compute overall quota (a fraction of available free space) in blocks.
707 // The quota changes dynamically based on the amount of free space;
708 // that way when lots of data is available we can use it, but we'll get
709 // out of the way if storage starts getting tight.
710
711 long uptimeMillis = SystemClock.uptimeMillis();
712 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Doug Zongker43866e02010-01-07 12:09:54 -0800713 int quotaPercent = Settings.Secure.getInt(mContentResolver,
714 Settings.Secure.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
715 int reservePercent = Settings.Secure.getInt(mContentResolver,
716 Settings.Secure.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
717 int quotaKb = Settings.Secure.getInt(mContentResolver,
718 Settings.Secure.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700719
720 mStatFs.restat(mDropBoxDir.getPath());
721 int available = mStatFs.getAvailableBlocks();
722 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
723 int maximum = quotaKb * 1024 / mBlockSize;
724 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
725 mCachedQuotaUptimeMillis = uptimeMillis;
726 }
727
728 // If we're using too much space, delete old items to make room.
729 //
730 // We trim each tag independently (this is why we keep per-tag lists).
731 // Space is "fairly" shared between tags -- they are all squeezed
732 // equally until enough space is reclaimed.
733 //
734 // A single circular buffer (a la logcat) would be simpler, but this
735 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
736 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700737 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700738 //
739 // Deleted files are replaced with zero-length tombstones to mark what
740 // was lost. Tombstones are expunged by age (see above).
741
742 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700743 // Find a fair share amount of space to limit each tag
744 int unsqueezed = mAllFiles.blocks, squeezed = 0;
745 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
746 for (FileList tag : tags) {
747 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
748 break;
749 }
750 unsqueezed -= tag.blocks;
751 squeezed++;
752 }
753 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
754
755 // Remove old items from each tag until it meets the per-tag quota.
756 for (FileList tag : tags) {
757 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
758 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
759 EntryFile entry = tag.contents.first();
760 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
761 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
762
763 try {
764 if (entry.file != null) entry.file.delete();
765 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
766 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800767 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700768 }
769 }
770 }
771 }
772
773 return mCachedQuotaBlocks * mBlockSize;
774 }
775}