blob: 0a28da7542f0cce25be16225ee686b5657d186e9 [file] [log] [blame]
Dan Egnor4410ec82009-09-11 16:40:01 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.pm.PackageManager;
Doug Zongker43866e02010-01-07 12:09:54 -080025import android.database.ContentObserver;
Dan Egnor4410ec82009-09-11 16:40:01 -070026import android.net.Uri;
Dan Egnor3d40df32009-11-17 13:36:31 -080027import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080028import android.os.DropBoxManager;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070029import android.os.FileUtils;
Doug Zongker43866e02010-01-07 12:09:54 -080030import android.os.Handler;
Dan Egnor4410ec82009-09-11 16:40:01 -070031import android.os.ParcelFileDescriptor;
32import android.os.StatFs;
33import android.os.SystemClock;
34import android.provider.Settings;
Dan Egnor3d40df32009-11-17 13:36:31 -080035import android.text.format.Time;
Joe Onorato8a9b2202010-02-26 18:56:32 -080036import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070037
Dan Egnorf18a01c2009-11-12 11:32:50 -080038import com.android.internal.os.IDropBoxManagerService;
Dan Egnor95240272009-10-27 18:23:39 -070039
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070040import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070041import java.io.File;
42import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070043import java.io.FileOutputStream;
44import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070045import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070046import java.io.InputStreamReader;
47import java.io.OutputStream;
48import java.io.OutputStreamWriter;
49import java.io.PrintWriter;
50import java.io.UnsupportedEncodingException;
51import java.util.ArrayList;
52import java.util.Comparator;
Dan Egnor4410ec82009-09-11 16:40:01 -070053import java.util.HashMap;
54import java.util.Iterator;
55import java.util.Map;
56import java.util.SortedSet;
57import java.util.TreeSet;
58import java.util.zip.GZIPOutputStream;
59
60/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080061 * Implementation of {@link IDropBoxManagerService} using the filesystem.
62 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070063 */
Dan Egnorf18a01c2009-11-12 11:32:50 -080064public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
65 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070066 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070067 private static final int DEFAULT_MAX_FILES = 1000;
68 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
69 private static final int DEFAULT_QUOTA_PERCENT = 10;
70 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070071 private static final int QUOTA_RESCAN_MILLIS = 5000;
72
Dan Egnor3d40df32009-11-17 13:36:31 -080073 private static final boolean PROFILE_DUMP = false;
74
Dan Egnor4410ec82009-09-11 16:40:01 -070075 // TODO: This implementation currently uses one file per entry, which is
76 // inefficient for smallish entries -- consider using a single queue file
77 // per tag (or even globally) instead.
78
79 // The cached context and derived objects
80
81 private final Context mContext;
82 private final ContentResolver mContentResolver;
83 private final File mDropBoxDir;
84
85 // Accounting of all currently written log files (set in init()).
86
87 private FileList mAllFiles = null;
88 private HashMap<String, FileList> mFilesByTag = null;
89
90 // Various bits of disk information
91
92 private StatFs mStatFs = null;
93 private int mBlockSize = 0;
94 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
95 private long mCachedQuotaUptimeMillis = 0;
96
97 // Ensure that all log entries have a unique timestamp
98 private long mLastTimestamp = 0;
99
100 /** Receives events that might indicate a need to clean up files. */
101 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
102 @Override
103 public void onReceive(Context context, Intent intent) {
104 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700105
106 // Run the initialization in the background (not this main thread).
107 // The init() and trimToFit() methods are synchronized, so they still
108 // block other users -- but at least the onReceive() call can finish.
109 new Thread() {
110 public void run() {
111 try {
112 init();
113 trimToFit();
114 } catch (IOException e) {
115 Slog.e(TAG, "Can't init", e);
116 }
117 }
118 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700119 }
120 };
121
122 /**
123 * Creates an instance of managed drop box storage. Normally there is one of these
124 * run by the system, but others can be created for testing and other purposes.
125 *
126 * @param context to use for receiving free space & gservices intents
127 * @param path to store drop box entries in
128 */
Doug Zongker43866e02010-01-07 12:09:54 -0800129 public DropBoxManagerService(final Context context, File path) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700130 mDropBoxDir = path;
131
132 // Set up intent receivers
133 mContext = context;
134 mContentResolver = context.getContentResolver();
135 context.registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW));
Doug Zongker43866e02010-01-07 12:09:54 -0800136
137 mContentResolver.registerContentObserver(
138 Settings.Secure.CONTENT_URI, true,
139 new ContentObserver(new Handler()) {
140 public void onChange(boolean selfChange) {
141 mReceiver.onReceive(context, (Intent) null);
142 }
143 });
Dan Egnor4410ec82009-09-11 16:40:01 -0700144
145 // The real work gets done lazily in init() -- that way service creation always
146 // succeeds, and things like disk problems cause individual method failures.
147 }
148
149 /** Unregisters broadcast receivers and any other hooks -- for test instances */
150 public void stop() {
151 mContext.unregisterReceiver(mReceiver);
152 }
153
Dan Egnorf18a01c2009-11-12 11:32:50 -0800154 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700155 File temp = null;
156 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700157 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700158 try {
Dan Egnor95240272009-10-27 18:23:39 -0700159 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800160 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700161
162 init();
163 if (!isTagEnabled(tag)) return;
164 long max = trimToFit();
165 long lastTrim = System.currentTimeMillis();
166
167 byte[] buffer = new byte[mBlockSize];
Dan Egnor95240272009-10-27 18:23:39 -0700168 InputStream input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700169
170 // First, accumulate up to one block worth of data in memory before
171 // deciding whether to compress the data or not.
172
173 int read = 0;
174 while (read < buffer.length) {
175 int n = input.read(buffer, read, buffer.length - read);
176 if (n <= 0) break;
177 read += n;
178 }
179
180 // If we have at least one block, compress it -- otherwise, just write
181 // the data in uncompressed form.
182
183 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700184 int bufferSize = mBlockSize;
185 if (bufferSize > 4096) bufferSize = 4096;
186 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700187 FileOutputStream foutput = new FileOutputStream(temp);
188 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800189 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700190 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800191 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700192 }
193
194 do {
195 output.write(buffer, 0, read);
196
197 long now = System.currentTimeMillis();
198 if (now - lastTrim > 30 * 1000) {
199 max = trimToFit(); // In case data dribbles in slowly
200 lastTrim = now;
201 }
202
203 read = input.read(buffer);
204 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700205 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700206 output.close(); // Get a final size measurement
207 output = null;
208 } else {
209 output.flush(); // So the size measurement is pseudo-reasonable
210 }
211
212 long len = temp.length();
213 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800214 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700215 temp.delete();
216 temp = null; // Pass temp = null to createEntry() to leave a tombstone
217 break;
218 }
219 } while (read > 0);
220
221 createEntry(temp, tag, flags);
222 temp = null;
223 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800224 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700225 } finally {
226 try { if (output != null) output.close(); } catch (IOException e) {}
Dan Egnor95240272009-10-27 18:23:39 -0700227 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700228 if (temp != null) temp.delete();
229 }
230 }
231
232 public boolean isTagEnabled(String tag) {
Doug Zongker43866e02010-01-07 12:09:54 -0800233 return !"disabled".equals(Settings.Secure.getString(
234 mContentResolver, Settings.Secure.DROPBOX_TAG_PREFIX + tag));
Dan Egnor4410ec82009-09-11 16:40:01 -0700235 }
236
Dan Egnorf18a01c2009-11-12 11:32:50 -0800237 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700238 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
239 != PackageManager.PERMISSION_GRANTED) {
240 throw new SecurityException("READ_LOGS permission required");
241 }
242
243 try {
244 init();
245 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800246 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700247 return null;
248 }
249
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700250 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
251 if (list == null) return null;
252
253 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700254 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800255 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
256 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700257 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700258 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800259 return new DropBoxManager.Entry(
260 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700261 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800262 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700263 // Continue to next file
264 }
265 }
266
267 return null;
268 }
269
270 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
271 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
272 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800273 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700274 return;
275 }
276
277 try {
278 init();
279 } catch (IOException e) {
280 pw.println("Can't initialize: " + 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;
283 }
284
Dan Egnor3d40df32009-11-17 13:36:31 -0800285 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
286
Dan Egnor5ec249a2009-11-25 13:16:47 -0800287 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700288 boolean doPrint = false, doFile = false;
289 ArrayList<String> searchArgs = new ArrayList<String>();
290 for (int i = 0; args != null && i < args.length; i++) {
291 if (args[i].equals("-p") || args[i].equals("--print")) {
292 doPrint = true;
293 } else if (args[i].equals("-f") || args[i].equals("--file")) {
294 doFile = true;
295 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800296 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700297 } else {
298 searchArgs.add(args[i]);
299 }
300 }
301
Dan Egnor5ec249a2009-11-25 13:16:47 -0800302 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700303
304 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800305 out.append("Searching for:");
306 for (String a : searchArgs) out.append(" ").append(a);
307 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700308 }
309
Dan Egnor3d40df32009-11-17 13:36:31 -0800310 int numFound = 0, numArgs = searchArgs.size();
311 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800312 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700313 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800314 time.set(entry.timestampMillis);
315 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700316 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800317 for (int i = 0; i < numArgs && match; i++) {
318 String arg = searchArgs.get(i);
319 match = (date.contains(arg) || arg.equals(entry.tag));
320 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700321 if (!match) continue;
322
323 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800324 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800325 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700326 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800327 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700328 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800329 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800330 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700331 continue;
332 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800333 out.append(" (");
334 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
335 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
336 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700337 }
338
Dan Egnorf18a01c2009-11-12 11:32:50 -0800339 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800340 if (!doPrint) out.append(" ");
341 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700342 }
343
Dan Egnorf18a01c2009-11-12 11:32:50 -0800344 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
345 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800346 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700347 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800348 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700349 entry.tag, entry.timestampMillis, entry.file, entry.flags);
350
351 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800352 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700353 char[] buf = new char[4096];
354 boolean newline = false;
355 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800356 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700357 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800358 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700359 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800360
361 // Flush periodically when printing to avoid out-of-memory.
362 if (out.length() > 65536) {
363 pw.write(out.toString());
364 out.setLength(0);
365 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700366 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800367 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700368 } else {
369 String text = dbe.getText(70);
370 boolean truncated = (text.length() == 70);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800371 out.append(" ").append(text.trim().replace('\n', '/'));
372 if (truncated) out.append(" ...");
373 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700374 }
375 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800376 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800377 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700378 } finally {
379 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800380 if (isr != null) {
381 try {
382 isr.close();
383 } catch (IOException unused) {
384 }
385 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700386 }
387 }
388
Dan Egnor5ec249a2009-11-25 13:16:47 -0800389 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700390 }
391
Dan Egnor5ec249a2009-11-25 13:16:47 -0800392 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700393
394 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800395 if (!doPrint) out.append("\n");
396 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700397 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800398
399 pw.write(out.toString());
400 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700401 }
402
403 ///////////////////////////////////////////////////////////////////////////
404
405 /** Chronologically sorted list of {@link #EntryFile} */
406 private static final class FileList implements Comparable<FileList> {
407 public int blocks = 0;
408 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
409
410 /** Sorts bigger FileList instances before smaller ones. */
411 public final int compareTo(FileList o) {
412 if (blocks != o.blocks) return o.blocks - blocks;
413 if (this == o) return 0;
414 if (hashCode() < o.hashCode()) return -1;
415 if (hashCode() > o.hashCode()) return 1;
416 return 0;
417 }
418 }
419
420 /** Metadata describing an on-disk log file. */
421 private static final class EntryFile implements Comparable<EntryFile> {
422 public final String tag;
423 public final long timestampMillis;
424 public final int flags;
425 public final File file;
426 public final int blocks;
427
428 /** Sorts earlier EntryFile instances before later ones. */
429 public final int compareTo(EntryFile o) {
430 if (timestampMillis < o.timestampMillis) return -1;
431 if (timestampMillis > o.timestampMillis) return 1;
432 if (file != null && o.file != null) return file.compareTo(o.file);
433 if (o.file != null) return -1;
434 if (file != null) return 1;
435 if (this == o) return 0;
436 if (hashCode() < o.hashCode()) return -1;
437 if (hashCode() > o.hashCode()) return 1;
438 return 0;
439 }
440
441 /**
442 * Moves an existing temporary file to a new log filename.
443 * @param temp file to rename
444 * @param dir to store file in
445 * @param tag to use for new log file name
446 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700447 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700448 * @param blockSize to use for space accounting
449 * @throws IOException if the file can't be moved
450 */
451 public EntryFile(File temp, File dir, String tag,long timestampMillis,
452 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800453 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700454
455 this.tag = tag;
456 this.timestampMillis = timestampMillis;
457 this.flags = flags;
458 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800459 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
460 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700461
462 if (!temp.renameTo(this.file)) {
463 throw new IOException("Can't rename " + temp + " to " + this.file);
464 }
465 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
466 }
467
468 /**
469 * Creates a zero-length tombstone for a file whose contents were lost.
470 * @param dir to store file in
471 * @param tag to use for new log file name
472 * @param timestampMillis of log entry
473 * @throws IOException if the file can't be created.
474 */
475 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
476 this.tag = tag;
477 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800478 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700479 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
480 this.blocks = 0;
481 new FileOutputStream(this.file).close();
482 }
483
484 /**
485 * Extracts metadata from an existing on-disk log filename.
486 * @param file name of existing log file
487 * @param blockSize to use for space accounting
488 */
489 public EntryFile(File file, int blockSize) {
490 this.file = file;
491 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
492
493 String name = file.getName();
494 int at = name.lastIndexOf('@');
495 if (at < 0) {
496 this.tag = null;
497 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800498 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700499 return;
500 }
501
502 int flags = 0;
503 this.tag = Uri.decode(name.substring(0, at));
504 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800505 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700506 name = name.substring(0, name.length() - 3);
507 }
508 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800509 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700510 name = name.substring(at + 1, name.length() - 5);
511 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800512 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700513 name = name.substring(at + 1, name.length() - 4);
514 } else if (name.endsWith(".dat")) {
515 name = name.substring(at + 1, name.length() - 4);
516 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800517 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700518 this.timestampMillis = 0;
519 return;
520 }
521 this.flags = flags;
522
523 long millis;
524 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
525 this.timestampMillis = millis;
526 }
527
528 /**
529 * Creates a EntryFile object with only a timestamp for comparison purposes.
530 * @param timestampMillis to compare with.
531 */
532 public EntryFile(long millis) {
533 this.tag = null;
534 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800535 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700536 this.file = null;
537 this.blocks = 0;
538 }
539 }
540
541 ///////////////////////////////////////////////////////////////////////////
542
543 /** If never run before, scans disk contents to build in-memory tracking data. */
544 private synchronized void init() throws IOException {
545 if (mStatFs == null) {
546 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
547 throw new IOException("Can't mkdir: " + mDropBoxDir);
548 }
549 try {
550 mStatFs = new StatFs(mDropBoxDir.getPath());
551 mBlockSize = mStatFs.getBlockSize();
552 } catch (IllegalArgumentException e) { // StatFs throws this on error
553 throw new IOException("Can't statfs: " + mDropBoxDir);
554 }
555 }
556
557 if (mAllFiles == null) {
558 File[] files = mDropBoxDir.listFiles();
559 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
560
561 mAllFiles = new FileList();
562 mFilesByTag = new HashMap<String, FileList>();
563
564 // Scan pre-existing files.
565 for (File file : files) {
566 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800567 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700568 file.delete();
569 continue;
570 }
571
572 EntryFile entry = new EntryFile(file, mBlockSize);
573 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800574 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700575 continue;
576 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800577 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700578 file.delete();
579 continue;
580 }
581
582 enrollEntry(entry);
583 }
584 }
585 }
586
587 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
588 private synchronized void enrollEntry(EntryFile entry) {
589 mAllFiles.contents.add(entry);
590 mAllFiles.blocks += entry.blocks;
591
592 // mFilesByTag is used for trimming, so don't list empty files.
593 // (Zero-length/lost files are trimmed by date from mAllFiles.)
594
595 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
596 FileList tagFiles = mFilesByTag.get(entry.tag);
597 if (tagFiles == null) {
598 tagFiles = new FileList();
599 mFilesByTag.put(entry.tag, tagFiles);
600 }
601 tagFiles.contents.add(entry);
602 tagFiles.blocks += entry.blocks;
603 }
604 }
605
606 /** Moves a temporary file to a final log filename and enrolls it. */
607 private synchronized void createEntry(File temp, String tag, int flags) throws IOException {
608 long t = System.currentTimeMillis();
609
610 // Require each entry to have a unique timestamp; if there are entries
611 // >10sec in the future (due to clock skew), drag them back to avoid
612 // keeping them around forever.
613
614 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
615 EntryFile[] future = null;
616 if (!tail.isEmpty()) {
617 future = tail.toArray(new EntryFile[tail.size()]);
618 tail.clear(); // Remove from mAllFiles
619 }
620
621 if (!mAllFiles.contents.isEmpty()) {
622 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
623 }
624
625 if (future != null) {
626 for (EntryFile late : future) {
627 mAllFiles.blocks -= late.blocks;
628 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800629 if (tagFiles != null && tagFiles.contents.remove(late)) {
630 tagFiles.blocks -= late.blocks;
631 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800632 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700633 enrollEntry(new EntryFile(
634 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
635 } else {
636 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
637 }
638 }
639 }
640
641 if (temp == null) {
642 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
643 } else {
644 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
645 }
646 }
647
648 /**
649 * Trims the files on disk to make sure they aren't using too much space.
650 * @return the overall quota for storage (in bytes)
651 */
652 private synchronized long trimToFit() {
653 // Expunge aged items (including tombstones marking deleted data).
654
Doug Zongker43866e02010-01-07 12:09:54 -0800655 int ageSeconds = Settings.Secure.getInt(mContentResolver,
656 Settings.Secure.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700657 int maxFiles = Settings.Secure.getInt(mContentResolver,
658 Settings.Secure.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700659 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
660 while (!mAllFiles.contents.isEmpty()) {
661 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700662 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700663
664 FileList tag = mFilesByTag.get(entry.tag);
665 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
666 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
667 if (entry.file != null) entry.file.delete();
668 }
669
670 // Compute overall quota (a fraction of available free space) in blocks.
671 // The quota changes dynamically based on the amount of free space;
672 // that way when lots of data is available we can use it, but we'll get
673 // out of the way if storage starts getting tight.
674
675 long uptimeMillis = SystemClock.uptimeMillis();
676 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Doug Zongker43866e02010-01-07 12:09:54 -0800677 int quotaPercent = Settings.Secure.getInt(mContentResolver,
678 Settings.Secure.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
679 int reservePercent = Settings.Secure.getInt(mContentResolver,
680 Settings.Secure.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
681 int quotaKb = Settings.Secure.getInt(mContentResolver,
682 Settings.Secure.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700683
684 mStatFs.restat(mDropBoxDir.getPath());
685 int available = mStatFs.getAvailableBlocks();
686 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
687 int maximum = quotaKb * 1024 / mBlockSize;
688 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
689 mCachedQuotaUptimeMillis = uptimeMillis;
690 }
691
692 // If we're using too much space, delete old items to make room.
693 //
694 // We trim each tag independently (this is why we keep per-tag lists).
695 // Space is "fairly" shared between tags -- they are all squeezed
696 // equally until enough space is reclaimed.
697 //
698 // A single circular buffer (a la logcat) would be simpler, but this
699 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
700 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700701 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700702 //
703 // Deleted files are replaced with zero-length tombstones to mark what
704 // was lost. Tombstones are expunged by age (see above).
705
706 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700707 // Find a fair share amount of space to limit each tag
708 int unsqueezed = mAllFiles.blocks, squeezed = 0;
709 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
710 for (FileList tag : tags) {
711 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
712 break;
713 }
714 unsqueezed -= tag.blocks;
715 squeezed++;
716 }
717 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
718
719 // Remove old items from each tag until it meets the per-tag quota.
720 for (FileList tag : tags) {
721 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
722 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
723 EntryFile entry = tag.contents.first();
724 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
725 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
726
727 try {
728 if (entry.file != null) entry.file.delete();
729 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
730 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800731 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700732 }
733 }
734 }
735 }
736
737 return mCachedQuotaBlocks * mBlockSize;
738 }
739}