blob: e1756d1bf1980b7c4681612b0d186a5a072829dd [file] [log] [blame]
Dan Egnor4410ec82009-09-11 16:40:01 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.pm.PackageManager;
Doug Zongker43866e02010-01-07 12:09:54 -080025import android.database.ContentObserver;
Dan Egnor4410ec82009-09-11 16:40:01 -070026import android.net.Uri;
Jeff Sharkey911d7f42013-09-05 18:11:45 -070027import android.os.Binder;
Dan Egnor3d40df32009-11-17 13:36:31 -080028import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080029import android.os.DropBoxManager;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070030import android.os.FileUtils;
Doug Zongker43866e02010-01-07 12:09:54 -080031import android.os.Handler;
Craig Mautner26caf7a2012-03-04 17:17:59 -080032import android.os.Message;
Dan Egnor4410ec82009-09-11 16:40:01 -070033import android.os.StatFs;
34import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070035import android.os.UserHandle;
Dan Egnor4410ec82009-09-11 16:40:01 -070036import android.provider.Settings;
Dan Egnor3d40df32009-11-17 13:36:31 -080037import android.text.format.Time;
Joe Onorato8a9b2202010-02-26 18:56:32 -080038import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070039
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070040import libcore.io.IoUtils;
41
Dan Egnorf18a01c2009-11-12 11:32:50 -080042import com.android.internal.os.IDropBoxManagerService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060043import com.android.internal.util.DumpUtils;
Dan Egnor95240272009-10-27 18:23:39 -070044
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070045import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070046import java.io.File;
47import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070048import java.io.FileOutputStream;
49import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070050import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070051import java.io.InputStreamReader;
52import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070053import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070054import java.util.ArrayList;
Dan Egnor4410ec82009-09-11 16:40:01 -070055import java.util.HashMap;
Dan Egnor4410ec82009-09-11 16:40:01 -070056import 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 */
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070064public final class DropBoxManagerService extends SystemService {
Dan Egnorf18a01c2009-11-12 11:32:50 -080065 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
Craig Mautner26caf7a2012-03-04 17:17:59 -080073 // mHandler 'what' value.
74 private static final int MSG_SEND_BROADCAST = 1;
75
Dan Egnor3d40df32009-11-17 13:36:31 -080076 private static final boolean PROFILE_DUMP = false;
77
Dan Egnor4410ec82009-09-11 16:40:01 -070078 // TODO: This implementation currently uses one file per entry, which is
79 // inefficient for smallish entries -- consider using a single queue file
80 // per tag (or even globally) instead.
81
82 // The cached context and derived objects
83
Dan Egnor4410ec82009-09-11 16:40:01 -070084 private final ContentResolver mContentResolver;
85 private final File mDropBoxDir;
86
87 // Accounting of all currently written log files (set in init()).
88
89 private FileList mAllFiles = null;
90 private HashMap<String, FileList> mFilesByTag = null;
91
92 // Various bits of disk information
93
94 private StatFs mStatFs = null;
95 private int mBlockSize = 0;
96 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
97 private long mCachedQuotaUptimeMillis = 0;
98
Brad Fitzpatrick34165c62011-01-17 18:14:18 -080099 private volatile boolean mBooted = false;
100
Craig Mautner26caf7a2012-03-04 17:17:59 -0800101 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
102 private final Handler mHandler;
103
Dan Egnor4410ec82009-09-11 16:40:01 -0700104 /** Receives events that might indicate a need to clean up files. */
105 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
106 @Override
107 public void onReceive(Context context, Intent intent) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700108 // For ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700109 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700110
111 // Run the initialization in the background (not this main thread).
112 // The init() and trimToFit() methods are synchronized, so they still
113 // block other users -- but at least the onReceive() call can finish.
114 new Thread() {
115 public void run() {
116 try {
117 init();
118 trimToFit();
119 } catch (IOException e) {
120 Slog.e(TAG, "Can't init", e);
121 }
122 }
123 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700124 }
125 };
126
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700127 private final IDropBoxManagerService.Stub mStub = new IDropBoxManagerService.Stub() {
128 @Override
129 public void add(DropBoxManager.Entry entry) {
130 DropBoxManagerService.this.add(entry);
131 }
132
133 @Override
134 public boolean isTagEnabled(String tag) {
135 return DropBoxManagerService.this.isTagEnabled(tag);
136 }
137
138 @Override
139 public DropBoxManager.Entry getNextEntry(String tag, long millis) {
140 return DropBoxManagerService.this.getNextEntry(tag, millis);
141 }
142
143 @Override
144 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
145 DropBoxManagerService.this.dump(fd, pw, args);
146 }
147 };
148
149 /**
150 * Creates an instance of managed drop box storage using the default dropbox
151 * directory.
152 *
153 * @param context to use for receiving free space & gservices intents
154 */
155 public DropBoxManagerService(final Context context) {
156 this(context, new File("/data/system/dropbox"));
157 }
158
Dan Egnor4410ec82009-09-11 16:40:01 -0700159 /**
160 * Creates an instance of managed drop box storage. Normally there is one of these
161 * run by the system, but others can be created for testing and other purposes.
162 *
163 * @param context to use for receiving free space & gservices intents
164 * @param path to store drop box entries in
165 */
Doug Zongker43866e02010-01-07 12:09:54 -0800166 public DropBoxManagerService(final Context context, File path) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700167 super(context);
Dan Egnor4410ec82009-09-11 16:40:01 -0700168 mDropBoxDir = path;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700169 mContentResolver = getContext().getContentResolver();
170 mHandler = new Handler() {
171 @Override
172 public void handleMessage(Message msg) {
173 if (msg.what == MSG_SEND_BROADCAST) {
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700174 getContext().sendBroadcastAsUser((Intent)msg.obj, UserHandle.SYSTEM,
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700175 android.Manifest.permission.READ_LOGS);
176 }
177 }
178 };
179 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700180
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700181 @Override
182 public void onStart() {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700183 publishBinderService(Context.DROPBOX_SERVICE, mStub);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800184
Dan Egnor4410ec82009-09-11 16:40:01 -0700185 // The real work gets done lazily in init() -- that way service creation always
186 // succeeds, and things like disk problems cause individual method failures.
187 }
188
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700189 @Override
190 public void onBootPhase(int phase) {
191 switch (phase) {
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600192 case PHASE_SYSTEM_SERVICES_READY:
193 IntentFilter filter = new IntentFilter();
194 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
195 getContext().registerReceiver(mReceiver, filter);
196
197 mContentResolver.registerContentObserver(
198 Settings.Global.CONTENT_URI, true,
199 new ContentObserver(new Handler()) {
200 @Override
201 public void onChange(boolean selfChange) {
202 mReceiver.onReceive(getContext(), (Intent) null);
203 }
204 });
205 break;
206
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700207 case PHASE_BOOT_COMPLETED:
208 mBooted = true;
209 break;
210 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700211 }
212
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700213 /** Retrieves the binder stub -- for test instances */
214 public IDropBoxManagerService getServiceStub() {
215 return mStub;
216 }
217
Dan Egnorf18a01c2009-11-12 11:32:50 -0800218 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700219 File temp = null;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700220 InputStream input = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700221 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700222 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700223 try {
Dan Egnor95240272009-10-27 18:23:39 -0700224 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800225 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700226
227 init();
228 if (!isTagEnabled(tag)) return;
229 long max = trimToFit();
230 long lastTrim = System.currentTimeMillis();
231
232 byte[] buffer = new byte[mBlockSize];
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700233 input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700234
235 // First, accumulate up to one block worth of data in memory before
236 // deciding whether to compress the data or not.
237
238 int read = 0;
239 while (read < buffer.length) {
240 int n = input.read(buffer, read, buffer.length - read);
241 if (n <= 0) break;
242 read += n;
243 }
244
245 // If we have at least one block, compress it -- otherwise, just write
246 // the data in uncompressed form.
247
248 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700249 int bufferSize = mBlockSize;
250 if (bufferSize > 4096) bufferSize = 4096;
251 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700252 FileOutputStream foutput = new FileOutputStream(temp);
253 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800254 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700255 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800256 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700257 }
258
259 do {
260 output.write(buffer, 0, read);
261
262 long now = System.currentTimeMillis();
263 if (now - lastTrim > 30 * 1000) {
264 max = trimToFit(); // In case data dribbles in slowly
265 lastTrim = now;
266 }
267
268 read = input.read(buffer);
269 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700270 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700271 output.close(); // Get a final size measurement
272 output = null;
273 } else {
274 output.flush(); // So the size measurement is pseudo-reasonable
275 }
276
277 long len = temp.length();
278 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800279 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700280 temp.delete();
281 temp = null; // Pass temp = null to createEntry() to leave a tombstone
282 break;
283 }
284 } while (read > 0);
285
Hakan Stillb2475362010-12-07 14:05:55 +0100286 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700287 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100288
Craig Mautner26caf7a2012-03-04 17:17:59 -0800289 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
Hakan Stillb2475362010-12-07 14:05:55 +0100290 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
291 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800292 if (!mBooted) {
293 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
294 }
Craig Mautner26caf7a2012-03-04 17:17:59 -0800295 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
296 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
297 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
298 // very lock while waiting for the WindowManagerService lock.
299 mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
Dan Egnor4410ec82009-09-11 16:40:01 -0700300 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800301 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700302 } finally {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700303 IoUtils.closeQuietly(output);
304 IoUtils.closeQuietly(input);
Dan Egnor95240272009-10-27 18:23:39 -0700305 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700306 if (temp != null) temp.delete();
307 }
308 }
309
310 public boolean isTagEnabled(String tag) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700311 final long token = Binder.clearCallingIdentity();
312 try {
313 return !"disabled".equals(Settings.Global.getString(
314 mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
315 } finally {
316 Binder.restoreCallingIdentity(token);
317 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700318 }
319
Dan Egnorf18a01c2009-11-12 11:32:50 -0800320 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700321 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
Dan Egnor4410ec82009-09-11 16:40:01 -0700322 != PackageManager.PERMISSION_GRANTED) {
323 throw new SecurityException("READ_LOGS permission required");
324 }
325
326 try {
327 init();
328 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800329 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700330 return null;
331 }
332
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700333 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
334 if (list == null) return null;
335
336 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700337 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800338 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
339 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700340 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700341 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800342 return new DropBoxManager.Entry(
343 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700344 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800345 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700346 // Continue to next file
347 }
348 }
349
350 return null;
351 }
352
353 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -0600354 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700355
356 try {
357 init();
358 } catch (IOException e) {
359 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800360 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700361 return;
362 }
363
Dan Egnor3d40df32009-11-17 13:36:31 -0800364 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
365
Dan Egnor5ec249a2009-11-25 13:16:47 -0800366 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700367 boolean doPrint = false, doFile = false;
368 ArrayList<String> searchArgs = new ArrayList<String>();
369 for (int i = 0; args != null && i < args.length; i++) {
370 if (args[i].equals("-p") || args[i].equals("--print")) {
371 doPrint = true;
372 } else if (args[i].equals("-f") || args[i].equals("--file")) {
373 doFile = true;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700374 } else if (args[i].equals("-h") || args[i].equals("--help")) {
375 pw.println("Dropbox (dropbox) dump options:");
376 pw.println(" [-h|--help] [-p|--print] [-f|--file] [timestamp]");
377 pw.println(" -h|--help: print this help");
378 pw.println(" -p|--print: print full contents of each entry");
379 pw.println(" -f|--file: print path of each entry's file");
380 pw.println(" [timestamp] optionally filters to only those entries.");
381 return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700382 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800383 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700384 } else {
385 searchArgs.add(args[i]);
386 }
387 }
388
Dan Egnor5ec249a2009-11-25 13:16:47 -0800389 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700390
391 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800392 out.append("Searching for:");
393 for (String a : searchArgs) out.append(" ").append(a);
394 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700395 }
396
Dan Egnor3d40df32009-11-17 13:36:31 -0800397 int numFound = 0, numArgs = searchArgs.size();
398 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800399 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700400 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800401 time.set(entry.timestampMillis);
402 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700403 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800404 for (int i = 0; i < numArgs && match; i++) {
405 String arg = searchArgs.get(i);
406 match = (date.contains(arg) || arg.equals(entry.tag));
407 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700408 if (!match) continue;
409
410 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800411 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800412 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700413 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800414 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700415 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800416 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800417 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700418 continue;
419 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800420 out.append(" (");
421 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
422 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
423 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700424 }
425
Dan Egnorf18a01c2009-11-12 11:32:50 -0800426 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800427 if (!doPrint) out.append(" ");
428 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700429 }
430
Dan Egnorf18a01c2009-11-12 11:32:50 -0800431 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
432 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800433 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700434 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800435 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700436 entry.tag, entry.timestampMillis, entry.file, entry.flags);
437
438 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800439 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700440 char[] buf = new char[4096];
441 boolean newline = false;
442 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800443 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700444 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800445 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700446 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800447
448 // Flush periodically when printing to avoid out-of-memory.
449 if (out.length() > 65536) {
450 pw.write(out.toString());
451 out.setLength(0);
452 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700453 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800454 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700455 } else {
456 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800457 out.append(" ");
458 if (text == null) {
459 out.append("[null]");
460 } else {
461 boolean truncated = (text.length() == 70);
462 out.append(text.trim().replace('\n', '/'));
463 if (truncated) out.append(" ...");
464 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800465 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700466 }
467 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800468 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800469 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700470 } finally {
471 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800472 if (isr != null) {
473 try {
474 isr.close();
475 } catch (IOException unused) {
476 }
477 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700478 }
479 }
480
Dan Egnor5ec249a2009-11-25 13:16:47 -0800481 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700482 }
483
Dan Egnor5ec249a2009-11-25 13:16:47 -0800484 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700485
486 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800487 if (!doPrint) out.append("\n");
488 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700489 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800490
491 pw.write(out.toString());
492 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700493 }
494
495 ///////////////////////////////////////////////////////////////////////////
496
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700497 /** Chronologically sorted list of {@link EntryFile} */
Dan Egnor4410ec82009-09-11 16:40:01 -0700498 private static final class FileList implements Comparable<FileList> {
499 public int blocks = 0;
500 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
501
502 /** Sorts bigger FileList instances before smaller ones. */
503 public final int compareTo(FileList o) {
504 if (blocks != o.blocks) return o.blocks - blocks;
505 if (this == o) return 0;
506 if (hashCode() < o.hashCode()) return -1;
507 if (hashCode() > o.hashCode()) return 1;
508 return 0;
509 }
510 }
511
512 /** Metadata describing an on-disk log file. */
513 private static final class EntryFile implements Comparable<EntryFile> {
514 public final String tag;
515 public final long timestampMillis;
516 public final int flags;
517 public final File file;
518 public final int blocks;
519
520 /** Sorts earlier EntryFile instances before later ones. */
521 public final int compareTo(EntryFile o) {
522 if (timestampMillis < o.timestampMillis) return -1;
523 if (timestampMillis > o.timestampMillis) return 1;
524 if (file != null && o.file != null) return file.compareTo(o.file);
525 if (o.file != null) return -1;
526 if (file != null) return 1;
527 if (this == o) return 0;
528 if (hashCode() < o.hashCode()) return -1;
529 if (hashCode() > o.hashCode()) return 1;
530 return 0;
531 }
532
533 /**
534 * Moves an existing temporary file to a new log filename.
535 * @param temp file to rename
536 * @param dir to store file in
537 * @param tag to use for new log file name
538 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700539 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700540 * @param blockSize to use for space accounting
541 * @throws IOException if the file can't be moved
542 */
543 public EntryFile(File temp, File dir, String tag,long timestampMillis,
544 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800545 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700546
547 this.tag = tag;
548 this.timestampMillis = timestampMillis;
549 this.flags = flags;
550 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800551 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
552 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700553
554 if (!temp.renameTo(this.file)) {
555 throw new IOException("Can't rename " + temp + " to " + this.file);
556 }
557 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
558 }
559
560 /**
561 * Creates a zero-length tombstone for a file whose contents were lost.
562 * @param dir to store file in
563 * @param tag to use for new log file name
564 * @param timestampMillis of log entry
565 * @throws IOException if the file can't be created.
566 */
567 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
568 this.tag = tag;
569 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800570 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700571 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
572 this.blocks = 0;
573 new FileOutputStream(this.file).close();
574 }
575
576 /**
577 * Extracts metadata from an existing on-disk log filename.
578 * @param file name of existing log file
579 * @param blockSize to use for space accounting
580 */
581 public EntryFile(File file, int blockSize) {
582 this.file = file;
583 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
584
585 String name = file.getName();
586 int at = name.lastIndexOf('@');
587 if (at < 0) {
588 this.tag = null;
589 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800590 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700591 return;
592 }
593
594 int flags = 0;
595 this.tag = Uri.decode(name.substring(0, at));
596 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800597 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700598 name = name.substring(0, name.length() - 3);
599 }
600 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800601 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700602 name = name.substring(at + 1, name.length() - 5);
603 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800604 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700605 name = name.substring(at + 1, name.length() - 4);
606 } else if (name.endsWith(".dat")) {
607 name = name.substring(at + 1, name.length() - 4);
608 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800609 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700610 this.timestampMillis = 0;
611 return;
612 }
613 this.flags = flags;
614
615 long millis;
Tobias Thierer28532d02016-04-21 14:52:10 +0100616 try { millis = Long.parseLong(name); } catch (NumberFormatException e) { millis = 0; }
Dan Egnor4410ec82009-09-11 16:40:01 -0700617 this.timestampMillis = millis;
618 }
619
620 /**
621 * Creates a EntryFile object with only a timestamp for comparison purposes.
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700622 * @param millis to compare with.
Dan Egnor4410ec82009-09-11 16:40:01 -0700623 */
624 public EntryFile(long millis) {
625 this.tag = null;
626 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800627 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700628 this.file = null;
629 this.blocks = 0;
630 }
631 }
632
633 ///////////////////////////////////////////////////////////////////////////
634
635 /** If never run before, scans disk contents to build in-memory tracking data. */
636 private synchronized void init() throws IOException {
637 if (mStatFs == null) {
638 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
639 throw new IOException("Can't mkdir: " + mDropBoxDir);
640 }
641 try {
642 mStatFs = new StatFs(mDropBoxDir.getPath());
643 mBlockSize = mStatFs.getBlockSize();
644 } catch (IllegalArgumentException e) { // StatFs throws this on error
645 throw new IOException("Can't statfs: " + mDropBoxDir);
646 }
647 }
648
649 if (mAllFiles == null) {
650 File[] files = mDropBoxDir.listFiles();
651 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
652
653 mAllFiles = new FileList();
654 mFilesByTag = new HashMap<String, FileList>();
655
656 // Scan pre-existing files.
657 for (File file : files) {
658 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800659 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700660 file.delete();
661 continue;
662 }
663
664 EntryFile entry = new EntryFile(file, mBlockSize);
665 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800666 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700667 continue;
668 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800669 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700670 file.delete();
671 continue;
672 }
673
674 enrollEntry(entry);
675 }
676 }
677 }
678
679 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
680 private synchronized void enrollEntry(EntryFile entry) {
681 mAllFiles.contents.add(entry);
682 mAllFiles.blocks += entry.blocks;
683
684 // mFilesByTag is used for trimming, so don't list empty files.
685 // (Zero-length/lost files are trimmed by date from mAllFiles.)
686
687 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
688 FileList tagFiles = mFilesByTag.get(entry.tag);
689 if (tagFiles == null) {
690 tagFiles = new FileList();
691 mFilesByTag.put(entry.tag, tagFiles);
692 }
693 tagFiles.contents.add(entry);
694 tagFiles.blocks += entry.blocks;
695 }
696 }
697
698 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100699 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700700 long t = System.currentTimeMillis();
701
702 // Require each entry to have a unique timestamp; if there are entries
703 // >10sec in the future (due to clock skew), drag them back to avoid
704 // keeping them around forever.
705
706 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
707 EntryFile[] future = null;
708 if (!tail.isEmpty()) {
709 future = tail.toArray(new EntryFile[tail.size()]);
710 tail.clear(); // Remove from mAllFiles
711 }
712
713 if (!mAllFiles.contents.isEmpty()) {
714 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
715 }
716
717 if (future != null) {
718 for (EntryFile late : future) {
719 mAllFiles.blocks -= late.blocks;
720 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800721 if (tagFiles != null && tagFiles.contents.remove(late)) {
722 tagFiles.blocks -= late.blocks;
723 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800724 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700725 enrollEntry(new EntryFile(
726 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
727 } else {
728 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
729 }
730 }
731 }
732
733 if (temp == null) {
734 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
735 } else {
736 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
737 }
Hakan Stillb2475362010-12-07 14:05:55 +0100738 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700739 }
740
741 /**
742 * Trims the files on disk to make sure they aren't using too much space.
743 * @return the overall quota for storage (in bytes)
744 */
songjinshic5e249b2016-07-27 20:36:46 +0800745 private synchronized long trimToFit() throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700746 // Expunge aged items (including tombstones marking deleted data).
747
Jeff Sharkey625239a2012-09-26 22:03:49 -0700748 int ageSeconds = Settings.Global.getInt(mContentResolver,
749 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
750 int maxFiles = Settings.Global.getInt(mContentResolver,
751 Settings.Global.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700752 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
753 while (!mAllFiles.contents.isEmpty()) {
754 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700755 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700756
757 FileList tag = mFilesByTag.get(entry.tag);
758 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
759 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
760 if (entry.file != null) entry.file.delete();
761 }
762
763 // Compute overall quota (a fraction of available free space) in blocks.
764 // The quota changes dynamically based on the amount of free space;
765 // that way when lots of data is available we can use it, but we'll get
766 // out of the way if storage starts getting tight.
767
768 long uptimeMillis = SystemClock.uptimeMillis();
769 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -0700770 int quotaPercent = Settings.Global.getInt(mContentResolver,
771 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
772 int reservePercent = Settings.Global.getInt(mContentResolver,
773 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
774 int quotaKb = Settings.Global.getInt(mContentResolver,
775 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700776
songjinshic5e249b2016-07-27 20:36:46 +0800777 String dirPath = mDropBoxDir.getPath();
778 try {
779 mStatFs.restat(dirPath);
780 } catch (IllegalArgumentException e) { // restat throws this on error
781 throw new IOException("Can't restat: " + mDropBoxDir);
782 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700783 int available = mStatFs.getAvailableBlocks();
784 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
785 int maximum = quotaKb * 1024 / mBlockSize;
786 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
787 mCachedQuotaUptimeMillis = uptimeMillis;
788 }
789
790 // If we're using too much space, delete old items to make room.
791 //
792 // We trim each tag independently (this is why we keep per-tag lists).
793 // Space is "fairly" shared between tags -- they are all squeezed
794 // equally until enough space is reclaimed.
795 //
796 // A single circular buffer (a la logcat) would be simpler, but this
797 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
798 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700799 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700800 //
801 // Deleted files are replaced with zero-length tombstones to mark what
802 // was lost. Tombstones are expunged by age (see above).
803
804 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700805 // Find a fair share amount of space to limit each tag
806 int unsqueezed = mAllFiles.blocks, squeezed = 0;
807 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
808 for (FileList tag : tags) {
809 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
810 break;
811 }
812 unsqueezed -= tag.blocks;
813 squeezed++;
814 }
815 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
816
817 // Remove old items from each tag until it meets the per-tag quota.
818 for (FileList tag : tags) {
819 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
820 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
821 EntryFile entry = tag.contents.first();
822 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
823 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
824
825 try {
826 if (entry.file != null) entry.file.delete();
827 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
828 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800829 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700830 }
831 }
832 }
833 }
834
835 return mCachedQuotaBlocks * mBlockSize;
836 }
837}