blob: 040d22cbe1247cb37971bb0f466ce59ba05e490f [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;
Dan Egnor95240272009-10-27 18:23:39 -070043
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070044import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070045import java.io.File;
46import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070047import java.io.FileOutputStream;
48import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070049import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070050import java.io.InputStreamReader;
51import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070052import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070053import java.util.ArrayList;
Dan Egnor4410ec82009-09-11 16:40:01 -070054import java.util.HashMap;
Dan Egnor4410ec82009-09-11 16:40:01 -070055import java.util.SortedSet;
56import java.util.TreeSet;
57import java.util.zip.GZIPOutputStream;
58
59/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080060 * Implementation of {@link IDropBoxManagerService} using the filesystem.
61 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070062 */
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070063public final class DropBoxManagerService extends SystemService {
Dan Egnorf18a01c2009-11-12 11:32:50 -080064 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070065 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070066 private static final int DEFAULT_MAX_FILES = 1000;
67 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
68 private static final int DEFAULT_QUOTA_PERCENT = 10;
69 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070070 private static final int QUOTA_RESCAN_MILLIS = 5000;
71
Craig Mautner26caf7a2012-03-04 17:17:59 -080072 // mHandler 'what' value.
73 private static final int MSG_SEND_BROADCAST = 1;
74
Dan Egnor3d40df32009-11-17 13:36:31 -080075 private static final boolean PROFILE_DUMP = false;
76
Dan Egnor4410ec82009-09-11 16:40:01 -070077 // TODO: This implementation currently uses one file per entry, which is
78 // inefficient for smallish entries -- consider using a single queue file
79 // per tag (or even globally) instead.
80
81 // The cached context and derived objects
82
Dan Egnor4410ec82009-09-11 16:40:01 -070083 private final ContentResolver mContentResolver;
84 private final File mDropBoxDir;
85
86 // Accounting of all currently written log files (set in init()).
87
88 private FileList mAllFiles = null;
89 private HashMap<String, FileList> mFilesByTag = null;
90
91 // Various bits of disk information
92
93 private StatFs mStatFs = null;
94 private int mBlockSize = 0;
95 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
96 private long mCachedQuotaUptimeMillis = 0;
97
Brad Fitzpatrick34165c62011-01-17 18:14:18 -080098 private volatile boolean mBooted = false;
99
Craig Mautner26caf7a2012-03-04 17:17:59 -0800100 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
101 private final Handler mHandler;
102
Dan Egnor4410ec82009-09-11 16:40:01 -0700103 /** Receives events that might indicate a need to clean up files. */
104 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
105 @Override
106 public void onReceive(Context context, Intent intent) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700107 // For ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700108 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700109
110 // Run the initialization in the background (not this main thread).
111 // The init() and trimToFit() methods are synchronized, so they still
112 // block other users -- but at least the onReceive() call can finish.
113 new Thread() {
114 public void run() {
115 try {
116 init();
117 trimToFit();
118 } catch (IOException e) {
119 Slog.e(TAG, "Can't init", e);
120 }
121 }
122 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700123 }
124 };
125
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700126 private final IDropBoxManagerService.Stub mStub = new IDropBoxManagerService.Stub() {
127 @Override
128 public void add(DropBoxManager.Entry entry) {
129 DropBoxManagerService.this.add(entry);
130 }
131
132 @Override
133 public boolean isTagEnabled(String tag) {
134 return DropBoxManagerService.this.isTagEnabled(tag);
135 }
136
137 @Override
138 public DropBoxManager.Entry getNextEntry(String tag, long millis) {
139 return DropBoxManagerService.this.getNextEntry(tag, millis);
140 }
141
142 @Override
143 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
144 DropBoxManagerService.this.dump(fd, pw, args);
145 }
146 };
147
148 /**
149 * Creates an instance of managed drop box storage using the default dropbox
150 * directory.
151 *
152 * @param context to use for receiving free space & gservices intents
153 */
154 public DropBoxManagerService(final Context context) {
155 this(context, new File("/data/system/dropbox"));
156 }
157
Dan Egnor4410ec82009-09-11 16:40:01 -0700158 /**
159 * Creates an instance of managed drop box storage. Normally there is one of these
160 * run by the system, but others can be created for testing and other purposes.
161 *
162 * @param context to use for receiving free space & gservices intents
163 * @param path to store drop box entries in
164 */
Doug Zongker43866e02010-01-07 12:09:54 -0800165 public DropBoxManagerService(final Context context, File path) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700166 super(context);
Dan Egnor4410ec82009-09-11 16:40:01 -0700167 mDropBoxDir = path;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700168 mContentResolver = getContext().getContentResolver();
169 mHandler = new Handler() {
170 @Override
171 public void handleMessage(Message msg) {
172 if (msg.what == MSG_SEND_BROADCAST) {
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700173 getContext().sendBroadcastAsUser((Intent)msg.obj, UserHandle.SYSTEM,
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700174 android.Manifest.permission.READ_LOGS);
175 }
176 }
177 };
178 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700179
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700180 @Override
181 public void onStart() {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700182 publishBinderService(Context.DROPBOX_SERVICE, mStub);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800183
Dan Egnor4410ec82009-09-11 16:40:01 -0700184 // The real work gets done lazily in init() -- that way service creation always
185 // succeeds, and things like disk problems cause individual method failures.
186 }
187
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700188 @Override
189 public void onBootPhase(int phase) {
190 switch (phase) {
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600191 case PHASE_SYSTEM_SERVICES_READY:
192 IntentFilter filter = new IntentFilter();
193 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
194 getContext().registerReceiver(mReceiver, filter);
195
196 mContentResolver.registerContentObserver(
197 Settings.Global.CONTENT_URI, true,
198 new ContentObserver(new Handler()) {
199 @Override
200 public void onChange(boolean selfChange) {
201 mReceiver.onReceive(getContext(), (Intent) null);
202 }
203 });
204 break;
205
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700206 case PHASE_BOOT_COMPLETED:
207 mBooted = true;
208 break;
209 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700210 }
211
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700212 /** Retrieves the binder stub -- for test instances */
213 public IDropBoxManagerService getServiceStub() {
214 return mStub;
215 }
216
Dan Egnorf18a01c2009-11-12 11:32:50 -0800217 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700218 File temp = null;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700219 InputStream input = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700220 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700221 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700222 try {
Dan Egnor95240272009-10-27 18:23:39 -0700223 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800224 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700225
226 init();
227 if (!isTagEnabled(tag)) return;
228 long max = trimToFit();
229 long lastTrim = System.currentTimeMillis();
230
231 byte[] buffer = new byte[mBlockSize];
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700232 input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700233
234 // First, accumulate up to one block worth of data in memory before
235 // deciding whether to compress the data or not.
236
237 int read = 0;
238 while (read < buffer.length) {
239 int n = input.read(buffer, read, buffer.length - read);
240 if (n <= 0) break;
241 read += n;
242 }
243
244 // If we have at least one block, compress it -- otherwise, just write
245 // the data in uncompressed form.
246
247 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700248 int bufferSize = mBlockSize;
249 if (bufferSize > 4096) bufferSize = 4096;
250 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700251 FileOutputStream foutput = new FileOutputStream(temp);
252 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800253 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700254 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800255 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700256 }
257
258 do {
259 output.write(buffer, 0, read);
260
261 long now = System.currentTimeMillis();
262 if (now - lastTrim > 30 * 1000) {
263 max = trimToFit(); // In case data dribbles in slowly
264 lastTrim = now;
265 }
266
267 read = input.read(buffer);
268 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700269 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700270 output.close(); // Get a final size measurement
271 output = null;
272 } else {
273 output.flush(); // So the size measurement is pseudo-reasonable
274 }
275
276 long len = temp.length();
277 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800278 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700279 temp.delete();
280 temp = null; // Pass temp = null to createEntry() to leave a tombstone
281 break;
282 }
283 } while (read > 0);
284
Hakan Stillb2475362010-12-07 14:05:55 +0100285 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700286 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100287
Craig Mautner26caf7a2012-03-04 17:17:59 -0800288 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
Hakan Stillb2475362010-12-07 14:05:55 +0100289 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
290 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800291 if (!mBooted) {
292 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
293 }
Craig Mautner26caf7a2012-03-04 17:17:59 -0800294 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
295 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
296 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
297 // very lock while waiting for the WindowManagerService lock.
298 mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
Dan Egnor4410ec82009-09-11 16:40:01 -0700299 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800300 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700301 } finally {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700302 IoUtils.closeQuietly(output);
303 IoUtils.closeQuietly(input);
Dan Egnor95240272009-10-27 18:23:39 -0700304 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700305 if (temp != null) temp.delete();
306 }
307 }
308
309 public boolean isTagEnabled(String tag) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700310 final long token = Binder.clearCallingIdentity();
311 try {
312 return !"disabled".equals(Settings.Global.getString(
313 mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
314 } finally {
315 Binder.restoreCallingIdentity(token);
316 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700317 }
318
Dan Egnorf18a01c2009-11-12 11:32:50 -0800319 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700320 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
Dan Egnor4410ec82009-09-11 16:40:01 -0700321 != PackageManager.PERMISSION_GRANTED) {
322 throw new SecurityException("READ_LOGS permission required");
323 }
324
325 try {
326 init();
327 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800328 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700329 return null;
330 }
331
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700332 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
333 if (list == null) return null;
334
335 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700336 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800337 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
338 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700339 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700340 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800341 return new DropBoxManager.Entry(
342 entry.tag, entry.timestampMillis, entry.file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700343 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800344 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700345 // Continue to next file
346 }
347 }
348
349 return null;
350 }
351
352 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700353 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
Dan Egnor4410ec82009-09-11 16:40:01 -0700354 != PackageManager.PERMISSION_GRANTED) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800355 pw.println("Permission Denial: Can't dump DropBoxManagerService");
Dan Egnor4410ec82009-09-11 16:40:01 -0700356 return;
357 }
358
359 try {
360 init();
361 } catch (IOException e) {
362 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800363 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700364 return;
365 }
366
Dan Egnor3d40df32009-11-17 13:36:31 -0800367 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
368
Dan Egnor5ec249a2009-11-25 13:16:47 -0800369 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700370 boolean doPrint = false, doFile = false;
371 ArrayList<String> searchArgs = new ArrayList<String>();
372 for (int i = 0; args != null && i < args.length; i++) {
373 if (args[i].equals("-p") || args[i].equals("--print")) {
374 doPrint = true;
375 } else if (args[i].equals("-f") || args[i].equals("--file")) {
376 doFile = true;
377 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800378 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700379 } else {
380 searchArgs.add(args[i]);
381 }
382 }
383
Dan Egnor5ec249a2009-11-25 13:16:47 -0800384 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700385
386 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800387 out.append("Searching for:");
388 for (String a : searchArgs) out.append(" ").append(a);
389 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700390 }
391
Dan Egnor3d40df32009-11-17 13:36:31 -0800392 int numFound = 0, numArgs = searchArgs.size();
393 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800394 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700395 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800396 time.set(entry.timestampMillis);
397 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700398 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800399 for (int i = 0; i < numArgs && match; i++) {
400 String arg = searchArgs.get(i);
401 match = (date.contains(arg) || arg.equals(entry.tag));
402 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700403 if (!match) continue;
404
405 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800406 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800407 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700408 if (entry.file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800409 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700410 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800411 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800412 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700413 continue;
414 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800415 out.append(" (");
416 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
417 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
418 out.append(", ").append(entry.file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700419 }
420
Dan Egnorf18a01c2009-11-12 11:32:50 -0800421 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800422 if (!doPrint) out.append(" ");
423 out.append(entry.file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700424 }
425
Dan Egnorf18a01c2009-11-12 11:32:50 -0800426 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
427 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800428 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700429 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800430 dbe = new DropBoxManager.Entry(
Dan Egnor4410ec82009-09-11 16:40:01 -0700431 entry.tag, entry.timestampMillis, entry.file, entry.flags);
432
433 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800434 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700435 char[] buf = new char[4096];
436 boolean newline = false;
437 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800438 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700439 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800440 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700441 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800442
443 // Flush periodically when printing to avoid out-of-memory.
444 if (out.length() > 65536) {
445 pw.write(out.toString());
446 out.setLength(0);
447 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700448 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800449 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700450 } else {
451 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800452 out.append(" ");
453 if (text == null) {
454 out.append("[null]");
455 } else {
456 boolean truncated = (text.length() == 70);
457 out.append(text.trim().replace('\n', '/'));
458 if (truncated) out.append(" ...");
459 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800460 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700461 }
462 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800463 out.append("*** ").append(e.toString()).append("\n");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800464 Slog.e(TAG, "Can't read: " + entry.file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700465 } finally {
466 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800467 if (isr != null) {
468 try {
469 isr.close();
470 } catch (IOException unused) {
471 }
472 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700473 }
474 }
475
Dan Egnor5ec249a2009-11-25 13:16:47 -0800476 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700477 }
478
Dan Egnor5ec249a2009-11-25 13:16:47 -0800479 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700480
481 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800482 if (!doPrint) out.append("\n");
483 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700484 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800485
486 pw.write(out.toString());
487 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700488 }
489
490 ///////////////////////////////////////////////////////////////////////////
491
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700492 /** Chronologically sorted list of {@link EntryFile} */
Dan Egnor4410ec82009-09-11 16:40:01 -0700493 private static final class FileList implements Comparable<FileList> {
494 public int blocks = 0;
495 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
496
497 /** Sorts bigger FileList instances before smaller ones. */
498 public final int compareTo(FileList o) {
499 if (blocks != o.blocks) return o.blocks - blocks;
500 if (this == o) return 0;
501 if (hashCode() < o.hashCode()) return -1;
502 if (hashCode() > o.hashCode()) return 1;
503 return 0;
504 }
505 }
506
507 /** Metadata describing an on-disk log file. */
508 private static final class EntryFile implements Comparable<EntryFile> {
509 public final String tag;
510 public final long timestampMillis;
511 public final int flags;
512 public final File file;
513 public final int blocks;
514
515 /** Sorts earlier EntryFile instances before later ones. */
516 public final int compareTo(EntryFile o) {
517 if (timestampMillis < o.timestampMillis) return -1;
518 if (timestampMillis > o.timestampMillis) return 1;
519 if (file != null && o.file != null) return file.compareTo(o.file);
520 if (o.file != null) return -1;
521 if (file != null) return 1;
522 if (this == o) return 0;
523 if (hashCode() < o.hashCode()) return -1;
524 if (hashCode() > o.hashCode()) return 1;
525 return 0;
526 }
527
528 /**
529 * Moves an existing temporary file to a new log filename.
530 * @param temp file to rename
531 * @param dir to store file in
532 * @param tag to use for new log file name
533 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700534 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700535 * @param blockSize to use for space accounting
536 * @throws IOException if the file can't be moved
537 */
538 public EntryFile(File temp, File dir, String tag,long timestampMillis,
539 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800540 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700541
542 this.tag = tag;
543 this.timestampMillis = timestampMillis;
544 this.flags = flags;
545 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
Dan Egnorf18a01c2009-11-12 11:32:50 -0800546 ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
547 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
Dan Egnor4410ec82009-09-11 16:40:01 -0700548
549 if (!temp.renameTo(this.file)) {
550 throw new IOException("Can't rename " + temp + " to " + this.file);
551 }
552 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
553 }
554
555 /**
556 * Creates a zero-length tombstone for a file whose contents were lost.
557 * @param dir to store file in
558 * @param tag to use for new log file name
559 * @param timestampMillis of log entry
560 * @throws IOException if the file can't be created.
561 */
562 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
563 this.tag = tag;
564 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800565 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700566 this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
567 this.blocks = 0;
568 new FileOutputStream(this.file).close();
569 }
570
571 /**
572 * Extracts metadata from an existing on-disk log filename.
573 * @param file name of existing log file
574 * @param blockSize to use for space accounting
575 */
576 public EntryFile(File file, int blockSize) {
577 this.file = file;
578 this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
579
580 String name = file.getName();
581 int at = name.lastIndexOf('@');
582 if (at < 0) {
583 this.tag = null;
584 this.timestampMillis = 0;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800585 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700586 return;
587 }
588
589 int flags = 0;
590 this.tag = Uri.decode(name.substring(0, at));
591 if (name.endsWith(".gz")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800592 flags |= DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700593 name = name.substring(0, name.length() - 3);
594 }
595 if (name.endsWith(".lost")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800596 flags |= DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700597 name = name.substring(at + 1, name.length() - 5);
598 } else if (name.endsWith(".txt")) {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800599 flags |= DropBoxManager.IS_TEXT;
Dan Egnor4410ec82009-09-11 16:40:01 -0700600 name = name.substring(at + 1, name.length() - 4);
601 } else if (name.endsWith(".dat")) {
602 name = name.substring(at + 1, name.length() - 4);
603 } else {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800604 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700605 this.timestampMillis = 0;
606 return;
607 }
608 this.flags = flags;
609
610 long millis;
Tobias Thierer28532d02016-04-21 14:52:10 +0100611 try { millis = Long.parseLong(name); } catch (NumberFormatException e) { millis = 0; }
Dan Egnor4410ec82009-09-11 16:40:01 -0700612 this.timestampMillis = millis;
613 }
614
615 /**
616 * Creates a EntryFile object with only a timestamp for comparison purposes.
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700617 * @param millis to compare with.
Dan Egnor4410ec82009-09-11 16:40:01 -0700618 */
619 public EntryFile(long millis) {
620 this.tag = null;
621 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800622 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700623 this.file = null;
624 this.blocks = 0;
625 }
626 }
627
628 ///////////////////////////////////////////////////////////////////////////
629
630 /** If never run before, scans disk contents to build in-memory tracking data. */
631 private synchronized void init() throws IOException {
632 if (mStatFs == null) {
633 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
634 throw new IOException("Can't mkdir: " + mDropBoxDir);
635 }
636 try {
637 mStatFs = new StatFs(mDropBoxDir.getPath());
638 mBlockSize = mStatFs.getBlockSize();
639 } catch (IllegalArgumentException e) { // StatFs throws this on error
640 throw new IOException("Can't statfs: " + mDropBoxDir);
641 }
642 }
643
644 if (mAllFiles == null) {
645 File[] files = mDropBoxDir.listFiles();
646 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
647
648 mAllFiles = new FileList();
649 mFilesByTag = new HashMap<String, FileList>();
650
651 // Scan pre-existing files.
652 for (File file : files) {
653 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800654 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700655 file.delete();
656 continue;
657 }
658
659 EntryFile entry = new EntryFile(file, mBlockSize);
660 if (entry.tag == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800661 Slog.w(TAG, "Unrecognized file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700662 continue;
663 } else if (entry.timestampMillis == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800664 Slog.w(TAG, "Invalid filename: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700665 file.delete();
666 continue;
667 }
668
669 enrollEntry(entry);
670 }
671 }
672 }
673
674 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
675 private synchronized void enrollEntry(EntryFile entry) {
676 mAllFiles.contents.add(entry);
677 mAllFiles.blocks += entry.blocks;
678
679 // mFilesByTag is used for trimming, so don't list empty files.
680 // (Zero-length/lost files are trimmed by date from mAllFiles.)
681
682 if (entry.tag != null && entry.file != null && entry.blocks > 0) {
683 FileList tagFiles = mFilesByTag.get(entry.tag);
684 if (tagFiles == null) {
685 tagFiles = new FileList();
686 mFilesByTag.put(entry.tag, tagFiles);
687 }
688 tagFiles.contents.add(entry);
689 tagFiles.blocks += entry.blocks;
690 }
691 }
692
693 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100694 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700695 long t = System.currentTimeMillis();
696
697 // Require each entry to have a unique timestamp; if there are entries
698 // >10sec in the future (due to clock skew), drag them back to avoid
699 // keeping them around forever.
700
701 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
702 EntryFile[] future = null;
703 if (!tail.isEmpty()) {
704 future = tail.toArray(new EntryFile[tail.size()]);
705 tail.clear(); // Remove from mAllFiles
706 }
707
708 if (!mAllFiles.contents.isEmpty()) {
709 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
710 }
711
712 if (future != null) {
713 for (EntryFile late : future) {
714 mAllFiles.blocks -= late.blocks;
715 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800716 if (tagFiles != null && tagFiles.contents.remove(late)) {
717 tagFiles.blocks -= late.blocks;
718 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800719 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700720 enrollEntry(new EntryFile(
721 late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
722 } else {
723 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
724 }
725 }
726 }
727
728 if (temp == null) {
729 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
730 } else {
731 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
732 }
Hakan Stillb2475362010-12-07 14:05:55 +0100733 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700734 }
735
736 /**
737 * Trims the files on disk to make sure they aren't using too much space.
738 * @return the overall quota for storage (in bytes)
739 */
songjinshic5e249b2016-07-27 20:36:46 +0800740 private synchronized long trimToFit() throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700741 // Expunge aged items (including tombstones marking deleted data).
742
Jeff Sharkey625239a2012-09-26 22:03:49 -0700743 int ageSeconds = Settings.Global.getInt(mContentResolver,
744 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
745 int maxFiles = Settings.Global.getInt(mContentResolver,
746 Settings.Global.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700747 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
748 while (!mAllFiles.contents.isEmpty()) {
749 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700750 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700751
752 FileList tag = mFilesByTag.get(entry.tag);
753 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
754 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
755 if (entry.file != null) entry.file.delete();
756 }
757
758 // Compute overall quota (a fraction of available free space) in blocks.
759 // The quota changes dynamically based on the amount of free space;
760 // that way when lots of data is available we can use it, but we'll get
761 // out of the way if storage starts getting tight.
762
763 long uptimeMillis = SystemClock.uptimeMillis();
764 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -0700765 int quotaPercent = Settings.Global.getInt(mContentResolver,
766 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
767 int reservePercent = Settings.Global.getInt(mContentResolver,
768 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
769 int quotaKb = Settings.Global.getInt(mContentResolver,
770 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700771
songjinshic5e249b2016-07-27 20:36:46 +0800772 String dirPath = mDropBoxDir.getPath();
773 try {
774 mStatFs.restat(dirPath);
775 } catch (IllegalArgumentException e) { // restat throws this on error
776 throw new IOException("Can't restat: " + mDropBoxDir);
777 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700778 int available = mStatFs.getAvailableBlocks();
779 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
780 int maximum = quotaKb * 1024 / mBlockSize;
781 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
782 mCachedQuotaUptimeMillis = uptimeMillis;
783 }
784
785 // If we're using too much space, delete old items to make room.
786 //
787 // We trim each tag independently (this is why we keep per-tag lists).
788 // Space is "fairly" shared between tags -- they are all squeezed
789 // equally until enough space is reclaimed.
790 //
791 // A single circular buffer (a la logcat) would be simpler, but this
792 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
793 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700794 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700795 //
796 // Deleted files are replaced with zero-length tombstones to mark what
797 // was lost. Tombstones are expunged by age (see above).
798
799 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700800 // Find a fair share amount of space to limit each tag
801 int unsqueezed = mAllFiles.blocks, squeezed = 0;
802 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
803 for (FileList tag : tags) {
804 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
805 break;
806 }
807 unsqueezed -= tag.blocks;
808 squeezed++;
809 }
810 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
811
812 // Remove old items from each tag until it meets the per-tag quota.
813 for (FileList tag : tags) {
814 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
815 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
816 EntryFile entry = tag.contents.first();
817 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
818 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
819
820 try {
821 if (entry.file != null) entry.file.delete();
822 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
823 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800824 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700825 }
826 }
827 }
828 }
829
830 return mCachedQuotaBlocks * mBlockSize;
831 }
832}