blob: d37c9ab14b77691d1bf8459e00bc00165225a2a2 [file] [log] [blame]
Dan Egnor4410ec82009-09-11 16:40:01 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.pm.PackageManager;
Doug Zongker43866e02010-01-07 12:09:54 -080025import android.database.ContentObserver;
Dan Egnor4410ec82009-09-11 16:40:01 -070026import android.net.Uri;
Dan Egnor3d40df32009-11-17 13:36:31 -080027import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080028import android.os.DropBoxManager;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070029import android.os.FileUtils;
Doug Zongker43866e02010-01-07 12:09:54 -080030import android.os.Handler;
Dan Egnor4410ec82009-09-11 16:40:01 -070031import android.os.StatFs;
32import android.os.SystemClock;
33import android.provider.Settings;
Dan Egnor3d40df32009-11-17 13:36:31 -080034import android.text.format.Time;
Joe Onorato8a9b2202010-02-26 18:56:32 -080035import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070036
Dan Egnorf18a01c2009-11-12 11:32:50 -080037import com.android.internal.os.IDropBoxManagerService;
Dan Egnor95240272009-10-27 18:23:39 -070038
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070039import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070040import java.io.File;
41import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070042import java.io.FileOutputStream;
43import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070044import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070045import java.io.InputStreamReader;
46import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070047import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070048import java.util.ArrayList;
Dan Egnor4410ec82009-09-11 16:40:01 -070049import java.util.HashMap;
Dan Egnor4410ec82009-09-11 16:40:01 -070050import java.util.SortedSet;
51import java.util.TreeSet;
52import java.util.zip.GZIPOutputStream;
53
54/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080055 * Implementation of {@link IDropBoxManagerService} using the filesystem.
56 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070057 */
Dan Egnorf18a01c2009-11-12 11:32:50 -080058public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
59 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070060 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070061 private static final int DEFAULT_MAX_FILES = 1000;
62 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
63 private static final int DEFAULT_QUOTA_PERCENT = 10;
64 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070065 private static final int QUOTA_RESCAN_MILLIS = 5000;
66
Dan Egnor3d40df32009-11-17 13:36:31 -080067 private static final boolean PROFILE_DUMP = false;
68
Dan Egnor4410ec82009-09-11 16:40:01 -070069 // TODO: This implementation currently uses one file per entry, which is
70 // inefficient for smallish entries -- consider using a single queue file
71 // per tag (or even globally) instead.
72
73 // The cached context and derived objects
74
75 private final Context mContext;
76 private final ContentResolver mContentResolver;
77 private final File mDropBoxDir;
78
79 // Accounting of all currently written log files (set in init()).
80
81 private FileList mAllFiles = null;
82 private HashMap<String, FileList> mFilesByTag = null;
83
84 // Various bits of disk information
85
86 private StatFs mStatFs = null;
87 private int mBlockSize = 0;
88 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
89 private long mCachedQuotaUptimeMillis = 0;
90
91 // Ensure that all log entries have a unique timestamp
92 private long mLastTimestamp = 0;
93
Brad Fitzpatrick34165c62011-01-17 18:14:18 -080094 private volatile boolean mBooted = false;
95
Dan Egnor4410ec82009-09-11 16:40:01 -070096 /** Receives events that might indicate a need to clean up files. */
97 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
98 @Override
99 public void onReceive(Context context, Intent intent) {
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800100 if (intent != null && Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
101 mBooted = true;
102 return;
103 }
104
105 // Else, for ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700106 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700107
108 // Run the initialization in the background (not this main thread).
109 // The init() and trimToFit() methods are synchronized, so they still
110 // block other users -- but at least the onReceive() call can finish.
111 new Thread() {
112 public void run() {
113 try {
114 init();
115 trimToFit();
116 } catch (IOException e) {
117 Slog.e(TAG, "Can't init", e);
118 }
119 }
120 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700121 }
122 };
123
124 /**
125 * Creates an instance of managed drop box storage. Normally there is one of these
126 * run by the system, but others can be created for testing and other purposes.
127 *
128 * @param context to use for receiving free space & gservices intents
129 * @param path to store drop box entries in
130 */
Doug Zongker43866e02010-01-07 12:09:54 -0800131 public DropBoxManagerService(final Context context, File path) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700132 mDropBoxDir = path;
133
134 // Set up intent receivers
135 mContext = context;
136 mContentResolver = context.getContentResolver();
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800137
138 IntentFilter filter = new IntentFilter();
139 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
140 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
141 context.registerReceiver(mReceiver, filter);
Doug Zongker43866e02010-01-07 12:09:54 -0800142
143 mContentResolver.registerContentObserver(
144 Settings.Secure.CONTENT_URI, true,
145 new ContentObserver(new Handler()) {
146 public void onChange(boolean selfChange) {
147 mReceiver.onReceive(context, (Intent) null);
148 }
149 });
Dan Egnor4410ec82009-09-11 16:40:01 -0700150
151 // The real work gets done lazily in init() -- that way service creation always
152 // succeeds, and things like disk problems cause individual method failures.
153 }
154
155 /** Unregisters broadcast receivers and any other hooks -- for test instances */
156 public void stop() {
157 mContext.unregisterReceiver(mReceiver);
158 }
159
Dan Egnorf18a01c2009-11-12 11:32:50 -0800160 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700161 File temp = null;
162 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700163 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700164 try {
Dan Egnor95240272009-10-27 18:23:39 -0700165 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800166 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700167
168 init();
169 if (!isTagEnabled(tag)) return;
170 long max = trimToFit();
171 long lastTrim = System.currentTimeMillis();
172
173 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700174 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700175
176 // First, accumulate up to one block worth of data in memory before
177 // deciding whether to compress the data or not.
178
179 int read = 0;
180 while (read < buffer.length) {
181 int n = input.read(buffer, read, buffer.length - read);
182 if (n <= 0) break;
183 read += n;
184 }
185
186 // If we have at least one block, compress it -- otherwise, just write
187 // the data in uncompressed form.
188
189 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700190 int bufferSize = mBlockSize;
191 if (bufferSize > 4096) bufferSize = 4096;
192 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700193 FileOutputStream foutput = new FileOutputStream(temp);
194 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800195 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700196 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800197 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700198 }
199
200 do {
201 output.write(buffer, 0, read);
202
203 long now = System.currentTimeMillis();
204 if (now - lastTrim > 30 * 1000) {
205 max = trimToFit(); // In case data dribbles in slowly
206 lastTrim = now;
207 }
208
209 read = input.read(buffer);
210 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700211 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700212 output.close(); // Get a final size measurement
213 output = null;
214 } else {
215 output.flush(); // So the size measurement is pseudo-reasonable
216 }
217
218 long len = temp.length();
219 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800220 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700221 temp.delete();
222 temp = null; // Pass temp = null to createEntry() to leave a tombstone
223 break;
224 }
225 } while (read > 0);
226
Hakan Stillb2475362010-12-07 14:05:55 +0100227 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700228 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100229
230 Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
231 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
232 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800233 if (!mBooted) {
234 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
235 }
Hakan Stillb2475362010-12-07 14:05:55 +0100236 mContext.sendBroadcast(dropboxIntent, android.Manifest.permission.READ_LOGS);
237
Dan Egnor4410ec82009-09-11 16:40:01 -0700238 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800239 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700240 } finally {
241 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700242 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700243 if (temp != null) temp.delete();
244 }
245 }
246
247 public boolean isTagEnabled(String tag) {
Doug Zongker43866e02010-01-07 12:09:54 -0800248 return !"disabled".equals(Settings.Secure.getString(
249 mContentResolver, Settings.Secure.DROPBOX_TAG_PREFIX + tag));
Dan Egnor4410ec82009-09-11 16:40:01 -0700250 }
251
Dan Egnorf18a01c2009-11-12 11:32:50 -0800252 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700253 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
254 != PackageManager.PERMISSION_GRANTED) {
255 throw new SecurityException("READ_LOGS permission required");
256 }
257
258 try {
259 init();
260 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800261 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700262 return null;
263 }
264
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700265 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
266 if (list == null) return null;
267
268 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700269 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800270 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
271 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700272 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700273 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800274 return new DropBoxManager.Entry(
275 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700276 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800277 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700278 // Continue to next file
279 }
280 }
281
282 return null;
283 }
284
285 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
286 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
287 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800288 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700289 return;
290 }
291
292 try {
293 init();
294 } catch (IOException e) {
295 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800296 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700297 return;
298 }
299
Dan Egnor3d40df32009-11-17 13:36:31 -0800300 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
301
Dan Egnor5ec249a2009-11-25 13:16:47 -0800302 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700303 boolean doPrint = false, doFile = false;
304 ArrayList<String> searchArgs = new ArrayList<String>();
305 for (int i = 0; args != null && i < args.length; i++) {
306 if (args[i].equals("-p") || args[i].equals("--print")) {
307 doPrint = true;
308 } else if (args[i].equals("-f") || args[i].equals("--file")) {
309 doFile = true;
310 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800311 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700312 } else {
313 searchArgs.add(args[i]);
314 }
315 }
316
Dan Egnor5ec249a2009-11-25 13:16:47 -0800317 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700318
319 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800320 out.append("Searching for:");
321 for (String a : searchArgs) out.append(" ").append(a);
322 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700323 }
324
Dan Egnor3d40df32009-11-17 13:36:31 -0800325 int numFound = 0, numArgs = searchArgs.size();
326 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800327 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700328 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800329 time.set(entry.timestampMillis);
330 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700331 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800332 for (int i = 0; i < numArgs && match; i++) {
333 String arg = searchArgs.get(i);
334 match = (date.contains(arg) || arg.equals(entry.tag));
335 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700336 if (!match) continue;
337
338 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800339 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800340 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700341 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800342 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700343 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800344 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800345 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700346 continue;
347 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800348 out.append(" (");
349 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
350 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
351 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700352 }
353
Dan Egnorf18a01c2009-11-12 11:32:50 -0800354 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800355 if (!doPrint) out.append(" ");
356 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700357 }
358
Dan Egnorf18a01c2009-11-12 11:32:50 -0800359 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
360 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800361 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700362 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800363 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700364 entry.tag, entry.timestampMillis, entry.file, entry.flags);
365
366 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800367 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700368 char[] buf = new char[4096];
369 boolean newline = false;
370 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800371 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700372 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800373 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700374 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800375
376 // Flush periodically when printing to avoid out-of-memory.
377 if (out.length() > 65536) {
378 pw.write(out.toString());
379 out.setLength(0);
380 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700381 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800382 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700383 } else {
384 String text = dbe.getText(70);
385 boolean truncated = (text.length() == 70);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800386 out.append(" ").append(text.trim().replace('\n', '/'));
387 if (truncated) out.append(" ...");
388 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700389 }
390 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800391 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800392 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700393 } finally {
394 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800395 if (isr != null) {
396 try {
397 isr.close();
398 } catch (IOException unused) {
399 }
400 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700401 }
402 }
403
Dan Egnor5ec249a2009-11-25 13:16:47 -0800404 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700405 }
406
Dan Egnor5ec249a2009-11-25 13:16:47 -0800407 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700408
409 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800410 if (!doPrint) out.append("\n");
411 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700412 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800413
414 pw.write(out.toString());
415 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700416 }
417
418 ///////////////////////////////////////////////////////////////////////////
419
420 /** Chronologically sorted list of {@link #EntryFile} */
421 private static final class FileList implements Comparable<FileList> {
422 public int blocks = 0;
423 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
424
425 /** Sorts bigger FileList instances before smaller ones. */
426 public final int compareTo(FileList o) {
427 if (blocks != o.blocks) return o.blocks - blocks;
428 if (this == o) return 0;
429 if (hashCode() < o.hashCode()) return -1;
430 if (hashCode() > o.hashCode()) return 1;
431 return 0;
432 }
433 }
434
435 /** Metadata describing an on-disk log file. */
436 private static final class EntryFile implements Comparable<EntryFile> {
437 public final String tag;
438 public final long timestampMillis;
439 public final int flags;
440 public final File file;
441 public final int blocks;
442
443 /** Sorts earlier EntryFile instances before later ones. */
444 public final int compareTo(EntryFile o) {
445 if (timestampMillis < o.timestampMillis) return -1;
446 if (timestampMillis > o.timestampMillis) return 1;
447 if (file != null && o.file != null) return file.compareTo(o.file);
448 if (o.file != null) return -1;
449 if (file != null) return 1;
450 if (this == o) return 0;
451 if (hashCode() < o.hashCode()) return -1;
452 if (hashCode() > o.hashCode()) return 1;
453 return 0;
454 }
455
456 /**
457 * Moves an existing temporary file to a new log filename.
458 * @param temp file to rename
459 * @param dir to store file in
460 * @param tag to use for new log file name
461 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700462 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700463 * @param blockSize to use for space accounting
464 * @throws IOException if the file can't be moved
465 */
466 public EntryFile(File temp, File dir, String tag,long timestampMillis,
467 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800468 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700469
470 this.tag = tag;
471 this.timestampMillis = timestampMillis;
472 this.flags = flags;
473 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800474 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
475 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700476
477 if (!temp.renameTo(this.file)) {
478 throw new IOException("Can't rename " + temp + " to " + this.file);
479 }
480 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
481 }
482
483 /**
484 * Creates a zero-length tombstone for a file whose contents were lost.
485 * @param dir to store file in
486 * @param tag to use for new log file name
487 * @param timestampMillis of log entry
488 * @throws IOException if the file can't be created.
489 */
490 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
491 this.tag = tag;
492 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800493 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700494 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
495 this.blocks = 0;
496 new FileOutputStream(this.file).close();
497 }
498
499 /**
500 * Extracts metadata from an existing on-disk log filename.
501 * @param file name of existing log file
502 * @param blockSize to use for space accounting
503 */
504 public EntryFile(File file, int blockSize) {
505 this.file = file;
506 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
507
508 String name = file.getName();
509 int at = name.lastIndexOf('@');
510 if (at < 0) {
511 this.tag = null;
512 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800513 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700514 return;
515 }
516
517 int flags = 0;
518 this.tag = Uri.decode(name.substring(0, at));
519 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800520 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700521 name = name.substring(0, name.length() - 3);
522 }
523 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800524 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700525 name = name.substring(at + 1, name.length() - 5);
526 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800527 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700528 name = name.substring(at + 1, name.length() - 4);
529 } else if (name.endsWith(".dat")) {
530 name = name.substring(at + 1, name.length() - 4);
531 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800532 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700533 this.timestampMillis = 0;
534 return;
535 }
536 this.flags = flags;
537
538 long millis;
539 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
540 this.timestampMillis = millis;
541 }
542
543 /**
544 * Creates a EntryFile object with only a timestamp for comparison purposes.
545 * @param timestampMillis to compare with.
546 */
547 public EntryFile(long millis) {
548 this.tag = null;
549 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800550 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700551 this.file = null;
552 this.blocks = 0;
553 }
554 }
555
556 ///////////////////////////////////////////////////////////////////////////
557
558 /** If never run before, scans disk contents to build in-memory tracking data. */
559 private synchronized void init() throws IOException {
560 if (mStatFs == null) {
561 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
562 throw new IOException("Can't mkdir: " + mDropBoxDir);
563 }
564 try {
565 mStatFs = new StatFs(mDropBoxDir.getPath());
566 mBlockSize = mStatFs.getBlockSize();
567 } catch (IllegalArgumentException e) { // StatFs throws this on error
568 throw new IOException("Can't statfs: " + mDropBoxDir);
569 }
570 }
571
572 if (mAllFiles == null) {
573 File[] files = mDropBoxDir.listFiles();
574 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
575
576 mAllFiles = new FileList();
577 mFilesByTag = new HashMap<String, FileList>();
578
579 // Scan pre-existing files.
580 for (File file : files) {
581 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800582 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700583 file.delete();
584 continue;
585 }
586
587 EntryFile entry = new EntryFile(file, mBlockSize);
588 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800589 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700590 continue;
591 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800592 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700593 file.delete();
594 continue;
595 }
596
597 enrollEntry(entry);
598 }
599 }
600 }
601
602 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
603 private synchronized void enrollEntry(EntryFile entry) {
604 mAllFiles.contents.add(entry);
605 mAllFiles.blocks += entry.blocks;
606
607 // mFilesByTag is used for trimming, so don't list empty files.
608 // (Zero-length/lost files are trimmed by date from mAllFiles.)
609
610 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
611 FileList tagFiles = mFilesByTag.get(entry.tag);
612 if (tagFiles == null) {
613 tagFiles = new FileList();
614 mFilesByTag.put(entry.tag, tagFiles);
615 }
616 tagFiles.contents.add(entry);
617 tagFiles.blocks += entry.blocks;
618 }
619 }
620
621 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100622 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700623 long t = System.currentTimeMillis();
624
625 // Require each entry to have a unique timestamp; if there are entries
626 // >10sec in the future (due to clock skew), drag them back to avoid
627 // keeping them around forever.
628
629 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
630 EntryFile[] future = null;
631 if (!tail.isEmpty()) {
632 future = tail.toArray(new EntryFile[tail.size()]);
633 tail.clear(); // Remove from mAllFiles
634 }
635
636 if (!mAllFiles.contents.isEmpty()) {
637 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
638 }
639
640 if (future != null) {
641 for (EntryFile late : future) {
642 mAllFiles.blocks -= late.blocks;
643 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800644 if (tagFiles != null && tagFiles.contents.remove(late)) {
645 tagFiles.blocks -= late.blocks;
646 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800647 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700648 enrollEntry(new EntryFile(
649 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
650 } else {
651 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
652 }
653 }
654 }
655
656 if (temp == null) {
657 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
658 } else {
659 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
660 }
Hakan Stillb2475362010-12-07 14:05:55 +0100661 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700662 }
663
664 /**
665 * Trims the files on disk to make sure they aren't using too much space.
666 * @return the overall quota for storage (in bytes)
667 */
668 private synchronized long trimToFit() {
669 // Expunge aged items (including tombstones marking deleted data).
670
Doug Zongker43866e02010-01-07 12:09:54 -0800671 int ageSeconds = Settings.Secure.getInt(mContentResolver,
672 Settings.Secure.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700673 int maxFiles = Settings.Secure.getInt(mContentResolver,
674 Settings.Secure.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700675 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
676 while (!mAllFiles.contents.isEmpty()) {
677 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700678 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700679
680 FileList tag = mFilesByTag.get(entry.tag);
681 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
682 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
683 if (entry.file != null) entry.file.delete();
684 }
685
686 // Compute overall quota (a fraction of available free space) in blocks.
687 // The quota changes dynamically based on the amount of free space;
688 // that way when lots of data is available we can use it, but we'll get
689 // out of the way if storage starts getting tight.
690
691 long uptimeMillis = SystemClock.uptimeMillis();
692 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Doug Zongker43866e02010-01-07 12:09:54 -0800693 int quotaPercent = Settings.Secure.getInt(mContentResolver,
694 Settings.Secure.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
695 int reservePercent = Settings.Secure.getInt(mContentResolver,
696 Settings.Secure.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
697 int quotaKb = Settings.Secure.getInt(mContentResolver,
698 Settings.Secure.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700699
700 mStatFs.restat(mDropBoxDir.getPath());
701 int available = mStatFs.getAvailableBlocks();
702 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
703 int maximum = quotaKb * 1024 / mBlockSize;
704 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
705 mCachedQuotaUptimeMillis = uptimeMillis;
706 }
707
708 // If we're using too much space, delete old items to make room.
709 //
710 // We trim each tag independently (this is why we keep per-tag lists).
711 // Space is "fairly" shared between tags -- they are all squeezed
712 // equally until enough space is reclaimed.
713 //
714 // A single circular buffer (a la logcat) would be simpler, but this
715 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
716 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700717 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700718 //
719 // Deleted files are replaced with zero-length tombstones to mark what
720 // was lost. Tombstones are expunged by age (see above).
721
722 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700723 // Find a fair share amount of space to limit each tag
724 int unsqueezed = mAllFiles.blocks, squeezed = 0;
725 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
726 for (FileList tag : tags) {
727 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
728 break;
729 }
730 unsqueezed -= tag.blocks;
731 squeezed++;
732 }
733 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
734
735 // Remove old items from each tag until it meets the per-tag quota.
736 for (FileList tag : tags) {
737 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
738 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
739 EntryFile entry = tag.contents.first();
740 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
741 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
742
743 try {
744 if (entry.file != null) entry.file.delete();
745 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
746 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800747 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700748 }
749 }
750 }
751 }
752
753 return mCachedQuotaBlocks * mBlockSize;
754 }
755}