blob: 894bca35de83fe8410465dd18e4fa35a58aec1dc [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 Sharkeyfe9a53b2017-03-31 14:08:23 -0600354 if (!DumpUtils.checkDumpPermission(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;
374 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800375 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700376 } else {
377 searchArgs.add(args[i]);
378 }
379 }
380
Dan Egnor5ec249a2009-11-25 13:16:47 -0800381 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700382
383 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800384 out.append("Searching for:");
385 for (String a : searchArgs) out.append(" ").append(a);
386 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700387 }
388
Dan Egnor3d40df32009-11-17 13:36:31 -0800389 int numFound = 0, numArgs = searchArgs.size();
390 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800391 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700392 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800393 time.set(entry.timestampMillis);
394 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700395 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800396 for (int i = 0; i < numArgs && match; i++) {
397 String arg = searchArgs.get(i);
398 match = (date.contains(arg) || arg.equals(entry.tag));
399 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700400 if (!match) continue;
401
402 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800403 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800404 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700405 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800406 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700407 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800408 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800409 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700410 continue;
411 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800412 out.append(" (");
413 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
414 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
415 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700416 }
417
Dan Egnorf18a01c2009-11-12 11:32:50 -0800418 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800419 if (!doPrint) out.append(" ");
420 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700421 }
422
Dan Egnorf18a01c2009-11-12 11:32:50 -0800423 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
424 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800425 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700426 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800427 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700428 entry.tag, entry.timestampMillis, entry.file, entry.flags);
429
430 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800431 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700432 char[] buf = new char[4096];
433 boolean newline = false;
434 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800435 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700436 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800437 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700438 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800439
440 // Flush periodically when printing to avoid out-of-memory.
441 if (out.length() > 65536) {
442 pw.write(out.toString());
443 out.setLength(0);
444 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700445 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800446 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700447 } else {
448 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800449 out.append(" ");
450 if (text == null) {
451 out.append("[null]");
452 } else {
453 boolean truncated = (text.length() == 70);
454 out.append(text.trim().replace('\n', '/'));
455 if (truncated) out.append(" ...");
456 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800457 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700458 }
459 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800460 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800461 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700462 } finally {
463 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800464 if (isr != null) {
465 try {
466 isr.close();
467 } catch (IOException unused) {
468 }
469 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700470 }
471 }
472
Dan Egnor5ec249a2009-11-25 13:16:47 -0800473 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700474 }
475
Dan Egnor5ec249a2009-11-25 13:16:47 -0800476 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700477
478 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800479 if (!doPrint) out.append("\n");
480 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700481 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800482
483 pw.write(out.toString());
484 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700485 }
486
487 ///////////////////////////////////////////////////////////////////////////
488
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700489 /** Chronologically sorted list of {@link EntryFile} */
Dan Egnor4410ec82009-09-11 16:40:01 -0700490 private static final class FileList implements Comparable<FileList> {
491 public int blocks = 0;
492 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
493
494 /** Sorts bigger FileList instances before smaller ones. */
495 public final int compareTo(FileList o) {
496 if (blocks != o.blocks) return o.blocks - blocks;
497 if (this == o) return 0;
498 if (hashCode() < o.hashCode()) return -1;
499 if (hashCode() > o.hashCode()) return 1;
500 return 0;
501 }
502 }
503
504 /** Metadata describing an on-disk log file. */
505 private static final class EntryFile implements Comparable<EntryFile> {
506 public final String tag;
507 public final long timestampMillis;
508 public final int flags;
509 public final File file;
510 public final int blocks;
511
512 /** Sorts earlier EntryFile instances before later ones. */
513 public final int compareTo(EntryFile o) {
514 if (timestampMillis < o.timestampMillis) return -1;
515 if (timestampMillis > o.timestampMillis) return 1;
516 if (file != null && o.file != null) return file.compareTo(o.file);
517 if (o.file != null) return -1;
518 if (file != null) return 1;
519 if (this == o) return 0;
520 if (hashCode() < o.hashCode()) return -1;
521 if (hashCode() > o.hashCode()) return 1;
522 return 0;
523 }
524
525 /**
526 * Moves an existing temporary file to a new log filename.
527 * @param temp file to rename
528 * @param dir to store file in
529 * @param tag to use for new log file name
530 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700531 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700532 * @param blockSize to use for space accounting
533 * @throws IOException if the file can't be moved
534 */
535 public EntryFile(File temp, File dir, String tag,long timestampMillis,
536 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800537 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700538
539 this.tag = tag;
540 this.timestampMillis = timestampMillis;
541 this.flags = flags;
542 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800543 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
544 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700545
546 if (!temp.renameTo(this.file)) {
547 throw new IOException("Can't rename " + temp + " to " + this.file);
548 }
549 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
550 }
551
552 /**
553 * Creates a zero-length tombstone for a file whose contents were lost.
554 * @param dir to store file in
555 * @param tag to use for new log file name
556 * @param timestampMillis of log entry
557 * @throws IOException if the file can't be created.
558 */
559 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
560 this.tag = tag;
561 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800562 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700563 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
564 this.blocks = 0;
565 new FileOutputStream(this.file).close();
566 }
567
568 /**
569 * Extracts metadata from an existing on-disk log filename.
570 * @param file name of existing log file
571 * @param blockSize to use for space accounting
572 */
573 public EntryFile(File file, int blockSize) {
574 this.file = file;
575 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
576
577 String name = file.getName();
578 int at = name.lastIndexOf('@');
579 if (at < 0) {
580 this.tag = null;
581 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800582 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700583 return;
584 }
585
586 int flags = 0;
587 this.tag = Uri.decode(name.substring(0, at));
588 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800589 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700590 name = name.substring(0, name.length() - 3);
591 }
592 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800593 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700594 name = name.substring(at + 1, name.length() - 5);
595 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800596 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700597 name = name.substring(at + 1, name.length() - 4);
598 } else if (name.endsWith(".dat")) {
599 name = name.substring(at + 1, name.length() - 4);
600 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800601 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700602 this.timestampMillis = 0;
603 return;
604 }
605 this.flags = flags;
606
607 long millis;
Tobias Thierer28532d02016-04-21 14:52:10 +0100608 try { millis = Long.parseLong(name); } catch (NumberFormatException e) { millis = 0; }
Dan Egnor4410ec82009-09-11 16:40:01 -0700609 this.timestampMillis = millis;
610 }
611
612 /**
613 * Creates a EntryFile object with only a timestamp for comparison purposes.
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700614 * @param millis to compare with.
Dan Egnor4410ec82009-09-11 16:40:01 -0700615 */
616 public EntryFile(long millis) {
617 this.tag = null;
618 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800619 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700620 this.file = null;
621 this.blocks = 0;
622 }
623 }
624
625 ///////////////////////////////////////////////////////////////////////////
626
627 /** If never run before, scans disk contents to build in-memory tracking data. */
628 private synchronized void init() throws IOException {
629 if (mStatFs == null) {
630 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
631 throw new IOException("Can't mkdir: " + mDropBoxDir);
632 }
633 try {
634 mStatFs = new StatFs(mDropBoxDir.getPath());
635 mBlockSize = mStatFs.getBlockSize();
636 } catch (IllegalArgumentException e) { // StatFs throws this on error
637 throw new IOException("Can't statfs: " + mDropBoxDir);
638 }
639 }
640
641 if (mAllFiles == null) {
642 File[] files = mDropBoxDir.listFiles();
643 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
644
645 mAllFiles = new FileList();
646 mFilesByTag = new HashMap<String, FileList>();
647
648 // Scan pre-existing files.
649 for (File file : files) {
650 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800651 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700652 file.delete();
653 continue;
654 }
655
656 EntryFile entry = new EntryFile(file, mBlockSize);
657 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800658 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700659 continue;
660 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800661 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700662 file.delete();
663 continue;
664 }
665
666 enrollEntry(entry);
667 }
668 }
669 }
670
671 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
672 private synchronized void enrollEntry(EntryFile entry) {
673 mAllFiles.contents.add(entry);
674 mAllFiles.blocks += entry.blocks;
675
676 // mFilesByTag is used for trimming, so don't list empty files.
677 // (Zero-length/lost files are trimmed by date from mAllFiles.)
678
679 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
680 FileList tagFiles = mFilesByTag.get(entry.tag);
681 if (tagFiles == null) {
682 tagFiles = new FileList();
683 mFilesByTag.put(entry.tag, tagFiles);
684 }
685 tagFiles.contents.add(entry);
686 tagFiles.blocks += entry.blocks;
687 }
688 }
689
690 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100691 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700692 long t = System.currentTimeMillis();
693
694 // Require each entry to have a unique timestamp; if there are entries
695 // >10sec in the future (due to clock skew), drag them back to avoid
696 // keeping them around forever.
697
698 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
699 EntryFile[] future = null;
700 if (!tail.isEmpty()) {
701 future = tail.toArray(new EntryFile[tail.size()]);
702 tail.clear(); // Remove from mAllFiles
703 }
704
705 if (!mAllFiles.contents.isEmpty()) {
706 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
707 }
708
709 if (future != null) {
710 for (EntryFile late : future) {
711 mAllFiles.blocks -= late.blocks;
712 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800713 if (tagFiles != null && tagFiles.contents.remove(late)) {
714 tagFiles.blocks -= late.blocks;
715 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800716 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700717 enrollEntry(new EntryFile(
718 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
719 } else {
720 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
721 }
722 }
723 }
724
725 if (temp == null) {
726 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
727 } else {
728 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
729 }
Hakan Stillb2475362010-12-07 14:05:55 +0100730 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700731 }
732
733 /**
734 * Trims the files on disk to make sure they aren't using too much space.
735 * @return the overall quota for storage (in bytes)
736 */
songjinshic5e249b2016-07-27 20:36:46 +0800737 private synchronized long trimToFit() throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700738 // Expunge aged items (including tombstones marking deleted data).
739
Jeff Sharkey625239a2012-09-26 22:03:49 -0700740 int ageSeconds = Settings.Global.getInt(mContentResolver,
741 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
742 int maxFiles = Settings.Global.getInt(mContentResolver,
743 Settings.Global.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700744 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
745 while (!mAllFiles.contents.isEmpty()) {
746 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700747 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700748
749 FileList tag = mFilesByTag.get(entry.tag);
750 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
751 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
752 if (entry.file != null) entry.file.delete();
753 }
754
755 // Compute overall quota (a fraction of available free space) in blocks.
756 // The quota changes dynamically based on the amount of free space;
757 // that way when lots of data is available we can use it, but we'll get
758 // out of the way if storage starts getting tight.
759
760 long uptimeMillis = SystemClock.uptimeMillis();
761 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -0700762 int quotaPercent = Settings.Global.getInt(mContentResolver,
763 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
764 int reservePercent = Settings.Global.getInt(mContentResolver,
765 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
766 int quotaKb = Settings.Global.getInt(mContentResolver,
767 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700768
songjinshic5e249b2016-07-27 20:36:46 +0800769 String dirPath = mDropBoxDir.getPath();
770 try {
771 mStatFs.restat(dirPath);
772 } catch (IllegalArgumentException e) { // restat throws this on error
773 throw new IOException("Can't restat: " + mDropBoxDir);
774 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700775 int available = mStatFs.getAvailableBlocks();
776 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
777 int maximum = quotaKb * 1024 / mBlockSize;
778 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
779 mCachedQuotaUptimeMillis = uptimeMillis;
780 }
781
782 // If we're using too much space, delete old items to make room.
783 //
784 // We trim each tag independently (this is why we keep per-tag lists).
785 // Space is "fairly" shared between tags -- they are all squeezed
786 // equally until enough space is reclaimed.
787 //
788 // A single circular buffer (a la logcat) would be simpler, but this
789 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
790 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700791 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700792 //
793 // Deleted files are replaced with zero-length tombstones to mark what
794 // was lost. Tombstones are expunged by age (see above).
795
796 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700797 // Find a fair share amount of space to limit each tag
798 int unsqueezed = mAllFiles.blocks, squeezed = 0;
799 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
800 for (FileList tag : tags) {
801 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
802 break;
803 }
804 unsqueezed -= tag.blocks;
805 squeezed++;
806 }
807 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
808
809 // Remove old items from each tag until it meets the per-tag quota.
810 for (FileList tag : tags) {
811 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
812 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
813 EntryFile entry = tag.contents.first();
814 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
815 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
816
817 try {
818 if (entry.file != null) entry.file.delete();
819 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
820 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800821 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700822 }
823 }
824 }
825 }
826
827 return mCachedQuotaBlocks * mBlockSize;
828 }
829}