blob: 1bf12c4f86f0c78ee55f8480711ab372913bd4ab [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;
Makoto Onukiff94e032017-08-08 14:58:19 -070032import android.os.Looper;
Craig Mautner26caf7a2012-03-04 17:17:59 -080033import android.os.Message;
Dan Egnor4410ec82009-09-11 16:40:01 -070034import android.os.StatFs;
35import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070036import android.os.UserHandle;
Dan Egnor4410ec82009-09-11 16:40:01 -070037import android.provider.Settings;
Makoto Onukiff94e032017-08-08 14:58:19 -070038import android.text.TextUtils;
Dan Egnor3d40df32009-11-17 13:36:31 -080039import android.text.format.Time;
Makoto Onukiff94e032017-08-08 14:58:19 -070040import android.util.ArrayMap;
Joe Onorato8a9b2202010-02-26 18:56:32 -080041import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070042
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070043import libcore.io.IoUtils;
44
Makoto Onukiff94e032017-08-08 14:58:19 -070045import com.android.internal.annotations.VisibleForTesting;
Dan Egnorf18a01c2009-11-12 11:32:50 -080046import com.android.internal.os.IDropBoxManagerService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060047import com.android.internal.util.DumpUtils;
Makoto Onukiff94e032017-08-08 14:58:19 -070048import com.android.internal.util.ObjectUtils;
Dan Egnor95240272009-10-27 18:23:39 -070049
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070050import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070051import java.io.File;
52import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070053import java.io.FileOutputStream;
54import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070055import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070056import java.io.InputStreamReader;
57import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070058import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070059import java.util.ArrayList;
Makoto Onukiff94e032017-08-08 14:58:19 -070060import java.util.Objects;
Dan Egnor4410ec82009-09-11 16:40:01 -070061import java.util.SortedSet;
62import java.util.TreeSet;
63import java.util.zip.GZIPOutputStream;
64
65/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080066 * Implementation of {@link IDropBoxManagerService} using the filesystem.
67 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070068 */
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070069public final class DropBoxManagerService extends SystemService {
Dan Egnorf18a01c2009-11-12 11:32:50 -080070 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070071 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070072 private static final int DEFAULT_MAX_FILES = 1000;
73 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
74 private static final int DEFAULT_QUOTA_PERCENT = 10;
75 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070076 private static final int QUOTA_RESCAN_MILLIS = 5000;
77
Craig Mautner26caf7a2012-03-04 17:17:59 -080078 // mHandler 'what' value.
79 private static final int MSG_SEND_BROADCAST = 1;
80
Dan Egnor3d40df32009-11-17 13:36:31 -080081 private static final boolean PROFILE_DUMP = false;
82
Dan Egnor4410ec82009-09-11 16:40:01 -070083 // TODO: This implementation currently uses one file per entry, which is
84 // inefficient for smallish entries -- consider using a single queue file
85 // per tag (or even globally) instead.
86
87 // The cached context and derived objects
88
Dan Egnor4410ec82009-09-11 16:40:01 -070089 private final ContentResolver mContentResolver;
90 private final File mDropBoxDir;
91
92 // Accounting of all currently written log files (set in init()).
93
94 private FileList mAllFiles = null;
Makoto Onukiff94e032017-08-08 14:58:19 -070095 private ArrayMap<String, FileList> mFilesByTag = null;
Dan Egnor4410ec82009-09-11 16:40:01 -070096
97 // Various bits of disk information
98
99 private StatFs mStatFs = null;
100 private int mBlockSize = 0;
101 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
102 private long mCachedQuotaUptimeMillis = 0;
103
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800104 private volatile boolean mBooted = false;
105
Craig Mautner26caf7a2012-03-04 17:17:59 -0800106 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
107 private final Handler mHandler;
108
Dan Egnor4410ec82009-09-11 16:40:01 -0700109 /** Receives events that might indicate a need to clean up files. */
110 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
111 @Override
112 public void onReceive(Context context, Intent intent) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700113 // For ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700114 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700115
116 // Run the initialization in the background (not this main thread).
117 // The init() and trimToFit() methods are synchronized, so they still
118 // block other users -- but at least the onReceive() call can finish.
119 new Thread() {
120 public void run() {
121 try {
122 init();
123 trimToFit();
124 } catch (IOException e) {
125 Slog.e(TAG, "Can't init", e);
126 }
127 }
128 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700129 }
130 };
131
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700132 private final IDropBoxManagerService.Stub mStub = new IDropBoxManagerService.Stub() {
133 @Override
134 public void add(DropBoxManager.Entry entry) {
135 DropBoxManagerService.this.add(entry);
136 }
137
138 @Override
139 public boolean isTagEnabled(String tag) {
140 return DropBoxManagerService.this.isTagEnabled(tag);
141 }
142
143 @Override
144 public DropBoxManager.Entry getNextEntry(String tag, long millis) {
145 return DropBoxManagerService.this.getNextEntry(tag, millis);
146 }
147
148 @Override
149 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
150 DropBoxManagerService.this.dump(fd, pw, args);
151 }
152 };
153
154 /**
155 * Creates an instance of managed drop box storage using the default dropbox
156 * directory.
157 *
158 * @param context to use for receiving free space & gservices intents
159 */
160 public DropBoxManagerService(final Context context) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700161 this(context, new File("/data/system/dropbox"), FgThread.get().getLooper());
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700162 }
163
Dan Egnor4410ec82009-09-11 16:40:01 -0700164 /**
165 * Creates an instance of managed drop box storage. Normally there is one of these
166 * run by the system, but others can be created for testing and other purposes.
167 *
168 * @param context to use for receiving free space & gservices intents
169 * @param path to store drop box entries in
170 */
Makoto Onukiff94e032017-08-08 14:58:19 -0700171 @VisibleForTesting
172 public DropBoxManagerService(final Context context, File path, Looper looper) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700173 super(context);
Dan Egnor4410ec82009-09-11 16:40:01 -0700174 mDropBoxDir = path;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700175 mContentResolver = getContext().getContentResolver();
Makoto Onukiff94e032017-08-08 14:58:19 -0700176 mHandler = new Handler(looper) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700177 @Override
178 public void handleMessage(Message msg) {
179 if (msg.what == MSG_SEND_BROADCAST) {
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700180 getContext().sendBroadcastAsUser((Intent)msg.obj, UserHandle.SYSTEM,
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700181 android.Manifest.permission.READ_LOGS);
182 }
183 }
184 };
185 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700186
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700187 @Override
188 public void onStart() {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700189 publishBinderService(Context.DROPBOX_SERVICE, mStub);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800190
Dan Egnor4410ec82009-09-11 16:40:01 -0700191 // The real work gets done lazily in init() -- that way service creation always
192 // succeeds, and things like disk problems cause individual method failures.
193 }
194
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700195 @Override
196 public void onBootPhase(int phase) {
197 switch (phase) {
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600198 case PHASE_SYSTEM_SERVICES_READY:
199 IntentFilter filter = new IntentFilter();
200 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
201 getContext().registerReceiver(mReceiver, filter);
202
203 mContentResolver.registerContentObserver(
204 Settings.Global.CONTENT_URI, true,
205 new ContentObserver(new Handler()) {
206 @Override
207 public void onChange(boolean selfChange) {
208 mReceiver.onReceive(getContext(), (Intent) null);
209 }
210 });
211 break;
212
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700213 case PHASE_BOOT_COMPLETED:
214 mBooted = true;
215 break;
216 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700217 }
218
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700219 /** Retrieves the binder stub -- for test instances */
220 public IDropBoxManagerService getServiceStub() {
221 return mStub;
222 }
223
Dan Egnorf18a01c2009-11-12 11:32:50 -0800224 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700225 File temp = null;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700226 InputStream input = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700227 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700228 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700229 try {
Dan Egnor95240272009-10-27 18:23:39 -0700230 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800231 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700232
233 init();
234 if (!isTagEnabled(tag)) return;
235 long max = trimToFit();
236 long lastTrim = System.currentTimeMillis();
237
238 byte[] buffer = new byte[mBlockSize];
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700239 input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700240
241 // First, accumulate up to one block worth of data in memory before
242 // deciding whether to compress the data or not.
243
244 int read = 0;
245 while (read < buffer.length) {
246 int n = input.read(buffer, read, buffer.length - read);
247 if (n <= 0) break;
248 read += n;
249 }
250
251 // If we have at least one block, compress it -- otherwise, just write
252 // the data in uncompressed form.
253
254 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700255 int bufferSize = mBlockSize;
256 if (bufferSize > 4096) bufferSize = 4096;
257 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700258 FileOutputStream foutput = new FileOutputStream(temp);
259 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800260 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700261 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800262 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700263 }
264
265 do {
266 output.write(buffer, 0, read);
267
268 long now = System.currentTimeMillis();
269 if (now - lastTrim > 30 * 1000) {
270 max = trimToFit(); // In case data dribbles in slowly
271 lastTrim = now;
272 }
273
274 read = input.read(buffer);
275 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700276 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700277 output.close(); // Get a final size measurement
278 output = null;
279 } else {
280 output.flush(); // So the size measurement is pseudo-reasonable
281 }
282
283 long len = temp.length();
284 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800285 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700286 temp.delete();
287 temp = null; // Pass temp = null to createEntry() to leave a tombstone
288 break;
289 }
290 } while (read > 0);
291
Hakan Stillb2475362010-12-07 14:05:55 +0100292 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700293 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100294
Craig Mautner26caf7a2012-03-04 17:17:59 -0800295 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
Hakan Stillb2475362010-12-07 14:05:55 +0100296 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
297 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800298 if (!mBooted) {
299 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
300 }
Craig Mautner26caf7a2012-03-04 17:17:59 -0800301 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
302 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
303 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
304 // very lock while waiting for the WindowManagerService lock.
305 mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
Dan Egnor4410ec82009-09-11 16:40:01 -0700306 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800307 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700308 } finally {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700309 IoUtils.closeQuietly(output);
310 IoUtils.closeQuietly(input);
Dan Egnor95240272009-10-27 18:23:39 -0700311 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700312 if (temp != null) temp.delete();
313 }
314 }
315
316 public boolean isTagEnabled(String tag) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700317 final long token = Binder.clearCallingIdentity();
318 try {
319 return !"disabled".equals(Settings.Global.getString(
320 mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
321 } finally {
322 Binder.restoreCallingIdentity(token);
323 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700324 }
325
Dan Egnorf18a01c2009-11-12 11:32:50 -0800326 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700327 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
Dan Egnor4410ec82009-09-11 16:40:01 -0700328 != PackageManager.PERMISSION_GRANTED) {
329 throw new SecurityException("READ_LOGS permission required");
330 }
331
332 try {
333 init();
334 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800335 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700336 return null;
337 }
338
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700339 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
340 if (list == null) return null;
341
342 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700343 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800344 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
345 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700346 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700347 final File file = entry.getFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700348 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800349 return new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700350 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700351 } catch (IOException e) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700352 Slog.wtf(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700353 // Continue to next file
354 }
355 }
356
357 return null;
358 }
359
360 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -0600361 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700362
363 try {
364 init();
365 } catch (IOException e) {
366 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800367 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700368 return;
369 }
370
Dan Egnor3d40df32009-11-17 13:36:31 -0800371 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
372
Dan Egnor5ec249a2009-11-25 13:16:47 -0800373 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700374 boolean doPrint = false, doFile = false;
375 ArrayList<String> searchArgs = new ArrayList<String>();
376 for (int i = 0; args != null && i < args.length; i++) {
377 if (args[i].equals("-p") || args[i].equals("--print")) {
378 doPrint = true;
379 } else if (args[i].equals("-f") || args[i].equals("--file")) {
380 doFile = true;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700381 } else if (args[i].equals("-h") || args[i].equals("--help")) {
382 pw.println("Dropbox (dropbox) dump options:");
383 pw.println(" [-h|--help] [-p|--print] [-f|--file] [timestamp]");
384 pw.println(" -h|--help: print this help");
385 pw.println(" -p|--print: print full contents of each entry");
386 pw.println(" -f|--file: print path of each entry's file");
387 pw.println(" [timestamp] optionally filters to only those entries.");
388 return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700389 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800390 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700391 } else {
392 searchArgs.add(args[i]);
393 }
394 }
395
Dan Egnor5ec249a2009-11-25 13:16:47 -0800396 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700397
398 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800399 out.append("Searching for:");
400 for (String a : searchArgs) out.append(" ").append(a);
401 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700402 }
403
Dan Egnor3d40df32009-11-17 13:36:31 -0800404 int numFound = 0, numArgs = searchArgs.size();
405 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800406 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700407 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800408 time.set(entry.timestampMillis);
409 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700410 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800411 for (int i = 0; i < numArgs && match; i++) {
412 String arg = searchArgs.get(i);
413 match = (date.contains(arg) || arg.equals(entry.tag));
414 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700415 if (!match) continue;
416
417 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800418 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800419 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Makoto Onukiff94e032017-08-08 14:58:19 -0700420
421 final File file = entry.getFile(mDropBoxDir);
422 if (file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800423 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700424 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800425 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800426 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700427 continue;
428 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800429 out.append(" (");
430 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
431 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
Makoto Onukiff94e032017-08-08 14:58:19 -0700432 out.append(", ").append(file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700433 }
434
Dan Egnorf18a01c2009-11-12 11:32:50 -0800435 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800436 if (!doPrint) out.append(" ");
Makoto Onukiff94e032017-08-08 14:58:19 -0700437 out.append(file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700438 }
439
Dan Egnorf18a01c2009-11-12 11:32:50 -0800440 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
441 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800442 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700443 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800444 dbe = new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700445 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700446
447 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800448 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700449 char[] buf = new char[4096];
450 boolean newline = false;
451 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800452 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700453 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800454 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700455 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800456
457 // Flush periodically when printing to avoid out-of-memory.
458 if (out.length() > 65536) {
459 pw.write(out.toString());
460 out.setLength(0);
461 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700462 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800463 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700464 } else {
465 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800466 out.append(" ");
467 if (text == null) {
468 out.append("[null]");
469 } else {
470 boolean truncated = (text.length() == 70);
471 out.append(text.trim().replace('\n', '/'));
472 if (truncated) out.append(" ...");
473 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800474 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700475 }
476 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800477 out.append("*** ").append(e.toString()).append("\n");
Makoto Onukiff94e032017-08-08 14:58:19 -0700478 Slog.e(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700479 } finally {
480 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800481 if (isr != null) {
482 try {
483 isr.close();
484 } catch (IOException unused) {
485 }
486 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700487 }
488 }
489
Dan Egnor5ec249a2009-11-25 13:16:47 -0800490 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700491 }
492
Dan Egnor5ec249a2009-11-25 13:16:47 -0800493 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700494
495 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800496 if (!doPrint) out.append("\n");
497 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700498 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800499
500 pw.write(out.toString());
501 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700502 }
503
504 ///////////////////////////////////////////////////////////////////////////
505
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700506 /** Chronologically sorted list of {@link EntryFile} */
Dan Egnor4410ec82009-09-11 16:40:01 -0700507 private static final class FileList implements Comparable<FileList> {
508 public int blocks = 0;
509 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
510
511 /** Sorts bigger FileList instances before smaller ones. */
512 public final int compareTo(FileList o) {
513 if (blocks != o.blocks) return o.blocks - blocks;
514 if (this == o) return 0;
515 if (hashCode() < o.hashCode()) return -1;
516 if (hashCode() > o.hashCode()) return 1;
517 return 0;
518 }
519 }
520
Makoto Onukiff94e032017-08-08 14:58:19 -0700521 /**
522 * Metadata describing an on-disk log file.
523 *
524 * Note its instances do no have knowledge on what directory they're stored, just to save
525 * 4/8 bytes per instance. Instead, {@link #getFile} takes a directory so it can build a
526 * fullpath.
527 */
528 @VisibleForTesting
529 static final class EntryFile implements Comparable<EntryFile> {
Dan Egnor4410ec82009-09-11 16:40:01 -0700530 public final String tag;
531 public final long timestampMillis;
532 public final int flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700533 public final int blocks;
534
535 /** Sorts earlier EntryFile instances before later ones. */
536 public final int compareTo(EntryFile o) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700537 int comp = Long.compare(timestampMillis, o.timestampMillis);
538 if (comp != 0) return comp;
539
540 comp = ObjectUtils.compare(tag, o.tag);
541 if (comp != 0) return comp;
542
543 comp = Integer.compare(flags, o.flags);
544 if (comp != 0) return comp;
545
546 return Integer.compare(hashCode(), o.hashCode());
Dan Egnor4410ec82009-09-11 16:40:01 -0700547 }
548
549 /**
550 * Moves an existing temporary file to a new log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700551 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700552 * @param temp file to rename
553 * @param dir to store file in
554 * @param tag to use for new log file name
555 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700556 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700557 * @param blockSize to use for space accounting
558 * @throws IOException if the file can't be moved
559 */
560 public EntryFile(File temp, File dir, String tag,long timestampMillis,
561 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800562 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700563
Makoto Onukiff94e032017-08-08 14:58:19 -0700564 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700565 this.timestampMillis = timestampMillis;
566 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700567
Makoto Onukiff94e032017-08-08 14:58:19 -0700568 final File file = this.getFile(dir);
569 if (!temp.renameTo(file)) {
570 throw new IOException("Can't rename " + temp + " to " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700571 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700572 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700573 }
574
575 /**
576 * Creates a zero-length tombstone for a file whose contents were lost.
Makoto Onukiff94e032017-08-08 14:58:19 -0700577 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700578 * @param dir to store file in
579 * @param tag to use for new log file name
580 * @param timestampMillis of log entry
581 * @throws IOException if the file can't be created.
582 */
583 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
Makoto Onukiff94e032017-08-08 14:58:19 -0700584 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700585 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800586 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700587 this.blocks = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700588 new FileOutputStream(getFile(dir)).close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700589 }
590
591 /**
592 * Extracts metadata from an existing on-disk log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700593 *
594 * Note when a filename is not recognizable, it will create an instance that
595 * {@link #hasFile()} would return false on, and also remove the file.
596 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700597 * @param file name of existing log file
598 * @param blockSize to use for space accounting
599 */
600 public EntryFile(File file, int blockSize) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700601
602 boolean parseFailure = false;
Dan Egnor4410ec82009-09-11 16:40:01 -0700603
604 String name = file.getName();
Dan Egnor4410ec82009-09-11 16:40:01 -0700605 int flags = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700606 String tag = null;
607 long millis = 0;
608
609 final int at = name.lastIndexOf('@');
610 if (at < 0) {
611 parseFailure = true;
Dan Egnor4410ec82009-09-11 16:40:01 -0700612 } else {
Makoto Onukiff94e032017-08-08 14:58:19 -0700613 tag = Uri.decode(name.substring(0, at));
614 if (name.endsWith(".gz")) {
615 flags |= DropBoxManager.IS_GZIPPED;
616 name = name.substring(0, name.length() - 3);
617 }
618 if (name.endsWith(".lost")) {
619 flags |= DropBoxManager.IS_EMPTY;
620 name = name.substring(at + 1, name.length() - 5);
621 } else if (name.endsWith(".txt")) {
622 flags |= DropBoxManager.IS_TEXT;
623 name = name.substring(at + 1, name.length() - 4);
624 } else if (name.endsWith(".dat")) {
625 name = name.substring(at + 1, name.length() - 4);
626 } else {
627 parseFailure = true;
628 }
629 if (!parseFailure) {
630 try {
631 millis = Long.parseLong(name);
632 } catch (NumberFormatException e) {
633 parseFailure = true;
634 }
635 }
636 }
637 if (parseFailure) {
638 Slog.wtf(TAG, "Invalid filename: " + file);
639
640 // Remove the file and return an empty instance.
641 file.delete();
642 this.tag = null;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800643 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700644 this.timestampMillis = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700645 this.blocks = 0;
Dan Egnor4410ec82009-09-11 16:40:01 -0700646 return;
647 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700648
Makoto Onukiff94e032017-08-08 14:58:19 -0700649 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
650 this.tag = TextUtils.safeIntern(tag);
651 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700652 this.timestampMillis = millis;
653 }
654
655 /**
656 * Creates a EntryFile object with only a timestamp for comparison purposes.
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700657 * @param millis to compare with.
Dan Egnor4410ec82009-09-11 16:40:01 -0700658 */
659 public EntryFile(long millis) {
660 this.tag = null;
661 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800662 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700663 this.blocks = 0;
664 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700665
666 /**
667 * @return whether an entry actually has a backing file, or it's an empty "tombstone"
668 * entry.
669 */
670 public boolean hasFile() {
671 return tag != null;
672 }
673
674 /** @return File extension for the flags. */
675 private String getExtension() {
676 if ((flags & DropBoxManager.IS_EMPTY) != 0) {
677 return ".lost";
678 }
679 return ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
680 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : "");
681 }
682
683 /**
684 * @return filename for this entry without the pathname.
685 */
686 public String getFilename() {
687 return hasFile() ? Uri.encode(tag) + "@" + timestampMillis + getExtension() : null;
688 }
689
690 /**
691 * Get a full-path {@link File} representing this entry.
692 * @param dir Parent directly. The caller needs to pass it because {@link EntryFile}s don't
693 * know in which directory they're stored.
694 */
695 public File getFile(File dir) {
696 return hasFile() ? new File(dir, getFilename()) : null;
697 }
698
699 /**
700 * If an entry has a backing file, remove it.
701 */
702 public void deleteFile(File dir) {
703 if (hasFile()) {
704 getFile(dir).delete();
705 }
706 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700707 }
708
709 ///////////////////////////////////////////////////////////////////////////
710
711 /** If never run before, scans disk contents to build in-memory tracking data. */
712 private synchronized void init() throws IOException {
713 if (mStatFs == null) {
714 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
715 throw new IOException("Can't mkdir: " + mDropBoxDir);
716 }
717 try {
718 mStatFs = new StatFs(mDropBoxDir.getPath());
719 mBlockSize = mStatFs.getBlockSize();
720 } catch (IllegalArgumentException e) { // StatFs throws this on error
721 throw new IOException("Can't statfs: " + mDropBoxDir);
722 }
723 }
724
725 if (mAllFiles == null) {
726 File[] files = mDropBoxDir.listFiles();
727 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
728
729 mAllFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700730 mFilesByTag = new ArrayMap<>();
Dan Egnor4410ec82009-09-11 16:40:01 -0700731
732 // Scan pre-existing files.
733 for (File file : files) {
734 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800735 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700736 file.delete();
737 continue;
738 }
739
740 EntryFile entry = new EntryFile(file, mBlockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700741
Makoto Onukiff94e032017-08-08 14:58:19 -0700742 if (entry.hasFile()) {
743 // Enroll only when the filename is valid. Otherwise the above constructor
744 // has removed the file already.
745 enrollEntry(entry);
746 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700747 }
748 }
749 }
750
751 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
752 private synchronized void enrollEntry(EntryFile entry) {
753 mAllFiles.contents.add(entry);
754 mAllFiles.blocks += entry.blocks;
755
756 // mFilesByTag is used for trimming, so don't list empty files.
757 // (Zero-length/lost files are trimmed by date from mAllFiles.)
758
Makoto Onukiff94e032017-08-08 14:58:19 -0700759 if (entry.hasFile() && entry.blocks > 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700760 FileList tagFiles = mFilesByTag.get(entry.tag);
761 if (tagFiles == null) {
762 tagFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700763 mFilesByTag.put(TextUtils.safeIntern(entry.tag), tagFiles);
Dan Egnor4410ec82009-09-11 16:40:01 -0700764 }
765 tagFiles.contents.add(entry);
766 tagFiles.blocks += entry.blocks;
767 }
768 }
769
770 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100771 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700772 long t = System.currentTimeMillis();
773
774 // Require each entry to have a unique timestamp; if there are entries
775 // >10sec in the future (due to clock skew), drag them back to avoid
776 // keeping them around forever.
777
778 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
779 EntryFile[] future = null;
780 if (!tail.isEmpty()) {
781 future = tail.toArray(new EntryFile[tail.size()]);
782 tail.clear(); // Remove from mAllFiles
783 }
784
785 if (!mAllFiles.contents.isEmpty()) {
786 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
787 }
788
789 if (future != null) {
790 for (EntryFile late : future) {
791 mAllFiles.blocks -= late.blocks;
792 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800793 if (tagFiles != null && tagFiles.contents.remove(late)) {
794 tagFiles.blocks -= late.blocks;
795 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800796 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700797 enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
798 late.tag, t++, late.flags, mBlockSize));
Dan Egnor4410ec82009-09-11 16:40:01 -0700799 } else {
800 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
801 }
802 }
803 }
804
805 if (temp == null) {
806 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
807 } else {
808 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
809 }
Hakan Stillb2475362010-12-07 14:05:55 +0100810 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700811 }
812
813 /**
814 * Trims the files on disk to make sure they aren't using too much space.
815 * @return the overall quota for storage (in bytes)
816 */
songjinshic5e249b2016-07-27 20:36:46 +0800817 private synchronized long trimToFit() throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700818 // Expunge aged items (including tombstones marking deleted data).
819
Jeff Sharkey625239a2012-09-26 22:03:49 -0700820 int ageSeconds = Settings.Global.getInt(mContentResolver,
821 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
822 int maxFiles = Settings.Global.getInt(mContentResolver,
823 Settings.Global.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
Dan Egnor4410ec82009-09-11 16:40:01 -0700824 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
825 while (!mAllFiles.contents.isEmpty()) {
826 EntryFile entry = mAllFiles.contents.first();
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700827 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
Dan Egnor4410ec82009-09-11 16:40:01 -0700828
829 FileList tag = mFilesByTag.get(entry.tag);
830 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
831 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
Makoto Onukiff94e032017-08-08 14:58:19 -0700832 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700833 }
834
835 // Compute overall quota (a fraction of available free space) in blocks.
836 // The quota changes dynamically based on the amount of free space;
837 // that way when lots of data is available we can use it, but we'll get
838 // out of the way if storage starts getting tight.
839
840 long uptimeMillis = SystemClock.uptimeMillis();
841 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -0700842 int quotaPercent = Settings.Global.getInt(mContentResolver,
843 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
844 int reservePercent = Settings.Global.getInt(mContentResolver,
845 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
846 int quotaKb = Settings.Global.getInt(mContentResolver,
847 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700848
songjinshic5e249b2016-07-27 20:36:46 +0800849 String dirPath = mDropBoxDir.getPath();
850 try {
851 mStatFs.restat(dirPath);
852 } catch (IllegalArgumentException e) { // restat throws this on error
853 throw new IOException("Can't restat: " + mDropBoxDir);
854 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700855 int available = mStatFs.getAvailableBlocks();
856 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
857 int maximum = quotaKb * 1024 / mBlockSize;
858 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
859 mCachedQuotaUptimeMillis = uptimeMillis;
860 }
861
862 // If we're using too much space, delete old items to make room.
863 //
864 // We trim each tag independently (this is why we keep per-tag lists).
865 // Space is "fairly" shared between tags -- they are all squeezed
866 // equally until enough space is reclaimed.
867 //
868 // A single circular buffer (a la logcat) would be simpler, but this
869 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
870 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700871 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700872 //
873 // Deleted files are replaced with zero-length tombstones to mark what
874 // was lost. Tombstones are expunged by age (see above).
875
876 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700877 // Find a fair share amount of space to limit each tag
878 int unsqueezed = mAllFiles.blocks, squeezed = 0;
879 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
880 for (FileList tag : tags) {
881 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
882 break;
883 }
884 unsqueezed -= tag.blocks;
885 squeezed++;
886 }
887 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
888
889 // Remove old items from each tag until it meets the per-tag quota.
890 for (FileList tag : tags) {
891 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
892 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
893 EntryFile entry = tag.contents.first();
894 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
895 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
896
897 try {
Makoto Onukiff94e032017-08-08 14:58:19 -0700898 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700899 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
900 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800901 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700902 }
903 }
904 }
905 }
906
907 return mCachedQuotaBlocks * mBlockSize;
908 }
909}