blob: 0e451459e0ecafcfa48f0a6246b73f4b258c5227 [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;
Dan Egnor4410ec82009-09-11 16:40:01 -0700346 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800347 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700348 entry.tag, entry.timestampMillis, entry.file, entry.flags);
349
350 if (doPrint) {
351 InputStreamReader r = new InputStreamReader(dbe.getInputStream());
352 char[] buf = new char[4096];
353 boolean newline = false;
354 for (;;) {
355 int n = r.read(buf);
356 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800357 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700358 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800359
360 // Flush periodically when printing to avoid out-of-memory.
361 if (out.length() > 65536) {
362 pw.write(out.toString());
363 out.setLength(0);
364 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700365 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800366 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700367 } else {
368 String text = dbe.getText(70);
369 boolean truncated = (text.length() == 70);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800370 out.append(" ").append(text.trim().replace('\n', '/'));
371 if (truncated) out.append(" ...");
372 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700373 }
374 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800375 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800376 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700377 } finally {
378 if (dbe != null) dbe.close();
379 }
380 }
381
Dan Egnor5ec249a2009-11-25 13:16:47 -0800382 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700383 }
384
Dan Egnor5ec249a2009-11-25 13:16:47 -0800385 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700386
387 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800388 if (!doPrint) out.append("\n");
389 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700390 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800391
392 pw.write(out.toString());
393 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700394 }
395
396 ///////////////////////////////////////////////////////////////////////////
397
398 /** Chronologically sorted list of {@link #EntryFile} */
399 private static final class FileList implements Comparable<FileList> {
400 public int blocks = 0;
401 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
402
403 /** Sorts bigger FileList instances before smaller ones. */
404 public final int compareTo(FileList o) {
405 if (blocks != o.blocks) return o.blocks - blocks;
406 if (this == o) return 0;
407 if (hashCode() < o.hashCode()) return -1;
408 if (hashCode() > o.hashCode()) return 1;
409 return 0;
410 }
411 }
412
413 /** Metadata describing an on-disk log file. */
414 private static final class EntryFile implements Comparable<EntryFile> {
415 public final String tag;
416 public final long timestampMillis;
417 public final int flags;
418 public final File file;
419 public final int blocks;
420
421 /** Sorts earlier EntryFile instances before later ones. */
422 public final int compareTo(EntryFile o) {
423 if (timestampMillis < o.timestampMillis) return -1;
424 if (timestampMillis > o.timestampMillis) return 1;
425 if (file != null && o.file != null) return file.compareTo(o.file);
426 if (o.file != null) return -1;
427 if (file != null) return 1;
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 * Moves an existing temporary file to a new log filename.
436 * @param temp file to rename
437 * @param dir to store file in
438 * @param tag to use for new log file name
439 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700440 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700441 * @param blockSize to use for space accounting
442 * @throws IOException if the file can't be moved
443 */
444 public EntryFile(File temp, File dir, String tag,long timestampMillis,
445 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800446 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700447
448 this.tag = tag;
449 this.timestampMillis = timestampMillis;
450 this.flags = flags;
451 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800452 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
453 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700454
455 if (!temp.renameTo(this.file)) {
456 throw new IOException("Can't rename " + temp + " to " + this.file);
457 }
458 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
459 }
460
461 /**
462 * Creates a zero-length tombstone for a file whose contents were lost.
463 * @param dir to store file in
464 * @param tag to use for new log file name
465 * @param timestampMillis of log entry
466 * @throws IOException if the file can't be created.
467 */
468 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
469 this.tag = tag;
470 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800471 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700472 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
473 this.blocks = 0;
474 new FileOutputStream(this.file).close();
475 }
476
477 /**
478 * Extracts metadata from an existing on-disk log filename.
479 * @param file name of existing log file
480 * @param blockSize to use for space accounting
481 */
482 public EntryFile(File file, int blockSize) {
483 this.file = file;
484 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
485
486 String name = file.getName();
487 int at = name.lastIndexOf('@');
488 if (at < 0) {
489 this.tag = null;
490 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800491 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700492 return;
493 }
494
495 int flags = 0;
496 this.tag = Uri.decode(name.substring(0, at));
497 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800498 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700499 name = name.substring(0, name.length() - 3);
500 }
501 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800502 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700503 name = name.substring(at + 1, name.length() - 5);
504 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800505 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700506 name = name.substring(at + 1, name.length() - 4);
507 } else if (name.endsWith(".dat")) {
508 name = name.substring(at + 1, name.length() - 4);
509 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800510 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700511 this.timestampMillis = 0;
512 return;
513 }
514 this.flags = flags;
515
516 long millis;
517 try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
518 this.timestampMillis = millis;
519 }
520
521 /**
522 * Creates a EntryFile object with only a timestamp for comparison purposes.
523 * @param timestampMillis to compare with.
524 */
525 public EntryFile(long millis) {
526 this.tag = null;
527 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800528 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700529 this.file = null;
530 this.blocks = 0;
531 }
532 }
533
534 ///////////////////////////////////////////////////////////////////////////
535
536 /** If never run before, scans disk contents to build in-memory tracking data. */
537 private synchronized void init() throws IOException {
538 if (mStatFs == null) {
539 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
540 throw new IOException("Can't mkdir: " + mDropBoxDir);
541 }
542 try {
543 mStatFs = new StatFs(mDropBoxDir.getPath());
544 mBlockSize = mStatFs.getBlockSize();
545 } catch (IllegalArgumentException e) { // StatFs throws this on error
546 throw new IOException("Can't statfs: " + mDropBoxDir);
547 }
548 }
549
550 if (mAllFiles == null) {
551 File[] files = mDropBoxDir.listFiles();
552 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
553
554 mAllFiles = new FileList();
555 mFilesByTag = new HashMap<String, FileList>();
556
557 // Scan pre-existing files.
558 for (File file : files) {
559 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800560 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700561 file.delete();
562 continue;
563 }
564
565 EntryFile entry = new EntryFile(file, mBlockSize);
566 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800567 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700568 continue;
569 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800570 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700571 file.delete();
572 continue;
573 }
574
575 enrollEntry(entry);
576 }
577 }
578 }
579
580 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
581 private synchronized void enrollEntry(EntryFile entry) {
582 mAllFiles.contents.add(entry);
583 mAllFiles.blocks += entry.blocks;
584
585 // mFilesByTag is used for trimming, so don't list empty files.
586 // (Zero-length/lost files are trimmed by date from mAllFiles.)
587
588 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
589 FileList tagFiles = mFilesByTag.get(entry.tag);
590 if (tagFiles == null) {
591 tagFiles = new FileList();
592 mFilesByTag.put(entry.tag, tagFiles);
593 }
594 tagFiles.contents.add(entry);
595 tagFiles.blocks += entry.blocks;
596 }
597 }
598
599 /** Moves a temporary file to a final log filename and enrolls it. */
600 private synchronized void createEntry(File temp, String tag, int flags) throws IOException {
601 long t = System.currentTimeMillis();
602
603 // Require each entry to have a unique timestamp; if there are entries
604 // >10sec in the future (due to clock skew), drag them back to avoid
605 // keeping them around forever.
606
607 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
608 EntryFile[] future = null;
609 if (!tail.isEmpty()) {
610 future = tail.toArray(new EntryFile[tail.size()]);
611 tail.clear(); // Remove from mAllFiles
612 }
613
614 if (!mAllFiles.contents.isEmpty()) {
615 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
616 }
617
618 if (future != null) {
619 for (EntryFile late : future) {
620 mAllFiles.blocks -= late.blocks;
621 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800622 if (tagFiles != null && tagFiles.contents.remove(late)) {
623 tagFiles.blocks -= late.blocks;
624 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800625 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700626 enrollEntry(new EntryFile(
627 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
628 } else {
629 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
630 }
631 }
632 }
633
634 if (temp == null) {
635 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
636 } else {
637 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
638 }
639 }
640
641 /**
642 * Trims the files on disk to make sure they aren't using too much space.
643 * @return the overall quota for storage (in bytes)
644 */
645 private synchronized long trimToFit() {
646 // Expunge aged items (including tombstones marking deleted data).
647
Doug Zongker43866e02010-01-07 12:09:54 -0800648 int ageSeconds = Settings.Secure.getInt(mContentResolver,
649 Settings.Secure.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700650 int maxFiles = Settings.Secure.getInt(mContentResolver,
651 Settings.Secure.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700652 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
653 while (!mAllFiles.contents.isEmpty()) {
654 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700655 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700656
657 FileList tag = mFilesByTag.get(entry.tag);
658 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
659 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
660 if (entry.file != null) entry.file.delete();
661 }
662
663 // Compute overall quota (a fraction of available free space) in blocks.
664 // The quota changes dynamically based on the amount of free space;
665 // that way when lots of data is available we can use it, but we'll get
666 // out of the way if storage starts getting tight.
667
668 long uptimeMillis = SystemClock.uptimeMillis();
669 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Doug Zongker43866e02010-01-07 12:09:54 -0800670 int quotaPercent = Settings.Secure.getInt(mContentResolver,
671 Settings.Secure.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
672 int reservePercent = Settings.Secure.getInt(mContentResolver,
673 Settings.Secure.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
674 int quotaKb = Settings.Secure.getInt(mContentResolver,
675 Settings.Secure.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700676
677 mStatFs.restat(mDropBoxDir.getPath());
678 int available = mStatFs.getAvailableBlocks();
679 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
680 int maximum = quotaKb * 1024 / mBlockSize;
681 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
682 mCachedQuotaUptimeMillis = uptimeMillis;
683 }
684
685 // If we're using too much space, delete old items to make room.
686 //
687 // We trim each tag independently (this is why we keep per-tag lists).
688 // Space is "fairly" shared between tags -- they are all squeezed
689 // equally until enough space is reclaimed.
690 //
691 // A single circular buffer (a la logcat) would be simpler, but this
692 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
693 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700694 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700695 //
696 // Deleted files are replaced with zero-length tombstones to mark what
697 // was lost. Tombstones are expunged by age (see above).
698
699 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700700 // Find a fair share amount of space to limit each tag
701 int unsqueezed = mAllFiles.blocks, squeezed = 0;
702 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
703 for (FileList tag : tags) {
704 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
705 break;
706 }
707 unsqueezed -= tag.blocks;
708 squeezed++;
709 }
710 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
711
712 // Remove old items from each tag until it meets the per-tag quota.
713 for (FileList tag : tags) {
714 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
715 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
716 EntryFile entry = tag.contents.first();
717 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
718 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
719
720 try {
721 if (entry.file != null) entry.file.delete();
722 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
723 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800724 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700725 }
726 }
727 }
728 }
729
730 return mCachedQuotaBlocks * mBlockSize;
731 }
732}