blob: 887de74f1cf9a7558bad19421f0c6fe50a121165 [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
Makoto Onuki0e623be2017-08-22 10:36:12 -070019import android.app.ActivityManager;
Dan Egnor4410ec82009-09-11 16:40:01 -070020import android.content.BroadcastReceiver;
21import android.content.ContentResolver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.IntentFilter;
25import android.content.pm.PackageManager;
Doug Zongker43866e02010-01-07 12:09:54 -080026import android.database.ContentObserver;
Dan Egnor4410ec82009-09-11 16:40:01 -070027import android.net.Uri;
Jeff Sharkey911d7f42013-09-05 18:11:45 -070028import android.os.Binder;
Dan Egnor3d40df32009-11-17 13:36:31 -080029import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080030import android.os.DropBoxManager;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070031import android.os.FileUtils;
Doug Zongker43866e02010-01-07 12:09:54 -080032import android.os.Handler;
Makoto Onukiff94e032017-08-08 14:58:19 -070033import android.os.Looper;
Craig Mautner26caf7a2012-03-04 17:17:59 -080034import android.os.Message;
Dan Egnor4410ec82009-09-11 16:40:01 -070035import android.os.StatFs;
36import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070037import android.os.UserHandle;
Dan Egnor4410ec82009-09-11 16:40:01 -070038import android.provider.Settings;
Makoto Onukiff94e032017-08-08 14:58:19 -070039import android.text.TextUtils;
Dan Egnor3d40df32009-11-17 13:36:31 -080040import android.text.format.Time;
Makoto Onukiff94e032017-08-08 14:58:19 -070041import android.util.ArrayMap;
Joe Onorato8a9b2202010-02-26 18:56:32 -080042import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070043
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070044import libcore.io.IoUtils;
45
Makoto Onukiff94e032017-08-08 14:58:19 -070046import com.android.internal.annotations.VisibleForTesting;
Dan Egnorf18a01c2009-11-12 11:32:50 -080047import com.android.internal.os.IDropBoxManagerService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060048import com.android.internal.util.DumpUtils;
Makoto Onukiff94e032017-08-08 14:58:19 -070049import com.android.internal.util.ObjectUtils;
Dan Egnor95240272009-10-27 18:23:39 -070050
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070051import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070052import java.io.File;
53import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070054import java.io.FileOutputStream;
55import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070056import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070057import java.io.InputStreamReader;
58import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070059import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070060import java.util.ArrayList;
Makoto Onukiff94e032017-08-08 14:58:19 -070061import java.util.Objects;
Dan Egnor4410ec82009-09-11 16:40:01 -070062import java.util.SortedSet;
63import java.util.TreeSet;
64import java.util.zip.GZIPOutputStream;
65
66/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080067 * Implementation of {@link IDropBoxManagerService} using the filesystem.
68 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070069 */
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070070public final class DropBoxManagerService extends SystemService {
Dan Egnorf18a01c2009-11-12 11:32:50 -080071 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070072 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070073 private static final int DEFAULT_MAX_FILES = 1000;
Makoto Onuki0e623be2017-08-22 10:36:12 -070074 private static final int DEFAULT_MAX_FILES_LOWRAM = 300;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070075 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
76 private static final int DEFAULT_QUOTA_PERCENT = 10;
77 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070078 private static final int QUOTA_RESCAN_MILLIS = 5000;
79
Craig Mautner26caf7a2012-03-04 17:17:59 -080080 // mHandler 'what' value.
81 private static final int MSG_SEND_BROADCAST = 1;
82
Dan Egnor3d40df32009-11-17 13:36:31 -080083 private static final boolean PROFILE_DUMP = false;
84
Dan Egnor4410ec82009-09-11 16:40:01 -070085 // TODO: This implementation currently uses one file per entry, which is
86 // inefficient for smallish entries -- consider using a single queue file
87 // per tag (or even globally) instead.
88
89 // The cached context and derived objects
90
Dan Egnor4410ec82009-09-11 16:40:01 -070091 private final ContentResolver mContentResolver;
92 private final File mDropBoxDir;
93
94 // Accounting of all currently written log files (set in init()).
95
96 private FileList mAllFiles = null;
Makoto Onukiff94e032017-08-08 14:58:19 -070097 private ArrayMap<String, FileList> mFilesByTag = null;
Dan Egnor4410ec82009-09-11 16:40:01 -070098
99 // Various bits of disk information
100
101 private StatFs mStatFs = null;
102 private int mBlockSize = 0;
103 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
104 private long mCachedQuotaUptimeMillis = 0;
105
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800106 private volatile boolean mBooted = false;
107
Craig Mautner26caf7a2012-03-04 17:17:59 -0800108 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
109 private final Handler mHandler;
110
Makoto Onuki0e623be2017-08-22 10:36:12 -0700111 private int mMaxFiles = -1; // -1 means uninitialized.
112
Dan Egnor4410ec82009-09-11 16:40:01 -0700113 /** Receives events that might indicate a need to clean up files. */
114 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
115 @Override
116 public void onReceive(Context context, Intent intent) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700117 // For ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700118 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700119
120 // Run the initialization in the background (not this main thread).
121 // The init() and trimToFit() methods are synchronized, so they still
122 // block other users -- but at least the onReceive() call can finish.
123 new Thread() {
124 public void run() {
125 try {
126 init();
127 trimToFit();
128 } catch (IOException e) {
129 Slog.e(TAG, "Can't init", e);
130 }
131 }
132 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700133 }
134 };
135
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700136 private final IDropBoxManagerService.Stub mStub = new IDropBoxManagerService.Stub() {
137 @Override
138 public void add(DropBoxManager.Entry entry) {
139 DropBoxManagerService.this.add(entry);
140 }
141
142 @Override
143 public boolean isTagEnabled(String tag) {
144 return DropBoxManagerService.this.isTagEnabled(tag);
145 }
146
147 @Override
148 public DropBoxManager.Entry getNextEntry(String tag, long millis) {
149 return DropBoxManagerService.this.getNextEntry(tag, millis);
150 }
151
152 @Override
153 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
154 DropBoxManagerService.this.dump(fd, pw, args);
155 }
156 };
157
158 /**
159 * Creates an instance of managed drop box storage using the default dropbox
160 * directory.
161 *
162 * @param context to use for receiving free space & gservices intents
163 */
164 public DropBoxManagerService(final Context context) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700165 this(context, new File("/data/system/dropbox"), FgThread.get().getLooper());
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700166 }
167
Dan Egnor4410ec82009-09-11 16:40:01 -0700168 /**
169 * Creates an instance of managed drop box storage. Normally there is one of these
170 * run by the system, but others can be created for testing and other purposes.
171 *
172 * @param context to use for receiving free space & gservices intents
173 * @param path to store drop box entries in
174 */
Makoto Onukiff94e032017-08-08 14:58:19 -0700175 @VisibleForTesting
176 public DropBoxManagerService(final Context context, File path, Looper looper) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700177 super(context);
Dan Egnor4410ec82009-09-11 16:40:01 -0700178 mDropBoxDir = path;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700179 mContentResolver = getContext().getContentResolver();
Makoto Onukiff94e032017-08-08 14:58:19 -0700180 mHandler = new Handler(looper) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700181 @Override
182 public void handleMessage(Message msg) {
183 if (msg.what == MSG_SEND_BROADCAST) {
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700184 getContext().sendBroadcastAsUser((Intent)msg.obj, UserHandle.SYSTEM,
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700185 android.Manifest.permission.READ_LOGS);
186 }
187 }
188 };
189 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700190
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700191 @Override
192 public void onStart() {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700193 publishBinderService(Context.DROPBOX_SERVICE, mStub);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800194
Dan Egnor4410ec82009-09-11 16:40:01 -0700195 // The real work gets done lazily in init() -- that way service creation always
196 // succeeds, and things like disk problems cause individual method failures.
197 }
198
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700199 @Override
200 public void onBootPhase(int phase) {
201 switch (phase) {
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600202 case PHASE_SYSTEM_SERVICES_READY:
203 IntentFilter filter = new IntentFilter();
204 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
205 getContext().registerReceiver(mReceiver, filter);
206
207 mContentResolver.registerContentObserver(
208 Settings.Global.CONTENT_URI, true,
209 new ContentObserver(new Handler()) {
210 @Override
211 public void onChange(boolean selfChange) {
212 mReceiver.onReceive(getContext(), (Intent) null);
213 }
214 });
215 break;
216
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700217 case PHASE_BOOT_COMPLETED:
218 mBooted = true;
219 break;
220 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700221 }
222
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700223 /** Retrieves the binder stub -- for test instances */
224 public IDropBoxManagerService getServiceStub() {
225 return mStub;
226 }
227
Dan Egnorf18a01c2009-11-12 11:32:50 -0800228 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700229 File temp = null;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700230 InputStream input = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700231 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700232 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700233 try {
Dan Egnor95240272009-10-27 18:23:39 -0700234 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800235 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700236
237 init();
238 if (!isTagEnabled(tag)) return;
239 long max = trimToFit();
240 long lastTrim = System.currentTimeMillis();
241
242 byte[] buffer = new byte[mBlockSize];
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700243 input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700244
245 // First, accumulate up to one block worth of data in memory before
246 // deciding whether to compress the data or not.
247
248 int read = 0;
249 while (read < buffer.length) {
250 int n = input.read(buffer, read, buffer.length - read);
251 if (n <= 0) break;
252 read += n;
253 }
254
255 // If we have at least one block, compress it -- otherwise, just write
256 // the data in uncompressed form.
257
258 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700259 int bufferSize = mBlockSize;
260 if (bufferSize > 4096) bufferSize = 4096;
261 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700262 FileOutputStream foutput = new FileOutputStream(temp);
263 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800264 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700265 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800266 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700267 }
268
269 do {
270 output.write(buffer, 0, read);
271
272 long now = System.currentTimeMillis();
273 if (now - lastTrim > 30 * 1000) {
274 max = trimToFit(); // In case data dribbles in slowly
275 lastTrim = now;
276 }
277
278 read = input.read(buffer);
279 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700280 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700281 output.close(); // Get a final size measurement
282 output = null;
283 } else {
284 output.flush(); // So the size measurement is pseudo-reasonable
285 }
286
287 long len = temp.length();
288 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800289 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700290 temp.delete();
291 temp = null; // Pass temp = null to createEntry() to leave a tombstone
292 break;
293 }
294 } while (read > 0);
295
Hakan Stillb2475362010-12-07 14:05:55 +0100296 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700297 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100298
Craig Mautner26caf7a2012-03-04 17:17:59 -0800299 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
Hakan Stillb2475362010-12-07 14:05:55 +0100300 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
301 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800302 if (!mBooted) {
303 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
304 }
Craig Mautner26caf7a2012-03-04 17:17:59 -0800305 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
306 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
307 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
308 // very lock while waiting for the WindowManagerService lock.
309 mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
Dan Egnor4410ec82009-09-11 16:40:01 -0700310 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800311 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700312 } finally {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700313 IoUtils.closeQuietly(output);
314 IoUtils.closeQuietly(input);
Dan Egnor95240272009-10-27 18:23:39 -0700315 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700316 if (temp != null) temp.delete();
317 }
318 }
319
320 public boolean isTagEnabled(String tag) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700321 final long token = Binder.clearCallingIdentity();
322 try {
323 return !"disabled".equals(Settings.Global.getString(
324 mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
325 } finally {
326 Binder.restoreCallingIdentity(token);
327 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700328 }
329
Dan Egnorf18a01c2009-11-12 11:32:50 -0800330 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700331 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
Dan Egnor4410ec82009-09-11 16:40:01 -0700332 != PackageManager.PERMISSION_GRANTED) {
333 throw new SecurityException("READ_LOGS permission required");
334 }
335
336 try {
337 init();
338 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800339 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700340 return null;
341 }
342
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700343 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
344 if (list == null) return null;
345
346 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700347 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800348 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
349 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700350 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700351 final File file = entry.getFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700352 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800353 return new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700354 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700355 } catch (IOException e) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700356 Slog.wtf(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700357 // Continue to next file
358 }
359 }
360
361 return null;
362 }
363
364 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -0600365 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700366
367 try {
368 init();
369 } catch (IOException e) {
370 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800371 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700372 return;
373 }
374
Dan Egnor3d40df32009-11-17 13:36:31 -0800375 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
376
Dan Egnor5ec249a2009-11-25 13:16:47 -0800377 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700378 boolean doPrint = false, doFile = false;
379 ArrayList<String> searchArgs = new ArrayList<String>();
380 for (int i = 0; args != null && i < args.length; i++) {
381 if (args[i].equals("-p") || args[i].equals("--print")) {
382 doPrint = true;
383 } else if (args[i].equals("-f") || args[i].equals("--file")) {
384 doFile = true;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700385 } else if (args[i].equals("-h") || args[i].equals("--help")) {
386 pw.println("Dropbox (dropbox) dump options:");
387 pw.println(" [-h|--help] [-p|--print] [-f|--file] [timestamp]");
388 pw.println(" -h|--help: print this help");
389 pw.println(" -p|--print: print full contents of each entry");
390 pw.println(" -f|--file: print path of each entry's file");
391 pw.println(" [timestamp] optionally filters to only those entries.");
392 return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700393 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800394 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700395 } else {
396 searchArgs.add(args[i]);
397 }
398 }
399
Dan Egnor5ec249a2009-11-25 13:16:47 -0800400 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Makoto Onuki0e623be2017-08-22 10:36:12 -0700401 out.append("Max entries: ").append(mMaxFiles).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700402
403 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800404 out.append("Searching for:");
405 for (String a : searchArgs) out.append(" ").append(a);
406 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700407 }
408
Dan Egnor3d40df32009-11-17 13:36:31 -0800409 int numFound = 0, numArgs = searchArgs.size();
410 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800411 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700412 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800413 time.set(entry.timestampMillis);
414 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700415 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800416 for (int i = 0; i < numArgs && match; i++) {
417 String arg = searchArgs.get(i);
418 match = (date.contains(arg) || arg.equals(entry.tag));
419 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700420 if (!match) continue;
421
422 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800423 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800424 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Makoto Onukiff94e032017-08-08 14:58:19 -0700425
426 final File file = entry.getFile(mDropBoxDir);
427 if (file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800428 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700429 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800430 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800431 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700432 continue;
433 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800434 out.append(" (");
435 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
436 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
Makoto Onukiff94e032017-08-08 14:58:19 -0700437 out.append(", ").append(file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700438 }
439
Dan Egnorf18a01c2009-11-12 11:32:50 -0800440 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800441 if (!doPrint) out.append(" ");
Makoto Onukiff94e032017-08-08 14:58:19 -0700442 out.append(file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700443 }
444
Dan Egnorf18a01c2009-11-12 11:32:50 -0800445 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
446 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800447 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700448 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800449 dbe = new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700450 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700451
452 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800453 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700454 char[] buf = new char[4096];
455 boolean newline = false;
456 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800457 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700458 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800459 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700460 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800461
462 // Flush periodically when printing to avoid out-of-memory.
463 if (out.length() > 65536) {
464 pw.write(out.toString());
465 out.setLength(0);
466 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700467 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800468 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700469 } else {
470 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800471 out.append(" ");
472 if (text == null) {
473 out.append("[null]");
474 } else {
475 boolean truncated = (text.length() == 70);
476 out.append(text.trim().replace('\n', '/'));
477 if (truncated) out.append(" ...");
478 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800479 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700480 }
481 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800482 out.append("*** ").append(e.toString()).append("\n");
Makoto Onukiff94e032017-08-08 14:58:19 -0700483 Slog.e(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700484 } finally {
485 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800486 if (isr != null) {
487 try {
488 isr.close();
489 } catch (IOException unused) {
490 }
491 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700492 }
493 }
494
Dan Egnor5ec249a2009-11-25 13:16:47 -0800495 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700496 }
497
Dan Egnor5ec249a2009-11-25 13:16:47 -0800498 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700499
500 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800501 if (!doPrint) out.append("\n");
502 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700503 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800504
505 pw.write(out.toString());
506 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700507 }
508
509 ///////////////////////////////////////////////////////////////////////////
510
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700511 /** Chronologically sorted list of {@link EntryFile} */
Dan Egnor4410ec82009-09-11 16:40:01 -0700512 private static final class FileList implements Comparable<FileList> {
513 public int blocks = 0;
514 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
515
516 /** Sorts bigger FileList instances before smaller ones. */
517 public final int compareTo(FileList o) {
518 if (blocks != o.blocks) return o.blocks - blocks;
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
Makoto Onukiff94e032017-08-08 14:58:19 -0700526 /**
527 * Metadata describing an on-disk log file.
528 *
529 * Note its instances do no have knowledge on what directory they're stored, just to save
530 * 4/8 bytes per instance. Instead, {@link #getFile} takes a directory so it can build a
531 * fullpath.
532 */
533 @VisibleForTesting
534 static final class EntryFile implements Comparable<EntryFile> {
Dan Egnor4410ec82009-09-11 16:40:01 -0700535 public final String tag;
536 public final long timestampMillis;
537 public final int flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700538 public final int blocks;
539
540 /** Sorts earlier EntryFile instances before later ones. */
541 public final int compareTo(EntryFile o) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700542 int comp = Long.compare(timestampMillis, o.timestampMillis);
543 if (comp != 0) return comp;
544
545 comp = ObjectUtils.compare(tag, o.tag);
546 if (comp != 0) return comp;
547
548 comp = Integer.compare(flags, o.flags);
549 if (comp != 0) return comp;
550
551 return Integer.compare(hashCode(), o.hashCode());
Dan Egnor4410ec82009-09-11 16:40:01 -0700552 }
553
554 /**
555 * Moves an existing temporary file to a new log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700556 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700557 * @param temp file to rename
558 * @param dir to store file in
559 * @param tag to use for new log file name
560 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700561 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700562 * @param blockSize to use for space accounting
563 * @throws IOException if the file can't be moved
564 */
565 public EntryFile(File temp, File dir, String tag,long timestampMillis,
566 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800567 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700568
Makoto Onukiff94e032017-08-08 14:58:19 -0700569 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700570 this.timestampMillis = timestampMillis;
571 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700572
Makoto Onukiff94e032017-08-08 14:58:19 -0700573 final File file = this.getFile(dir);
574 if (!temp.renameTo(file)) {
575 throw new IOException("Can't rename " + temp + " to " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700576 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700577 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700578 }
579
580 /**
581 * Creates a zero-length tombstone for a file whose contents were lost.
Makoto Onukiff94e032017-08-08 14:58:19 -0700582 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700583 * @param dir to store file in
584 * @param tag to use for new log file name
585 * @param timestampMillis of log entry
586 * @throws IOException if the file can't be created.
587 */
588 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
Makoto Onukiff94e032017-08-08 14:58:19 -0700589 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700590 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800591 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700592 this.blocks = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700593 new FileOutputStream(getFile(dir)).close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700594 }
595
596 /**
597 * Extracts metadata from an existing on-disk log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700598 *
599 * Note when a filename is not recognizable, it will create an instance that
600 * {@link #hasFile()} would return false on, and also remove the file.
601 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700602 * @param file name of existing log file
603 * @param blockSize to use for space accounting
604 */
605 public EntryFile(File file, int blockSize) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700606
607 boolean parseFailure = false;
Dan Egnor4410ec82009-09-11 16:40:01 -0700608
609 String name = file.getName();
Dan Egnor4410ec82009-09-11 16:40:01 -0700610 int flags = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700611 String tag = null;
612 long millis = 0;
613
614 final int at = name.lastIndexOf('@');
615 if (at < 0) {
616 parseFailure = true;
Dan Egnor4410ec82009-09-11 16:40:01 -0700617 } else {
Makoto Onukiff94e032017-08-08 14:58:19 -0700618 tag = Uri.decode(name.substring(0, at));
619 if (name.endsWith(".gz")) {
620 flags |= DropBoxManager.IS_GZIPPED;
621 name = name.substring(0, name.length() - 3);
622 }
623 if (name.endsWith(".lost")) {
624 flags |= DropBoxManager.IS_EMPTY;
625 name = name.substring(at + 1, name.length() - 5);
626 } else if (name.endsWith(".txt")) {
627 flags |= DropBoxManager.IS_TEXT;
628 name = name.substring(at + 1, name.length() - 4);
629 } else if (name.endsWith(".dat")) {
630 name = name.substring(at + 1, name.length() - 4);
631 } else {
632 parseFailure = true;
633 }
634 if (!parseFailure) {
635 try {
636 millis = Long.parseLong(name);
637 } catch (NumberFormatException e) {
638 parseFailure = true;
639 }
640 }
641 }
642 if (parseFailure) {
643 Slog.wtf(TAG, "Invalid filename: " + file);
644
645 // Remove the file and return an empty instance.
646 file.delete();
647 this.tag = null;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800648 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700649 this.timestampMillis = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700650 this.blocks = 0;
Dan Egnor4410ec82009-09-11 16:40:01 -0700651 return;
652 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700653
Makoto Onukiff94e032017-08-08 14:58:19 -0700654 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
655 this.tag = TextUtils.safeIntern(tag);
656 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700657 this.timestampMillis = millis;
658 }
659
660 /**
661 * Creates a EntryFile object with only a timestamp for comparison purposes.
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700662 * @param millis to compare with.
Dan Egnor4410ec82009-09-11 16:40:01 -0700663 */
664 public EntryFile(long millis) {
665 this.tag = null;
666 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800667 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700668 this.blocks = 0;
669 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700670
671 /**
672 * @return whether an entry actually has a backing file, or it's an empty "tombstone"
673 * entry.
674 */
675 public boolean hasFile() {
676 return tag != null;
677 }
678
679 /** @return File extension for the flags. */
680 private String getExtension() {
681 if ((flags & DropBoxManager.IS_EMPTY) != 0) {
682 return ".lost";
683 }
684 return ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
685 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : "");
686 }
687
688 /**
689 * @return filename for this entry without the pathname.
690 */
691 public String getFilename() {
692 return hasFile() ? Uri.encode(tag) + "@" + timestampMillis + getExtension() : null;
693 }
694
695 /**
696 * Get a full-path {@link File} representing this entry.
697 * @param dir Parent directly. The caller needs to pass it because {@link EntryFile}s don't
698 * know in which directory they're stored.
699 */
700 public File getFile(File dir) {
701 return hasFile() ? new File(dir, getFilename()) : null;
702 }
703
704 /**
705 * If an entry has a backing file, remove it.
706 */
707 public void deleteFile(File dir) {
708 if (hasFile()) {
709 getFile(dir).delete();
710 }
711 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700712 }
713
714 ///////////////////////////////////////////////////////////////////////////
715
716 /** If never run before, scans disk contents to build in-memory tracking data. */
717 private synchronized void init() throws IOException {
718 if (mStatFs == null) {
719 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
720 throw new IOException("Can't mkdir: " + mDropBoxDir);
721 }
722 try {
723 mStatFs = new StatFs(mDropBoxDir.getPath());
724 mBlockSize = mStatFs.getBlockSize();
725 } catch (IllegalArgumentException e) { // StatFs throws this on error
726 throw new IOException("Can't statfs: " + mDropBoxDir);
727 }
728 }
729
730 if (mAllFiles == null) {
731 File[] files = mDropBoxDir.listFiles();
732 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
733
734 mAllFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700735 mFilesByTag = new ArrayMap<>();
Dan Egnor4410ec82009-09-11 16:40:01 -0700736
737 // Scan pre-existing files.
738 for (File file : files) {
739 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800740 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700741 file.delete();
742 continue;
743 }
744
745 EntryFile entry = new EntryFile(file, mBlockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700746
Makoto Onukiff94e032017-08-08 14:58:19 -0700747 if (entry.hasFile()) {
748 // Enroll only when the filename is valid. Otherwise the above constructor
749 // has removed the file already.
750 enrollEntry(entry);
751 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700752 }
753 }
754 }
755
756 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
757 private synchronized void enrollEntry(EntryFile entry) {
758 mAllFiles.contents.add(entry);
759 mAllFiles.blocks += entry.blocks;
760
761 // mFilesByTag is used for trimming, so don't list empty files.
762 // (Zero-length/lost files are trimmed by date from mAllFiles.)
763
Makoto Onukiff94e032017-08-08 14:58:19 -0700764 if (entry.hasFile() && entry.blocks > 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700765 FileList tagFiles = mFilesByTag.get(entry.tag);
766 if (tagFiles == null) {
767 tagFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700768 mFilesByTag.put(TextUtils.safeIntern(entry.tag), tagFiles);
Dan Egnor4410ec82009-09-11 16:40:01 -0700769 }
770 tagFiles.contents.add(entry);
771 tagFiles.blocks += entry.blocks;
772 }
773 }
774
775 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100776 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700777 long t = System.currentTimeMillis();
778
779 // Require each entry to have a unique timestamp; if there are entries
780 // >10sec in the future (due to clock skew), drag them back to avoid
781 // keeping them around forever.
782
783 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
784 EntryFile[] future = null;
785 if (!tail.isEmpty()) {
786 future = tail.toArray(new EntryFile[tail.size()]);
787 tail.clear(); // Remove from mAllFiles
788 }
789
790 if (!mAllFiles.contents.isEmpty()) {
791 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
792 }
793
794 if (future != null) {
795 for (EntryFile late : future) {
796 mAllFiles.blocks -= late.blocks;
797 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800798 if (tagFiles != null && tagFiles.contents.remove(late)) {
799 tagFiles.blocks -= late.blocks;
800 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800801 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700802 enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
803 late.tag, t++, late.flags, mBlockSize));
Dan Egnor4410ec82009-09-11 16:40:01 -0700804 } else {
805 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
806 }
807 }
808 }
809
810 if (temp == null) {
811 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
812 } else {
813 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
814 }
Hakan Stillb2475362010-12-07 14:05:55 +0100815 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700816 }
817
818 /**
819 * Trims the files on disk to make sure they aren't using too much space.
820 * @return the overall quota for storage (in bytes)
821 */
songjinshic5e249b2016-07-27 20:36:46 +0800822 private synchronized long trimToFit() throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700823 // Expunge aged items (including tombstones marking deleted data).
824
Jeff Sharkey625239a2012-09-26 22:03:49 -0700825 int ageSeconds = Settings.Global.getInt(mContentResolver,
826 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Makoto Onuki0e623be2017-08-22 10:36:12 -0700827 mMaxFiles = Settings.Global.getInt(mContentResolver,
828 Settings.Global.DROPBOX_MAX_FILES,
829 (ActivityManager.isLowRamDeviceStatic()
830 ? DEFAULT_MAX_FILES_LOWRAM : DEFAULT_MAX_FILES));
Dan Egnor4410ec82009-09-11 16:40:01 -0700831 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
832 while (!mAllFiles.contents.isEmpty()) {
833 EntryFile entry = mAllFiles.contents.first();
Makoto Onuki0e623be2017-08-22 10:36:12 -0700834 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < mMaxFiles) {
835 break;
836 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700837
838 FileList tag = mFilesByTag.get(entry.tag);
839 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
840 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
Makoto Onukiff94e032017-08-08 14:58:19 -0700841 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700842 }
843
844 // Compute overall quota (a fraction of available free space) in blocks.
845 // The quota changes dynamically based on the amount of free space;
846 // that way when lots of data is available we can use it, but we'll get
847 // out of the way if storage starts getting tight.
848
849 long uptimeMillis = SystemClock.uptimeMillis();
850 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -0700851 int quotaPercent = Settings.Global.getInt(mContentResolver,
852 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
853 int reservePercent = Settings.Global.getInt(mContentResolver,
854 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
855 int quotaKb = Settings.Global.getInt(mContentResolver,
856 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700857
songjinshic5e249b2016-07-27 20:36:46 +0800858 String dirPath = mDropBoxDir.getPath();
859 try {
860 mStatFs.restat(dirPath);
861 } catch (IllegalArgumentException e) { // restat throws this on error
862 throw new IOException("Can't restat: " + mDropBoxDir);
863 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700864 int available = mStatFs.getAvailableBlocks();
865 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
866 int maximum = quotaKb * 1024 / mBlockSize;
867 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
868 mCachedQuotaUptimeMillis = uptimeMillis;
869 }
870
871 // If we're using too much space, delete old items to make room.
872 //
873 // We trim each tag independently (this is why we keep per-tag lists).
874 // Space is "fairly" shared between tags -- they are all squeezed
875 // equally until enough space is reclaimed.
876 //
877 // A single circular buffer (a la logcat) would be simpler, but this
878 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
879 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700880 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700881 //
882 // Deleted files are replaced with zero-length tombstones to mark what
883 // was lost. Tombstones are expunged by age (see above).
884
885 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700886 // Find a fair share amount of space to limit each tag
887 int unsqueezed = mAllFiles.blocks, squeezed = 0;
888 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
889 for (FileList tag : tags) {
890 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
891 break;
892 }
893 unsqueezed -= tag.blocks;
894 squeezed++;
895 }
896 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
897
898 // Remove old items from each tag until it meets the per-tag quota.
899 for (FileList tag : tags) {
900 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
901 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
902 EntryFile entry = tag.contents.first();
903 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
904 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
905
906 try {
Makoto Onukiff94e032017-08-08 14:58:19 -0700907 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700908 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
909 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800910 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700911 }
912 }
913 }
914 }
915
916 return mCachedQuotaBlocks * mBlockSize;
917 }
918}