blob: b393d8758f3b03ddb9b145a1c6b1492249c41027 [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;
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -060020import android.app.AppOpsManager;
Dan Egnor4410ec82009-09-11 16:40:01 -070021import android.content.BroadcastReceiver;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
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
Makoto Onukiff94e032017-08-08 14:58:19 -070044import com.android.internal.annotations.VisibleForTesting;
Dan Egnorf18a01c2009-11-12 11:32:50 -080045import com.android.internal.os.IDropBoxManagerService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060046import com.android.internal.util.DumpUtils;
Makoto Onukiff94e032017-08-08 14:58:19 -070047import com.android.internal.util.ObjectUtils;
Dan Egnor95240272009-10-27 18:23:39 -070048
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -060049import libcore.io.IoUtils;
50
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;
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;
Makoto Onuki0e623be2017-08-22 10:36:12 -070073 private static final int DEFAULT_MAX_FILES_LOWRAM = 300;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070074 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
75 private static final int DEFAULT_QUOTA_PERCENT = 10;
76 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070077 private static final int QUOTA_RESCAN_MILLIS = 5000;
78
Craig Mautner26caf7a2012-03-04 17:17:59 -080079 // mHandler 'what' value.
80 private static final int MSG_SEND_BROADCAST = 1;
81
Dan Egnor3d40df32009-11-17 13:36:31 -080082 private static final boolean PROFILE_DUMP = false;
83
Dan Egnor4410ec82009-09-11 16:40:01 -070084 // TODO: This implementation currently uses one file per entry, which is
85 // inefficient for smallish entries -- consider using a single queue file
86 // per tag (or even globally) instead.
87
88 // The cached context and derived objects
89
Dan Egnor4410ec82009-09-11 16:40:01 -070090 private final ContentResolver mContentResolver;
91 private final File mDropBoxDir;
92
93 // Accounting of all currently written log files (set in init()).
94
95 private FileList mAllFiles = null;
Makoto Onukiff94e032017-08-08 14:58:19 -070096 private ArrayMap<String, FileList> mFilesByTag = null;
Dan Egnor4410ec82009-09-11 16:40:01 -070097
98 // Various bits of disk information
99
100 private StatFs mStatFs = null;
101 private int mBlockSize = 0;
102 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
103 private long mCachedQuotaUptimeMillis = 0;
104
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800105 private volatile boolean mBooted = false;
106
Craig Mautner26caf7a2012-03-04 17:17:59 -0800107 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
108 private final Handler mHandler;
109
Makoto Onuki0e623be2017-08-22 10:36:12 -0700110 private int mMaxFiles = -1; // -1 means uninitialized.
111
Dan Egnor4410ec82009-09-11 16:40:01 -0700112 /** Receives events that might indicate a need to clean up files. */
113 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
114 @Override
115 public void onReceive(Context context, Intent intent) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700116 // For ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700117 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700118
119 // Run the initialization in the background (not this main thread).
120 // The init() and trimToFit() methods are synchronized, so they still
121 // block other users -- but at least the onReceive() call can finish.
122 new Thread() {
123 public void run() {
124 try {
125 init();
126 trimToFit();
127 } catch (IOException e) {
128 Slog.e(TAG, "Can't init", e);
129 }
130 }
131 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700132 }
133 };
134
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700135 private final IDropBoxManagerService.Stub mStub = new IDropBoxManagerService.Stub() {
136 @Override
137 public void add(DropBoxManager.Entry entry) {
138 DropBoxManagerService.this.add(entry);
139 }
140
141 @Override
142 public boolean isTagEnabled(String tag) {
143 return DropBoxManagerService.this.isTagEnabled(tag);
144 }
145
146 @Override
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -0600147 public DropBoxManager.Entry getNextEntry(String tag, long millis, String callingPackage) {
148 return DropBoxManagerService.this.getNextEntry(tag, millis, callingPackage);
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700149 }
150
151 @Override
152 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
153 DropBoxManagerService.this.dump(fd, pw, args);
154 }
155 };
156
157 /**
158 * Creates an instance of managed drop box storage using the default dropbox
159 * directory.
160 *
161 * @param context to use for receiving free space & gservices intents
162 */
163 public DropBoxManagerService(final Context context) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700164 this(context, new File("/data/system/dropbox"), FgThread.get().getLooper());
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700165 }
166
Dan Egnor4410ec82009-09-11 16:40:01 -0700167 /**
168 * Creates an instance of managed drop box storage. Normally there is one of these
169 * run by the system, but others can be created for testing and other purposes.
170 *
171 * @param context to use for receiving free space & gservices intents
172 * @param path to store drop box entries in
173 */
Makoto Onukiff94e032017-08-08 14:58:19 -0700174 @VisibleForTesting
175 public DropBoxManagerService(final Context context, File path, Looper looper) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700176 super(context);
Dan Egnor4410ec82009-09-11 16:40:01 -0700177 mDropBoxDir = path;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700178 mContentResolver = getContext().getContentResolver();
Makoto Onukiff94e032017-08-08 14:58:19 -0700179 mHandler = new Handler(looper) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700180 @Override
181 public void handleMessage(Message msg) {
182 if (msg.what == MSG_SEND_BROADCAST) {
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700183 getContext().sendBroadcastAsUser((Intent)msg.obj, UserHandle.SYSTEM,
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700184 android.Manifest.permission.READ_LOGS);
185 }
186 }
187 };
188 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700189
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700190 @Override
191 public void onStart() {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700192 publishBinderService(Context.DROPBOX_SERVICE, mStub);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800193
Dan Egnor4410ec82009-09-11 16:40:01 -0700194 // The real work gets done lazily in init() -- that way service creation always
195 // succeeds, and things like disk problems cause individual method failures.
196 }
197
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700198 @Override
199 public void onBootPhase(int phase) {
200 switch (phase) {
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600201 case PHASE_SYSTEM_SERVICES_READY:
202 IntentFilter filter = new IntentFilter();
203 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
204 getContext().registerReceiver(mReceiver, filter);
205
206 mContentResolver.registerContentObserver(
207 Settings.Global.CONTENT_URI, true,
208 new ContentObserver(new Handler()) {
209 @Override
210 public void onChange(boolean selfChange) {
211 mReceiver.onReceive(getContext(), (Intent) null);
212 }
213 });
214 break;
215
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700216 case PHASE_BOOT_COMPLETED:
217 mBooted = true;
218 break;
219 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700220 }
221
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700222 /** Retrieves the binder stub -- for test instances */
223 public IDropBoxManagerService getServiceStub() {
224 return mStub;
225 }
226
Dan Egnorf18a01c2009-11-12 11:32:50 -0800227 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700228 File temp = null;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700229 InputStream input = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700230 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700231 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700232 try {
Dan Egnor95240272009-10-27 18:23:39 -0700233 int flags = entry.getFlags();
Dan Egnorf18a01c2009-11-12 11:32:50 -0800234 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700235
236 init();
237 if (!isTagEnabled(tag)) return;
238 long max = trimToFit();
239 long lastTrim = System.currentTimeMillis();
240
241 byte[] buffer = new byte[mBlockSize];
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700242 input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700243
244 // First, accumulate up to one block worth of data in memory before
245 // deciding whether to compress the data or not.
246
247 int read = 0;
248 while (read < buffer.length) {
249 int n = input.read(buffer, read, buffer.length - read);
250 if (n <= 0) break;
251 read += n;
252 }
253
254 // If we have at least one block, compress it -- otherwise, just write
255 // the data in uncompressed form.
256
257 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700258 int bufferSize = mBlockSize;
259 if (bufferSize > 4096) bufferSize = 4096;
260 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700261 FileOutputStream foutput = new FileOutputStream(temp);
262 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800263 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700264 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800265 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700266 }
267
268 do {
269 output.write(buffer, 0, read);
270
271 long now = System.currentTimeMillis();
272 if (now - lastTrim > 30 * 1000) {
273 max = trimToFit(); // In case data dribbles in slowly
274 lastTrim = now;
275 }
276
277 read = input.read(buffer);
278 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700279 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700280 output.close(); // Get a final size measurement
281 output = null;
282 } else {
283 output.flush(); // So the size measurement is pseudo-reasonable
284 }
285
286 long len = temp.length();
287 if (len > max) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800288 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700289 temp.delete();
290 temp = null; // Pass temp = null to createEntry() to leave a tombstone
291 break;
292 }
293 } while (read > 0);
294
Hakan Stillb2475362010-12-07 14:05:55 +0100295 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700296 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100297
Craig Mautner26caf7a2012-03-04 17:17:59 -0800298 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
Hakan Stillb2475362010-12-07 14:05:55 +0100299 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
300 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800301 if (!mBooted) {
302 dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
303 }
Craig Mautner26caf7a2012-03-04 17:17:59 -0800304 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
305 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
306 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
307 // very lock while waiting for the WindowManagerService lock.
308 mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
Dan Egnor4410ec82009-09-11 16:40:01 -0700309 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800310 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700311 } finally {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700312 IoUtils.closeQuietly(output);
313 IoUtils.closeQuietly(input);
Dan Egnor95240272009-10-27 18:23:39 -0700314 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700315 if (temp != null) temp.delete();
316 }
317 }
318
319 public boolean isTagEnabled(String tag) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700320 final long token = Binder.clearCallingIdentity();
321 try {
322 return !"disabled".equals(Settings.Global.getString(
323 mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
324 } finally {
325 Binder.restoreCallingIdentity(token);
326 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700327 }
328
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -0600329 private boolean checkPermission(int callingUid, String callingPackage) {
330 // Callers always need this permission
331 getContext().enforceCallingOrSelfPermission(
332 android.Manifest.permission.READ_LOGS, TAG);
333
334 // Callers also need the ability to read usage statistics
335 switch (getContext().getSystemService(AppOpsManager.class)
336 .noteOp(AppOpsManager.OP_GET_USAGE_STATS, callingUid, callingPackage)) {
337 case AppOpsManager.MODE_ALLOWED:
338 return true;
339 case AppOpsManager.MODE_DEFAULT:
340 getContext().enforceCallingOrSelfPermission(
341 android.Manifest.permission.PACKAGE_USAGE_STATS, TAG);
342 return true;
343 default:
344 return false;
345 }
346 }
347
348 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis,
349 String callingPackage) {
350 if (!checkPermission(Binder.getCallingUid(), callingPackage)) {
351 return null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700352 }
353
354 try {
355 init();
356 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800357 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700358 return null;
359 }
360
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700361 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
362 if (list == null) return null;
363
364 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700365 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800366 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
367 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700368 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700369 final File file = entry.getFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700370 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800371 return new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700372 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700373 } catch (IOException e) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700374 Slog.wtf(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700375 // Continue to next file
376 }
377 }
378
379 return null;
380 }
381
382 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -0600383 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700384
385 try {
386 init();
387 } catch (IOException e) {
388 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800389 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700390 return;
391 }
392
Dan Egnor3d40df32009-11-17 13:36:31 -0800393 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
394
Dan Egnor5ec249a2009-11-25 13:16:47 -0800395 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700396 boolean doPrint = false, doFile = false;
397 ArrayList<String> searchArgs = new ArrayList<String>();
398 for (int i = 0; args != null && i < args.length; i++) {
399 if (args[i].equals("-p") || args[i].equals("--print")) {
400 doPrint = true;
401 } else if (args[i].equals("-f") || args[i].equals("--file")) {
402 doFile = true;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700403 } else if (args[i].equals("-h") || args[i].equals("--help")) {
404 pw.println("Dropbox (dropbox) dump options:");
405 pw.println(" [-h|--help] [-p|--print] [-f|--file] [timestamp]");
406 pw.println(" -h|--help: print this help");
407 pw.println(" -p|--print: print full contents of each entry");
408 pw.println(" -f|--file: print path of each entry's file");
409 pw.println(" [timestamp] optionally filters to only those entries.");
410 return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700411 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800412 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700413 } else {
414 searchArgs.add(args[i]);
415 }
416 }
417
Dan Egnor5ec249a2009-11-25 13:16:47 -0800418 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Makoto Onuki0e623be2017-08-22 10:36:12 -0700419 out.append("Max entries: ").append(mMaxFiles).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700420
421 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800422 out.append("Searching for:");
423 for (String a : searchArgs) out.append(" ").append(a);
424 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700425 }
426
Dan Egnor3d40df32009-11-17 13:36:31 -0800427 int numFound = 0, numArgs = searchArgs.size();
428 Time time = new Time();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800429 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700430 for (EntryFile entry : mAllFiles.contents) {
Dan Egnor3d40df32009-11-17 13:36:31 -0800431 time.set(entry.timestampMillis);
432 String date = time.format("%Y-%m-%d %H:%M:%S");
Dan Egnor4410ec82009-09-11 16:40:01 -0700433 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800434 for (int i = 0; i < numArgs && match; i++) {
435 String arg = searchArgs.get(i);
436 match = (date.contains(arg) || arg.equals(entry.tag));
437 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700438 if (!match) continue;
439
440 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800441 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800442 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Makoto Onukiff94e032017-08-08 14:58:19 -0700443
444 final File file = entry.getFile(mDropBoxDir);
445 if (file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800446 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700447 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800448 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800449 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700450 continue;
451 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800452 out.append(" (");
453 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
454 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
Makoto Onukiff94e032017-08-08 14:58:19 -0700455 out.append(", ").append(file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700456 }
457
Dan Egnorf18a01c2009-11-12 11:32:50 -0800458 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800459 if (!doPrint) out.append(" ");
Makoto Onukiff94e032017-08-08 14:58:19 -0700460 out.append(file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700461 }
462
Dan Egnorf18a01c2009-11-12 11:32:50 -0800463 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
464 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800465 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700466 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800467 dbe = new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700468 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700469
470 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800471 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700472 char[] buf = new char[4096];
473 boolean newline = false;
474 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800475 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700476 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800477 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700478 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800479
480 // Flush periodically when printing to avoid out-of-memory.
481 if (out.length() > 65536) {
482 pw.write(out.toString());
483 out.setLength(0);
484 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700485 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800486 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700487 } else {
488 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800489 out.append(" ");
490 if (text == null) {
491 out.append("[null]");
492 } else {
493 boolean truncated = (text.length() == 70);
494 out.append(text.trim().replace('\n', '/'));
495 if (truncated) out.append(" ...");
496 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800497 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700498 }
499 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800500 out.append("*** ").append(e.toString()).append("\n");
Makoto Onukiff94e032017-08-08 14:58:19 -0700501 Slog.e(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700502 } finally {
503 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800504 if (isr != null) {
505 try {
506 isr.close();
507 } catch (IOException unused) {
508 }
509 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700510 }
511 }
512
Dan Egnor5ec249a2009-11-25 13:16:47 -0800513 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700514 }
515
Dan Egnor5ec249a2009-11-25 13:16:47 -0800516 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700517
518 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800519 if (!doPrint) out.append("\n");
520 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700521 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800522
523 pw.write(out.toString());
524 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700525 }
526
527 ///////////////////////////////////////////////////////////////////////////
528
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700529 /** Chronologically sorted list of {@link EntryFile} */
Dan Egnor4410ec82009-09-11 16:40:01 -0700530 private static final class FileList implements Comparable<FileList> {
531 public int blocks = 0;
532 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
533
534 /** Sorts bigger FileList instances before smaller ones. */
535 public final int compareTo(FileList o) {
536 if (blocks != o.blocks) return o.blocks - blocks;
537 if (this == o) return 0;
538 if (hashCode() < o.hashCode()) return -1;
539 if (hashCode() > o.hashCode()) return 1;
540 return 0;
541 }
542 }
543
Makoto Onukiff94e032017-08-08 14:58:19 -0700544 /**
545 * Metadata describing an on-disk log file.
546 *
547 * Note its instances do no have knowledge on what directory they're stored, just to save
548 * 4/8 bytes per instance. Instead, {@link #getFile} takes a directory so it can build a
549 * fullpath.
550 */
551 @VisibleForTesting
552 static final class EntryFile implements Comparable<EntryFile> {
Dan Egnor4410ec82009-09-11 16:40:01 -0700553 public final String tag;
554 public final long timestampMillis;
555 public final int flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700556 public final int blocks;
557
558 /** Sorts earlier EntryFile instances before later ones. */
559 public final int compareTo(EntryFile o) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700560 int comp = Long.compare(timestampMillis, o.timestampMillis);
561 if (comp != 0) return comp;
562
563 comp = ObjectUtils.compare(tag, o.tag);
564 if (comp != 0) return comp;
565
566 comp = Integer.compare(flags, o.flags);
567 if (comp != 0) return comp;
568
569 return Integer.compare(hashCode(), o.hashCode());
Dan Egnor4410ec82009-09-11 16:40:01 -0700570 }
571
572 /**
573 * Moves an existing temporary file to a new log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700574 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700575 * @param temp file to rename
576 * @param dir to store file in
577 * @param tag to use for new log file name
578 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700579 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700580 * @param blockSize to use for space accounting
581 * @throws IOException if the file can't be moved
582 */
583 public EntryFile(File temp, File dir, String tag,long timestampMillis,
584 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800585 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700586
Makoto Onukiff94e032017-08-08 14:58:19 -0700587 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700588 this.timestampMillis = timestampMillis;
589 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700590
Makoto Onukiff94e032017-08-08 14:58:19 -0700591 final File file = this.getFile(dir);
592 if (!temp.renameTo(file)) {
593 throw new IOException("Can't rename " + temp + " to " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700594 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700595 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700596 }
597
598 /**
599 * Creates a zero-length tombstone for a file whose contents were lost.
Makoto Onukiff94e032017-08-08 14:58:19 -0700600 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700601 * @param dir to store file in
602 * @param tag to use for new log file name
603 * @param timestampMillis of log entry
604 * @throws IOException if the file can't be created.
605 */
606 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
Makoto Onukiff94e032017-08-08 14:58:19 -0700607 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700608 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800609 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700610 this.blocks = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700611 new FileOutputStream(getFile(dir)).close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700612 }
613
614 /**
615 * Extracts metadata from an existing on-disk log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700616 *
617 * Note when a filename is not recognizable, it will create an instance that
618 * {@link #hasFile()} would return false on, and also remove the file.
619 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700620 * @param file name of existing log file
621 * @param blockSize to use for space accounting
622 */
623 public EntryFile(File file, int blockSize) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700624
625 boolean parseFailure = false;
Dan Egnor4410ec82009-09-11 16:40:01 -0700626
627 String name = file.getName();
Dan Egnor4410ec82009-09-11 16:40:01 -0700628 int flags = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700629 String tag = null;
630 long millis = 0;
631
632 final int at = name.lastIndexOf('@');
633 if (at < 0) {
634 parseFailure = true;
Dan Egnor4410ec82009-09-11 16:40:01 -0700635 } else {
Makoto Onukiff94e032017-08-08 14:58:19 -0700636 tag = Uri.decode(name.substring(0, at));
637 if (name.endsWith(".gz")) {
638 flags |= DropBoxManager.IS_GZIPPED;
639 name = name.substring(0, name.length() - 3);
640 }
641 if (name.endsWith(".lost")) {
642 flags |= DropBoxManager.IS_EMPTY;
643 name = name.substring(at + 1, name.length() - 5);
644 } else if (name.endsWith(".txt")) {
645 flags |= DropBoxManager.IS_TEXT;
646 name = name.substring(at + 1, name.length() - 4);
647 } else if (name.endsWith(".dat")) {
648 name = name.substring(at + 1, name.length() - 4);
649 } else {
650 parseFailure = true;
651 }
652 if (!parseFailure) {
653 try {
654 millis = Long.parseLong(name);
655 } catch (NumberFormatException e) {
656 parseFailure = true;
657 }
658 }
659 }
660 if (parseFailure) {
661 Slog.wtf(TAG, "Invalid filename: " + file);
662
663 // Remove the file and return an empty instance.
664 file.delete();
665 this.tag = null;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800666 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700667 this.timestampMillis = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700668 this.blocks = 0;
Dan Egnor4410ec82009-09-11 16:40:01 -0700669 return;
670 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700671
Makoto Onukiff94e032017-08-08 14:58:19 -0700672 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
673 this.tag = TextUtils.safeIntern(tag);
674 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700675 this.timestampMillis = millis;
676 }
677
678 /**
679 * Creates a EntryFile object with only a timestamp for comparison purposes.
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700680 * @param millis to compare with.
Dan Egnor4410ec82009-09-11 16:40:01 -0700681 */
682 public EntryFile(long millis) {
683 this.tag = null;
684 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800685 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700686 this.blocks = 0;
687 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700688
689 /**
690 * @return whether an entry actually has a backing file, or it's an empty "tombstone"
691 * entry.
692 */
693 public boolean hasFile() {
694 return tag != null;
695 }
696
697 /** @return File extension for the flags. */
698 private String getExtension() {
699 if ((flags & DropBoxManager.IS_EMPTY) != 0) {
700 return ".lost";
701 }
702 return ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
703 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : "");
704 }
705
706 /**
707 * @return filename for this entry without the pathname.
708 */
709 public String getFilename() {
710 return hasFile() ? Uri.encode(tag) + "@" + timestampMillis + getExtension() : null;
711 }
712
713 /**
714 * Get a full-path {@link File} representing this entry.
715 * @param dir Parent directly. The caller needs to pass it because {@link EntryFile}s don't
716 * know in which directory they're stored.
717 */
718 public File getFile(File dir) {
719 return hasFile() ? new File(dir, getFilename()) : null;
720 }
721
722 /**
723 * If an entry has a backing file, remove it.
724 */
725 public void deleteFile(File dir) {
726 if (hasFile()) {
727 getFile(dir).delete();
728 }
729 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700730 }
731
732 ///////////////////////////////////////////////////////////////////////////
733
734 /** If never run before, scans disk contents to build in-memory tracking data. */
735 private synchronized void init() throws IOException {
736 if (mStatFs == null) {
737 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
738 throw new IOException("Can't mkdir: " + mDropBoxDir);
739 }
740 try {
741 mStatFs = new StatFs(mDropBoxDir.getPath());
742 mBlockSize = mStatFs.getBlockSize();
743 } catch (IllegalArgumentException e) { // StatFs throws this on error
744 throw new IOException("Can't statfs: " + mDropBoxDir);
745 }
746 }
747
748 if (mAllFiles == null) {
749 File[] files = mDropBoxDir.listFiles();
750 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
751
752 mAllFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700753 mFilesByTag = new ArrayMap<>();
Dan Egnor4410ec82009-09-11 16:40:01 -0700754
755 // Scan pre-existing files.
756 for (File file : files) {
757 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800758 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700759 file.delete();
760 continue;
761 }
762
763 EntryFile entry = new EntryFile(file, mBlockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700764
Makoto Onukiff94e032017-08-08 14:58:19 -0700765 if (entry.hasFile()) {
766 // Enroll only when the filename is valid. Otherwise the above constructor
767 // has removed the file already.
768 enrollEntry(entry);
769 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700770 }
771 }
772 }
773
774 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
775 private synchronized void enrollEntry(EntryFile entry) {
776 mAllFiles.contents.add(entry);
777 mAllFiles.blocks += entry.blocks;
778
779 // mFilesByTag is used for trimming, so don't list empty files.
780 // (Zero-length/lost files are trimmed by date from mAllFiles.)
781
Makoto Onukiff94e032017-08-08 14:58:19 -0700782 if (entry.hasFile() && entry.blocks > 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700783 FileList tagFiles = mFilesByTag.get(entry.tag);
784 if (tagFiles == null) {
785 tagFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700786 mFilesByTag.put(TextUtils.safeIntern(entry.tag), tagFiles);
Dan Egnor4410ec82009-09-11 16:40:01 -0700787 }
788 tagFiles.contents.add(entry);
789 tagFiles.blocks += entry.blocks;
790 }
791 }
792
793 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100794 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700795 long t = System.currentTimeMillis();
796
797 // Require each entry to have a unique timestamp; if there are entries
798 // >10sec in the future (due to clock skew), drag them back to avoid
799 // keeping them around forever.
800
801 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
802 EntryFile[] future = null;
803 if (!tail.isEmpty()) {
804 future = tail.toArray(new EntryFile[tail.size()]);
805 tail.clear(); // Remove from mAllFiles
806 }
807
808 if (!mAllFiles.contents.isEmpty()) {
809 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
810 }
811
812 if (future != null) {
813 for (EntryFile late : future) {
814 mAllFiles.blocks -= late.blocks;
815 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800816 if (tagFiles != null && tagFiles.contents.remove(late)) {
817 tagFiles.blocks -= late.blocks;
818 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800819 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700820 enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
821 late.tag, t++, late.flags, mBlockSize));
Dan Egnor4410ec82009-09-11 16:40:01 -0700822 } else {
823 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
824 }
825 }
826 }
827
828 if (temp == null) {
829 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
830 } else {
831 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
832 }
Hakan Stillb2475362010-12-07 14:05:55 +0100833 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700834 }
835
836 /**
837 * Trims the files on disk to make sure they aren't using too much space.
838 * @return the overall quota for storage (in bytes)
839 */
songjinshic5e249b2016-07-27 20:36:46 +0800840 private synchronized long trimToFit() throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700841 // Expunge aged items (including tombstones marking deleted data).
842
Jeff Sharkey625239a2012-09-26 22:03:49 -0700843 int ageSeconds = Settings.Global.getInt(mContentResolver,
844 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Makoto Onuki0e623be2017-08-22 10:36:12 -0700845 mMaxFiles = Settings.Global.getInt(mContentResolver,
846 Settings.Global.DROPBOX_MAX_FILES,
847 (ActivityManager.isLowRamDeviceStatic()
848 ? DEFAULT_MAX_FILES_LOWRAM : DEFAULT_MAX_FILES));
Dan Egnor4410ec82009-09-11 16:40:01 -0700849 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
850 while (!mAllFiles.contents.isEmpty()) {
851 EntryFile entry = mAllFiles.contents.first();
Makoto Onuki0e623be2017-08-22 10:36:12 -0700852 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < mMaxFiles) {
853 break;
854 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700855
856 FileList tag = mFilesByTag.get(entry.tag);
857 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
858 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
Makoto Onukiff94e032017-08-08 14:58:19 -0700859 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700860 }
861
862 // Compute overall quota (a fraction of available free space) in blocks.
863 // The quota changes dynamically based on the amount of free space;
864 // that way when lots of data is available we can use it, but we'll get
865 // out of the way if storage starts getting tight.
866
867 long uptimeMillis = SystemClock.uptimeMillis();
868 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -0700869 int quotaPercent = Settings.Global.getInt(mContentResolver,
870 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
871 int reservePercent = Settings.Global.getInt(mContentResolver,
872 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
873 int quotaKb = Settings.Global.getInt(mContentResolver,
874 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -0700875
songjinshic5e249b2016-07-27 20:36:46 +0800876 String dirPath = mDropBoxDir.getPath();
877 try {
878 mStatFs.restat(dirPath);
879 } catch (IllegalArgumentException e) { // restat throws this on error
880 throw new IOException("Can't restat: " + mDropBoxDir);
881 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700882 int available = mStatFs.getAvailableBlocks();
883 int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
884 int maximum = quotaKb * 1024 / mBlockSize;
885 mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
886 mCachedQuotaUptimeMillis = uptimeMillis;
887 }
888
889 // If we're using too much space, delete old items to make room.
890 //
891 // We trim each tag independently (this is why we keep per-tag lists).
892 // Space is "fairly" shared between tags -- they are all squeezed
893 // equally until enough space is reclaimed.
894 //
895 // A single circular buffer (a la logcat) would be simpler, but this
896 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
897 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700898 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -0700899 //
900 // Deleted files are replaced with zero-length tombstones to mark what
901 // was lost. Tombstones are expunged by age (see above).
902
903 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700904 // Find a fair share amount of space to limit each tag
905 int unsqueezed = mAllFiles.blocks, squeezed = 0;
906 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
907 for (FileList tag : tags) {
908 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
909 break;
910 }
911 unsqueezed -= tag.blocks;
912 squeezed++;
913 }
914 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
915
916 // Remove old items from each tag until it meets the per-tag quota.
917 for (FileList tag : tags) {
918 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
919 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
920 EntryFile entry = tag.contents.first();
921 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
922 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
923
924 try {
Makoto Onukiff94e032017-08-08 14:58:19 -0700925 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700926 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
927 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800928 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700929 }
930 }
931 }
932 }
933
934 return mCachedQuotaBlocks * mBlockSize;
935 }
936}