blob: a44cb72034e9089acf7b5095abca6becce8c3d20 [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;
Jeff Sharkey911d7f42013-09-05 18:11:45 -070027import android.os.Binder;
Dan Egnor3d40df32009-11-17 13:36:31 -080028import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080029import android.os.DropBoxManager;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070030import android.os.FileUtils;
Doug Zongker43866e02010-01-07 12:09:54 -080031import android.os.Handler;
Craig Mautner26caf7a2012-03-04 17:17:59 -080032import android.os.Message;
Dan Egnor4410ec82009-09-11 16:40:01 -070033import android.os.StatFs;
34import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070035import android.os.UserHandle;
Dan Egnor4410ec82009-09-11 16:40:01 -070036import android.provider.Settings;
Dan Egnor3d40df32009-11-17 13:36:31 -080037import android.text.format.Time;
Joe Onorato8a9b2202010-02-26 18:56:32 -080038import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070039
Dan Egnorf18a01c2009-11-12 11:32:50 -080040import com.android.internal.os.IDropBoxManagerService;
Dan Egnor95240272009-10-27 18:23:39 -070041
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070042import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070043import java.io.File;
44import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070045import java.io.FileOutputStream;
46import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070047import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070048import java.io.InputStreamReader;
49import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070050import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070051import java.util.ArrayList;
Dan Egnor4410ec82009-09-11 16:40:01 -070052import java.util.HashMap;
Dan Egnor4410ec82009-09-11 16:40:01 -070053import java.util.SortedSet;
54import java.util.TreeSet;
55import java.util.zip.GZIPOutputStream;
56
57/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080058 * Implementation of {@link IDropBoxManagerService} using the filesystem.
59 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070060 */
Dan Egnorf18a01c2009-11-12 11:32:50 -080061public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
62 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070063 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070064 private static final int DEFAULT_MAX_FILES = 1000;
65 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
66 private static final int DEFAULT_QUOTA_PERCENT = 10;
67 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070068 private static final int QUOTA_RESCAN_MILLIS = 5000;
69
Craig Mautner26caf7a2012-03-04 17:17:59 -080070 // mHandler 'what' value.
71 private static final int MSG_SEND_BROADCAST = 1;
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
Brad Fitzpatrick34165c62011-01-17 18:14:18 -080097 private volatile boolean mBooted = false;
98
Craig Mautner26caf7a2012-03-04 17:17:59 -080099 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
100 private final Handler mHandler;
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(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700150 Settings.Global.CONTENT_URI, true,
Doug Zongker43866e02010-01-07 12:09:54 -0800151 new ContentObserver(new Handler()) {
Craig Mautner26caf7a2012-03-04 17:17:59 -0800152 @Override
Doug Zongker43866e02010-01-07 12:09:54 -0800153 public void onChange(boolean selfChange) {
154 mReceiver.onReceive(context, (Intent) null);
155 }
156 });
Dan Egnor4410ec82009-09-11 16:40:01 -0700157
Craig Mautner26caf7a2012-03-04 17:17:59 -0800158 mHandler = new Handler() {
159 @Override
160 public void handleMessage(Message msg) {
161 if (msg.what == MSG_SEND_BROADCAST) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700162 mContext.sendBroadcastAsUser((Intent)msg.obj, UserHandle.OWNER,
163 android.Manifest.permission.READ_LOGS);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800164 }
165 }
166 };
167
Dan Egnor4410ec82009-09-11 16:40:01 -0700168 // The real work gets done lazily in init() -- that way service creation always
169 // succeeds, and things like disk problems cause individual method failures.
170 }
171
172 /** Unregisters broadcast receivers and any other hooks -- for test instances */
173 public void stop() {
174 mContext.unregisterReceiver(mReceiver);
175 }
176
Craig Mautner26caf7a2012-03-04 17:17:59 -0800177 @Override
Dan Egnorf18a01c2009-11-12 11:32:50 -0800178 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700179 File temp = null;
180 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700181 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700182 try {
Dan Egnor95240272009-10-27 18:23:39 -0700183 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800184 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700185
186 init();
187 if (!isTagEnabled(tag)) return;
188 long max = trimToFit();
189 long lastTrim = System.currentTimeMillis();
190
191 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700192 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700193
194 // First, accumulate up to one block worth of data in memory before
195 // deciding whether to compress the data or not.
196
197 int read = 0;
198 while (read < buffer.length) {
199 int n = input.read(buffer, read, buffer.length - read);
200 if (n <= 0) break;
201 read += n;
202 }
203
204 // If we have at least one block, compress it -- otherwise, just write
205 // the data in uncompressed form.
206
207 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700208 int bufferSize = mBlockSize;
209 if (bufferSize > 4096) bufferSize = 4096;
210 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700211 FileOutputStream foutput = new FileOutputStream(temp);
212 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800213 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700214 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800215 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700216 }
217
218 do {
219 output.write(buffer, 0, read);
220
221 long now = System.currentTimeMillis();
222 if (now - lastTrim > 30 * 1000) {
223 max = trimToFit(); // In case data dribbles in slowly
224 lastTrim = now;
225 }
226
227 read = input.read(buffer);
228 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700229 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700230 output.close(); // Get a final size measurement
231 output = null;
232 } else {
233 output.flush(); // So the size measurement is pseudo-reasonable
234 }
235
236 long len = temp.length();
237 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800238 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700239 temp.delete();
240 temp = null; // Pass temp = null to createEntry() to leave a tombstone
241 break;
242 }
243 } while (read > 0);
244
Hakan Stillb2475362010-12-07 14:05:55 +0100245 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700246 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100247
Craig Mautner26caf7a2012-03-04 17:17:59 -0800248 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
Hakan Stillb2475362010-12-07 14:05:55 +0100249 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
250 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800251 if (!mBooted) {
252 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
253 }
Craig Mautner26caf7a2012-03-04 17:17:59 -0800254 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
255 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
256 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
257 // very lock while waiting for the WindowManagerService lock.
258 mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
Dan Egnor4410ec82009-09-11 16:40:01 -0700259 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800260 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700261 } finally {
262 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700263 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700264 if (temp != null) temp.delete();
265 }
266 }
267
268 public boolean isTagEnabled(String tag) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700269 final long token = Binder.clearCallingIdentity();
270 try {
271 return !"disabled".equals(Settings.Global.getString(
272 mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
273 } finally {
274 Binder.restoreCallingIdentity(token);
275 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700276 }
277
Dan Egnorf18a01c2009-11-12 11:32:50 -0800278 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700279 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
280 != PackageManager.PERMISSION_GRANTED) {
281 throw new SecurityException("READ_LOGS permission required");
282 }
283
284 try {
285 init();
286 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800287 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700288 return null;
289 }
290
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700291 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
292 if (list == null) return null;
293
294 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700295 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800296 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
297 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700298 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700299 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800300 return new DropBoxManager.Entry(
301 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700302 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800303 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700304 // Continue to next file
305 }
306 }
307
308 return null;
309 }
310
311 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
312 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
313 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800314 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700315 return;
316 }
317
318 try {
319 init();
320 } catch (IOException e) {
321 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800322 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700323 return;
324 }
325
Dan Egnor3d40df32009-11-17 13:36:31 -0800326 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
327
Dan Egnor5ec249a2009-11-25 13:16:47 -0800328 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700329 boolean doPrint = false, doFile = false;
330 ArrayList<String> searchArgs = new ArrayList<String>();
331 for (int i = 0; args != null && i < args.length; i++) {
332 if (args[i].equals("-p") || args[i].equals("--print")) {
333 doPrint = true;
334 } else if (args[i].equals("-f") || args[i].equals("--file")) {
335 doFile = true;
336 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800337 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700338 } else {
339 searchArgs.add(args[i]);
340 }
341 }
342
Dan Egnor5ec249a2009-11-25 13:16:47 -0800343 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700344
345 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800346 out.append("Searching for:");
347 for (String a : searchArgs) out.append(" ").append(a);
348 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700349 }
350
Dan Egnor3d40df32009-11-17 13:36:31 -0800351 int numFound = 0, numArgs = searchArgs.size();
352 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800353 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700354 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800355 time.set(entry.timestampMillis);
356 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700357 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800358 for (int i = 0; i < numArgs && match; i++) {
359 String arg = searchArgs.get(i);
360 match = (date.contains(arg) || arg.equals(entry.tag));
361 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700362 if (!match) continue;
363
364 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800365 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800366 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700367 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800368 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700369 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800370 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800371 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700372 continue;
373 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800374 out.append(" (");
375 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
376 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
377 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700378 }
379
Dan Egnorf18a01c2009-11-12 11:32:50 -0800380 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800381 if (!doPrint) out.append(" ");
382 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700383 }
384
Dan Egnorf18a01c2009-11-12 11:32:50 -0800385 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
386 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800387 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700388 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800389 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700390 entry.tag, entry.timestampMillis, entry.file, entry.flags);
391
392 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800393 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700394 char[] buf = new char[4096];
395 boolean newline = false;
396 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800397 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700398 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800399 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700400 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800401
402 // Flush periodically when printing to avoid out-of-memory.
403 if (out.length() > 65536) {
404 pw.write(out.toString());
405 out.setLength(0);
406 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700407 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800408 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700409 } else {
410 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800411 out.append(" ");
412 if (text == null) {
413 out.append("[null]");
414 } else {
415 boolean truncated = (text.length() == 70);
416 out.append(text.trim().replace('\n', '/'));
417 if (truncated) out.append(" ...");
418 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800419 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700420 }
421 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800422 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800423 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700424 } finally {
425 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800426 if (isr != null) {
427 try {
428 isr.close();
429 } catch (IOException unused) {
430 }
431 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700432 }
433 }
434
Dan Egnor5ec249a2009-11-25 13:16:47 -0800435 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700436 }
437
Dan Egnor5ec249a2009-11-25 13:16:47 -0800438 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700439
440 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800441 if (!doPrint) out.append("\n");
442 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700443 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800444
445 pw.write(out.toString());
446 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700447 }
448
449 ///////////////////////////////////////////////////////////////////////////
450
451 /** Chronologically sorted list of {@link #EntryFile} */
452 private static final class FileList implements Comparable<FileList> {
453 public int blocks = 0;
454 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
455
456 /** Sorts bigger FileList instances before smaller ones. */
457 public final int compareTo(FileList o) {
458 if (blocks != o.blocks) return o.blocks - blocks;
459 if (this == o) return 0;
460 if (hashCode() < o.hashCode()) return -1;
461 if (hashCode() > o.hashCode()) return 1;
462 return 0;
463 }
464 }
465
466 /** Metadata describing an on-disk log file. */
467 private static final class EntryFile implements Comparable<EntryFile> {
468 public final String tag;
469 public final long timestampMillis;
470 public final int flags;
471 public final File file;
472 public final int blocks;
473
474 /** Sorts earlier EntryFile instances before later ones. */
475 public final int compareTo(EntryFile o) {
476 if (timestampMillis < o.timestampMillis) return -1;
477 if (timestampMillis > o.timestampMillis) return 1;
478 if (file != null && o.file != null) return file.compareTo(o.file);
479 if (o.file != null) return -1;
480 if (file != null) return 1;
481 if (this == o) return 0;
482 if (hashCode() < o.hashCode()) return -1;
483 if (hashCode() > o.hashCode()) return 1;
484 return 0;
485 }
486
487 /**
488 * Moves an existing temporary file to a new log filename.
489 * @param temp file to rename
490 * @param dir to store file in
491 * @param tag to use for new log file name
492 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700493 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700494 * @param blockSize to use for space accounting
495 * @throws IOException if the file can't be moved
496 */
497 public EntryFile(File temp, File dir, String tag,long timestampMillis,
498 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800499 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700500
501 this.tag = tag;
502 this.timestampMillis = timestampMillis;
503 this.flags = flags;
504 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800505 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
506 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700507
508 if (!temp.renameTo(this.file)) {
509 throw new IOException("Can't rename " + temp + " to " + this.file);
510 }
511 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
512 }
513
514 /**
515 * Creates a zero-length tombstone for a file whose contents were lost.
516 * @param dir to store file in
517 * @param tag to use for new log file name
518 * @param timestampMillis of log entry
519 * @throws IOException if the file can't be created.
520 */
521 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
522 this.tag = tag;
523 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800524 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700525 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
526 this.blocks = 0;
527 new FileOutputStream(this.file).close();
528 }
529
530 /**
531 * Extracts metadata from an existing on-disk log filename.
532 * @param file name of existing log file
533 * @param blockSize to use for space accounting
534 */
535 public EntryFile(File file, int blockSize) {
536 this.file = file;
537 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
538
539 String name = file.getName();
540 int at = name.lastIndexOf('@');
541 if (at < 0) {
542 this.tag = null;
543 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800544 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700545 return;
546 }
547
548 int flags = 0;
549 this.tag = Uri.decode(name.substring(0, at));
550 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800551 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700552 name = name.substring(0, name.length() - 3);
553 }
554 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800555 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700556 name = name.substring(at + 1, name.length() - 5);
557 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800558 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700559 name = name.substring(at + 1, name.length() - 4);
560 } else if (name.endsWith(".dat")) {
561 name = name.substring(at + 1, name.length() - 4);
562 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800563 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700564 this.timestampMillis = 0;
565 return;
566 }
567 this.flags = flags;
568
569 long millis;
570 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
571 this.timestampMillis = millis;
572 }
573
574 /**
575 * Creates a EntryFile object with only a timestamp for comparison purposes.
576 * @param timestampMillis to compare with.
577 */
578 public EntryFile(long millis) {
579 this.tag = null;
580 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800581 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700582 this.file = null;
583 this.blocks = 0;
584 }
585 }
586
587 ///////////////////////////////////////////////////////////////////////////
588
589 /** If never run before, scans disk contents to build in-memory tracking data. */
590 private synchronized void init() throws IOException {
591 if (mStatFs == null) {
592 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
593 throw new IOException("Can't mkdir: " + mDropBoxDir);
594 }
595 try {
596 mStatFs = new StatFs(mDropBoxDir.getPath());
597 mBlockSize = mStatFs.getBlockSize();
598 } catch (IllegalArgumentException e) { // StatFs throws this on error
599 throw new IOException("Can't statfs: " + mDropBoxDir);
600 }
601 }
602
603 if (mAllFiles == null) {
604 File[] files = mDropBoxDir.listFiles();
605 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
606
607 mAllFiles = new FileList();
608 mFilesByTag = new HashMap<String, FileList>();
609
610 // Scan pre-existing files.
611 for (File file : files) {
612 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800613 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700614 file.delete();
615 continue;
616 }
617
618 EntryFile entry = new EntryFile(file, mBlockSize);
619 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800620 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700621 continue;
622 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800623 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700624 file.delete();
625 continue;
626 }
627
628 enrollEntry(entry);
629 }
630 }
631 }
632
633 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
634 private synchronized void enrollEntry(EntryFile entry) {
635 mAllFiles.contents.add(entry);
636 mAllFiles.blocks += entry.blocks;
637
638 // mFilesByTag is used for trimming, so don't list empty files.
639 // (Zero-length/lost files are trimmed by date from mAllFiles.)
640
641 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
642 FileList tagFiles = mFilesByTag.get(entry.tag);
643 if (tagFiles == null) {
644 tagFiles = new FileList();
645 mFilesByTag.put(entry.tag, tagFiles);
646 }
647 tagFiles.contents.add(entry);
648 tagFiles.blocks += entry.blocks;
649 }
650 }
651
652 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100653 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700654 long t = System.currentTimeMillis();
655
656 // Require each entry to have a unique timestamp; if there are entries
657 // >10sec in the future (due to clock skew), drag them back to avoid
658 // keeping them around forever.
659
660 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
661 EntryFile[] future = null;
662 if (!tail.isEmpty()) {
663 future = tail.toArray(new EntryFile[tail.size()]);
664 tail.clear(); // Remove from mAllFiles
665 }
666
667 if (!mAllFiles.contents.isEmpty()) {
668 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
669 }
670
671 if (future != null) {
672 for (EntryFile late : future) {
673 mAllFiles.blocks -= late.blocks;
674 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800675 if (tagFiles != null && tagFiles.contents.remove(late)) {
676 tagFiles.blocks -= late.blocks;
677 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800678 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700679 enrollEntry(new EntryFile(
680 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
681 } else {
682 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
683 }
684 }
685 }
686
687 if (temp == null) {
688 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
689 } else {
690 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
691 }
Hakan Stillb2475362010-12-07 14:05:55 +0100692 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700693 }
694
695 /**
696 * Trims the files on disk to make sure they aren't using too much space.
697 * @return the overall quota for storage (in bytes)
698 */
699 private synchronized long trimToFit() {
700 // Expunge aged items (including tombstones marking deleted data).
701
Jeff Sharkey625239a2012-09-26 22:03:49 -0700702 int ageSeconds = Settings.Global.getInt(mContentResolver,
703 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
704 int maxFiles = Settings.Global.getInt(mContentResolver,
705 Settings.Global.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700706 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
707 while (!mAllFiles.contents.isEmpty()) {
708 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700709 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700710
711 FileList tag = mFilesByTag.get(entry.tag);
712 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
713 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
714 if (entry.file != null) entry.file.delete();
715 }
716
717 // Compute overall quota (a fraction of available free space) in blocks.
718 // The quota changes dynamically based on the amount of free space;
719 // that way when lots of data is available we can use it, but we'll get
720 // out of the way if storage starts getting tight.
721
722 long uptimeMillis = SystemClock.uptimeMillis();
723 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -0700724 int quotaPercent = Settings.Global.getInt(mContentResolver,
725 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
726 int reservePercent = Settings.Global.getInt(mContentResolver,
727 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
728 int quotaKb = Settings.Global.getInt(mContentResolver,
729 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700730
731 mStatFs.restat(mDropBoxDir.getPath());
732 int available = mStatFs.getAvailableBlocks();
733 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
734 int maximum = quotaKb * 1024 / mBlockSize;
735 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
736 mCachedQuotaUptimeMillis = uptimeMillis;
737 }
738
739 // If we're using too much space, delete old items to make room.
740 //
741 // We trim each tag independently (this is why we keep per-tag lists).
742 // Space is "fairly" shared between tags -- they are all squeezed
743 // equally until enough space is reclaimed.
744 //
745 // A single circular buffer (a la logcat) would be simpler, but this
746 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
747 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700748 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700749 //
750 // Deleted files are replaced with zero-length tombstones to mark what
751 // was lost. Tombstones are expunged by age (see above).
752
753 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700754 // Find a fair share amount of space to limit each tag
755 int unsqueezed = mAllFiles.blocks, squeezed = 0;
756 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
757 for (FileList tag : tags) {
758 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
759 break;
760 }
761 unsqueezed -= tag.blocks;
762 squeezed++;
763 }
764 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
765
766 // Remove old items from each tag until it meets the per-tag quota.
767 for (FileList tag : tags) {
768 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
769 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
770 EntryFile entry = tag.contents.first();
771 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
772 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
773
774 try {
775 if (entry.file != null) entry.file.delete();
776 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
777 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800778 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700779 }
780 }
781 }
782 }
783
784 return mCachedQuotaBlocks * mBlockSize;
785 }
786}