blob: cbbcb0e66860518daeae2cda0987dbf5ecac7d22 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007-2008 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
Adam Lesinski182f73f2013-12-05 16:48:06 -080017package com.android.server.storage;
18
19import com.android.server.EventLogTags;
20import com.android.server.SystemService;
Fyodor Kupoloveeea67b2015-02-23 17:14:45 -080021import com.android.server.pm.InstructionSets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.app.Notification;
23import android.app.NotificationManager;
24import android.app.PendingIntent;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.IPackageDataObserver;
29import android.content.pm.IPackageManager;
Dianne Hackborn197a0c82012-07-12 14:46:04 -070030import android.content.pm.PackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.Binder;
Dianne Hackbornf882efa2012-04-11 16:04:12 -070032import android.os.Environment;
Jeff Sharkey4b496572012-04-19 14:17:03 -070033import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080035import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.RemoteException;
38import android.os.ServiceManager;
39import android.os.StatFs;
40import android.os.SystemClock;
41import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070042import android.os.UserHandle;
Jeff Sharkeybe722152013-02-15 16:56:38 -080043import android.os.storage.StorageManager;
Doug Zongker43866e02010-01-07 12:09:54 -080044import android.provider.Settings;
Dianne Hackborn197a0c82012-07-12 14:46:04 -070045import android.text.format.Formatter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080047import android.util.Slog;
Dianne Hackborn197a0c82012-07-12 14:46:04 -070048import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
Jeff Sharkeybe722152013-02-15 16:56:38 -080050import java.io.File;
51import java.io.FileDescriptor;
52import java.io.PrintWriter;
53
Brian Carlstroma39871e2014-09-29 13:44:04 -070054import dalvik.system.VMRuntime;
55
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056/**
Doug Zongker43866e02010-01-07 12:09:54 -080057 * This class implements a service to monitor the amount of disk
58 * storage space on the device. If the free storage on device is less
59 * than a tunable threshold value (a secure settings parameter;
60 * default 10%) a low memory notification is displayed to alert the
61 * user. If the user clicks on the low memory notification the
62 * Application Manager application gets launched to let the user free
63 * storage space.
64 *
65 * Event log events: A low memory event with the free storage on
66 * device in bytes is logged to the event log when the device goes low
67 * on storage space. The amount of free storage on the device is
68 * periodically logged to the event log. The log interval is a secure
69 * settings parameter with a default value of 12 hours. When the free
70 * storage differential goes below a threshold (again a secure
71 * settings parameter with a default value of 2MB), the free memory is
72 * logged to the event log.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 */
Adam Lesinski182f73f2013-12-05 16:48:06 -080074public class DeviceStorageMonitorService extends SystemService {
75 static final String TAG = "DeviceStorageMonitorService";
Jeff Sharkeybe722152013-02-15 16:56:38 -080076
Jeff Sharkey529f91f2015-04-18 20:23:13 -070077 // TODO: extend to watch and manage caches on all private volumes
78
Adam Lesinski182f73f2013-12-05 16:48:06 -080079 static final boolean DEBUG = false;
80 static final boolean localLOGV = false;
Jeff Sharkeybe722152013-02-15 16:56:38 -080081
Adam Lesinski182f73f2013-12-05 16:48:06 -080082 static final int DEVICE_MEMORY_WHAT = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 private static final int MONITOR_INTERVAL = 1; //in minutes
84 private static final int LOW_MEMORY_NOTIFICATION_ID = 1;
Jeff Sharkeybe722152013-02-15 16:56:38 -080085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 private static final int DEFAULT_FREE_STORAGE_LOG_INTERVAL_IN_MINUTES = 12*60; //in minutes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 private static final long DEFAULT_DISK_FREE_CHANGE_REPORTING_THRESHOLD = 2 * 1024 * 1024; // 2MB
88 private static final long DEFAULT_CHECK_INTERVAL = MONITOR_INTERVAL*60*1000;
Jeff Sharkeybe722152013-02-15 16:56:38 -080089
Doug Zongker3161795b2009-10-07 15:14:03 -070090 private long mFreeMem; // on /data
Dianne Hackborn197a0c82012-07-12 14:46:04 -070091 private long mFreeMemAfterLastCacheClear; // on /data
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 private long mLastReportedFreeMem;
93 private long mLastReportedFreeMemTime;
Adam Lesinski182f73f2013-12-05 16:48:06 -080094 boolean mLowMemFlag=false;
Jake Hambybb371632010-08-23 18:16:48 -070095 private boolean mMemFullFlag=false;
Brian Carlstroma39871e2014-09-29 13:44:04 -070096 private final boolean mIsBootImageOnDisk;
Jeff Brownb880d882014-02-10 19:47:07 -080097 private final ContentResolver mResolver;
98 private final long mTotalMemory; // on /data
99 private final StatFs mDataFileStats;
100 private final StatFs mSystemFileStats;
101 private final StatFs mCacheFileStats;
Jeff Sharkeybe722152013-02-15 16:56:38 -0800102
103 private static final File DATA_PATH = Environment.getDataDirectory();
104 private static final File SYSTEM_PATH = Environment.getRootDirectory();
105 private static final File CACHE_PATH = Environment.getDownloadCacheDirectory();
106
Doug Zongker3161795b2009-10-07 15:14:03 -0700107 private long mThreadStartTime = -1;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 boolean mClearSucceeded = false;
109 boolean mClearingCache;
Jeff Brownb880d882014-02-10 19:47:07 -0800110 private final Intent mStorageLowIntent;
111 private final Intent mStorageOkIntent;
112 private final Intent mStorageFullIntent;
113 private final Intent mStorageNotFullIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private CachePackageDataObserver mClearCacheObserver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 private CacheFileDeletedObserver mCacheFileDeletedObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 private static final int _TRUE = 1;
117 private static final int _FALSE = 0;
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700118 // This is the raw threshold that has been set at which we consider
119 // storage to be low.
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 long mMemLowThreshold;
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700121 // This is the threshold at which we start trying to flush caches
122 // to get below the low threshold limit. It is less than the low
123 // threshold; we will allow storage to get a bit beyond the limit
124 // before flushing and checking if we are actually low.
125 private long mMemCacheStartTrimThreshold;
126 // This is the threshold that we try to get to when deleting cache
127 // files. This is greater than the low threshold so that we will flush
128 // more files than absolutely needed, to reduce the frequency that
129 // flushing takes place.
130 private long mMemCacheTrimToThreshold;
Jeff Sharkeybe722152013-02-15 16:56:38 -0800131 private long mMemFullThreshold;
Doug Zongker3161795b2009-10-07 15:14:03 -0700132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 /**
134 * This string is used for ServiceManager access to this class.
135 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800136 static final String SERVICE = "devicestoragemonitor";
Doug Zongker3161795b2009-10-07 15:14:03 -0700137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 /**
Doug Zongker3161795b2009-10-07 15:14:03 -0700139 * Handler that checks the amount of disk space on the device and sends a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 * notification if the device runs low on disk space
141 */
Jeff Brownb880d882014-02-10 19:47:07 -0800142 private final Handler mHandler = new Handler() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 @Override
144 public void handleMessage(Message msg) {
Jake Hambybb371632010-08-23 18:16:48 -0700145 //don't handle an invalid message
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 if (msg.what != DEVICE_MEMORY_WHAT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800147 Slog.e(TAG, "Will not process invalid message");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 return;
149 }
150 checkMemory(msg.arg1 == _TRUE);
151 }
152 };
Doug Zongker3161795b2009-10-07 15:14:03 -0700153
Adam Lesinski182f73f2013-12-05 16:48:06 -0800154 private class CachePackageDataObserver extends IPackageDataObserver.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 public void onRemoveCompleted(String packageName, boolean succeeded) {
156 mClearSucceeded = succeeded;
157 mClearingCache = false;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800158 if(localLOGV) Slog.i(TAG, " Clear succeeded:"+mClearSucceeded
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 +", mClearingCache:"+mClearingCache+" Forcing memory check");
160 postCheckMemoryMsg(false, 0);
Doug Zongker3161795b2009-10-07 15:14:03 -0700161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700163
Adam Lesinski182f73f2013-12-05 16:48:06 -0800164 private void restatDataDir() {
Doug Zongker3161795b2009-10-07 15:14:03 -0700165 try {
Jeff Sharkeybe722152013-02-15 16:56:38 -0800166 mDataFileStats.restat(DATA_PATH.getAbsolutePath());
Doug Zongker3161795b2009-10-07 15:14:03 -0700167 mFreeMem = (long) mDataFileStats.getAvailableBlocks() *
168 mDataFileStats.getBlockSize();
169 } catch (IllegalArgumentException e) {
170 // use the old value of mFreeMem
171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 // Allow freemem to be overridden by debug.freemem for testing
173 String debugFreeMem = SystemProperties.get("debug.freemem");
174 if (!"".equals(debugFreeMem)) {
175 mFreeMem = Long.parseLong(debugFreeMem);
176 }
Doug Zongker43866e02010-01-07 12:09:54 -0800177 // Read the log interval from secure settings
Jeff Sharkeybe722152013-02-15 16:56:38 -0800178 long freeMemLogInterval = Settings.Global.getLong(mResolver,
Jeff Sharkey625239a2012-09-26 22:03:49 -0700179 Settings.Global.SYS_FREE_STORAGE_LOG_INTERVAL,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 DEFAULT_FREE_STORAGE_LOG_INTERVAL_IN_MINUTES)*60*1000;
181 //log the amount of free memory in event log
182 long currTime = SystemClock.elapsedRealtime();
Doug Zongker3161795b2009-10-07 15:14:03 -0700183 if((mLastReportedFreeMemTime == 0) ||
184 (currTime-mLastReportedFreeMemTime) >= freeMemLogInterval) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 mLastReportedFreeMemTime = currTime;
Doug Zongker3161795b2009-10-07 15:14:03 -0700186 long mFreeSystem = -1, mFreeCache = -1;
187 try {
Jeff Sharkeybe722152013-02-15 16:56:38 -0800188 mSystemFileStats.restat(SYSTEM_PATH.getAbsolutePath());
Doug Zongker3161795b2009-10-07 15:14:03 -0700189 mFreeSystem = (long) mSystemFileStats.getAvailableBlocks() *
190 mSystemFileStats.getBlockSize();
191 } catch (IllegalArgumentException e) {
192 // ignore; report -1
193 }
194 try {
Jeff Sharkeybe722152013-02-15 16:56:38 -0800195 mCacheFileStats.restat(CACHE_PATH.getAbsolutePath());
Doug Zongker3161795b2009-10-07 15:14:03 -0700196 mFreeCache = (long) mCacheFileStats.getAvailableBlocks() *
197 mCacheFileStats.getBlockSize();
198 } catch (IllegalArgumentException e) {
199 // ignore; report -1
200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800201 EventLog.writeEvent(EventLogTags.FREE_STORAGE_LEFT,
Doug Zongker3161795b2009-10-07 15:14:03 -0700202 mFreeMem, mFreeSystem, mFreeCache);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 }
Doug Zongker43866e02010-01-07 12:09:54 -0800204 // Read the reporting threshold from secure settings
Jeff Sharkeybe722152013-02-15 16:56:38 -0800205 long threshold = Settings.Global.getLong(mResolver,
Jeff Sharkey625239a2012-09-26 22:03:49 -0700206 Settings.Global.DISK_FREE_CHANGE_REPORTING_THRESHOLD,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 DEFAULT_DISK_FREE_CHANGE_REPORTING_THRESHOLD);
208 // If mFree changed significantly log the new value
209 long delta = mFreeMem - mLastReportedFreeMem;
210 if (delta > threshold || delta < -threshold) {
211 mLastReportedFreeMem = mFreeMem;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800212 EventLog.writeEvent(EventLogTags.FREE_STORAGE_CHANGED, mFreeMem);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 }
214 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700215
Adam Lesinski182f73f2013-12-05 16:48:06 -0800216 private void clearCache() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 if (mClearCacheObserver == null) {
218 // Lazy instantiation
219 mClearCacheObserver = new CachePackageDataObserver();
220 }
221 mClearingCache = true;
222 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800223 if (localLOGV) Slog.i(TAG, "Clearing cache");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 IPackageManager.Stub.asInterface(ServiceManager.getService("package")).
Jeff Sharkey529f91f2015-04-18 20:23:13 -0700225 freeStorageAndNotify(null, mMemCacheTrimToThreshold, mClearCacheObserver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800227 Slog.w(TAG, "Failed to get handle for PackageManger Exception: "+e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 mClearingCache = false;
229 mClearSucceeded = false;
230 }
231 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700232
Adam Lesinski182f73f2013-12-05 16:48:06 -0800233 void checkMemory(boolean checkCache) {
Doug Zongker3161795b2009-10-07 15:14:03 -0700234 //if the thread that was started to clear cache is still running do nothing till its
235 //finished clearing cache. Ideally this flag could be modified by clearCache
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 // and should be accessed via a lock but even if it does this test will fail now and
237 //hopefully the next time this flag will be set to the correct value.
238 if(mClearingCache) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800239 if(localLOGV) Slog.i(TAG, "Thread already running just skip");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 //make sure the thread is not hung for too long
241 long diffTime = System.currentTimeMillis() - mThreadStartTime;
242 if(diffTime > (10*60*1000)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800243 Slog.w(TAG, "Thread that clears cache file seems to run for ever");
Doug Zongker3161795b2009-10-07 15:14:03 -0700244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 } else {
246 restatDataDir();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800247 if (localLOGV) Slog.v(TAG, "freeMemory="+mFreeMem);
Doug Zongker3161795b2009-10-07 15:14:03 -0700248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 //post intent to NotificationManager to display icon if necessary
Jake Hambybb371632010-08-23 18:16:48 -0700250 if (mFreeMem < mMemLowThreshold) {
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700251 if (checkCache) {
252 // We are allowed to clear cache files at this point to
253 // try to get down below the limit, because this is not
254 // the initial call after a cache clear has been attempted.
255 // In this case we will try a cache clear if our free
256 // space has gone below the cache clear limit.
257 if (mFreeMem < mMemCacheStartTrimThreshold) {
258 // We only clear the cache if the free storage has changed
259 // a significant amount since the last time.
260 if ((mFreeMemAfterLastCacheClear-mFreeMem)
261 >= ((mMemLowThreshold-mMemCacheStartTrimThreshold)/4)) {
262 // See if clearing cache helps
263 // Note that clearing cache is asynchronous and so we do a
264 // memory check again once the cache has been cleared.
265 mThreadStartTime = System.currentTimeMillis();
266 mClearSucceeded = false;
267 clearCache();
268 }
269 }
270 } else {
271 // This is a call from after clearing the cache. Note
272 // the amount of free storage at this point.
273 mFreeMemAfterLastCacheClear = mFreeMem;
274 if (!mLowMemFlag) {
275 // We tried to clear the cache, but that didn't get us
276 // below the low storage limit. Tell the user.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800277 Slog.i(TAG, "Running low on memory. Sending notification");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 sendNotification();
279 mLowMemFlag = true;
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700280 } else {
281 if (localLOGV) Slog.v(TAG, "Running low on memory " +
282 "notification already sent. do nothing");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285 } else {
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700286 mFreeMemAfterLastCacheClear = mFreeMem;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 if (mLowMemFlag) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800288 Slog.i(TAG, "Memory available. Cancelling notification");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 cancelNotification();
290 mLowMemFlag = false;
291 }
292 }
Brian Carlstroma39871e2014-09-29 13:44:04 -0700293 if (!mLowMemFlag && !mIsBootImageOnDisk) {
294 Slog.i(TAG, "No boot image on disk due to lack of space. Sending notification");
295 sendNotification();
296 }
Jake Hambybb371632010-08-23 18:16:48 -0700297 if (mFreeMem < mMemFullThreshold) {
298 if (!mMemFullFlag) {
299 sendFullNotification();
300 mMemFullFlag = true;
301 }
302 } else {
303 if (mMemFullFlag) {
304 cancelFullNotification();
305 mMemFullFlag = false;
306 }
307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800309 if(localLOGV) Slog.i(TAG, "Posting Message again");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 //keep posting messages to itself periodically
311 postCheckMemoryMsg(true, DEFAULT_CHECK_INTERVAL);
312 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700313
Adam Lesinski182f73f2013-12-05 16:48:06 -0800314 void postCheckMemoryMsg(boolean clearCache, long delay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 // Remove queued messages
316 mHandler.removeMessages(DEVICE_MEMORY_WHAT);
317 mHandler.sendMessageDelayed(mHandler.obtainMessage(DEVICE_MEMORY_WHAT,
318 clearCache ?_TRUE : _FALSE, 0),
319 delay);
320 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700321
Jeff Brownb880d882014-02-10 19:47:07 -0800322 public DeviceStorageMonitorService(Context context) {
323 super(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 mLastReportedFreeMemTime = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800325 mResolver = context.getContentResolver();
Brian Carlstroma39871e2014-09-29 13:44:04 -0700326 mIsBootImageOnDisk = isBootImageOnDisk();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 //create StatFs object
Jeff Sharkeybe722152013-02-15 16:56:38 -0800328 mDataFileStats = new StatFs(DATA_PATH.getAbsolutePath());
329 mSystemFileStats = new StatFs(SYSTEM_PATH.getAbsolutePath());
330 mCacheFileStats = new StatFs(CACHE_PATH.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 //initialize total storage on device
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700332 mTotalMemory = (long)mDataFileStats.getBlockCount() *
333 mDataFileStats.getBlockSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 mStorageLowIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_LOW);
Jeff Hamilton4b330922010-06-04 15:16:06 -0500335 mStorageLowIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 mStorageOkIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_OK);
Jeff Hamilton4b330922010-06-04 15:16:06 -0500337 mStorageOkIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Jake Hambybb371632010-08-23 18:16:48 -0700338 mStorageFullIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_FULL);
339 mStorageFullIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
340 mStorageNotFullIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_NOT_FULL);
341 mStorageNotFullIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800342 }
Jeff Sharkeybe722152013-02-15 16:56:38 -0800343
Brian Carlstroma39871e2014-09-29 13:44:04 -0700344 private static boolean isBootImageOnDisk() {
Fyodor Kupoloveeea67b2015-02-23 17:14:45 -0800345 for (String instructionSet : InstructionSets.getAllDexCodeInstructionSets()) {
Brian Carlstroma39871e2014-09-29 13:44:04 -0700346 if (!VMRuntime.isBootClassPathOnDisk(instructionSet)) {
347 return false;
348 }
349 }
350 return true;
351 }
352
Jeff Brownb880d882014-02-10 19:47:07 -0800353 /**
354 * Initializes the disk space threshold value and posts an empty message to
355 * kickstart the process.
356 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800357 @Override
358 public void onStart() {
Jake Hambybb371632010-08-23 18:16:48 -0700359 // cache storage thresholds
Adam Lesinski182f73f2013-12-05 16:48:06 -0800360 final StorageManager sm = StorageManager.from(getContext());
Jeff Sharkeybe722152013-02-15 16:56:38 -0800361 mMemLowThreshold = sm.getStorageLowBytes(DATA_PATH);
362 mMemFullThreshold = sm.getStorageFullBytes(DATA_PATH);
363
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700364 mMemCacheStartTrimThreshold = ((mMemLowThreshold*3)+mMemFullThreshold)/4;
365 mMemCacheTrimToThreshold = mMemLowThreshold
366 + ((mMemLowThreshold-mMemCacheStartTrimThreshold)*2);
367 mFreeMemAfterLastCacheClear = mTotalMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 checkMemory(true);
Jeff Sharkey4b496572012-04-19 14:17:03 -0700369
370 mCacheFileDeletedObserver = new CacheFileDeletedObserver();
371 mCacheFileDeletedObserver.startWatching();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800372
373 publishBinderService(SERVICE, mRemoteService);
374 publishLocalService(DeviceStorageMonitorInternal.class, mLocalService);
375 }
376
377 private final DeviceStorageMonitorInternal mLocalService = new DeviceStorageMonitorInternal() {
378 @Override
379 public void checkMemory() {
380 // force an early check
381 postCheckMemoryMsg(true, 0);
382 }
383
384 @Override
385 public boolean isMemoryLow() {
Brian Carlstroma39871e2014-09-29 13:44:04 -0700386 return mLowMemFlag || !mIsBootImageOnDisk;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800387 }
388
389 @Override
390 public long getMemoryLowThreshold() {
391 return mMemLowThreshold;
392 }
393 };
394
395 private final IBinder mRemoteService = new Binder() {
396 @Override
397 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
398 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
399 != PackageManager.PERMISSION_GRANTED) {
400
401 pw.println("Permission Denial: can't dump " + SERVICE + " from from pid="
402 + Binder.getCallingPid()
403 + ", uid=" + Binder.getCallingUid());
404 return;
405 }
406
407 dumpImpl(pw);
408 }
409 };
410
411 void dumpImpl(PrintWriter pw) {
412 final Context context = getContext();
413
414 pw.println("Current DeviceStorageMonitor state:");
415
416 pw.print(" mFreeMem="); pw.print(Formatter.formatFileSize(context, mFreeMem));
417 pw.print(" mTotalMemory=");
418 pw.println(Formatter.formatFileSize(context, mTotalMemory));
419
420 pw.print(" mFreeMemAfterLastCacheClear=");
421 pw.println(Formatter.formatFileSize(context, mFreeMemAfterLastCacheClear));
422
423 pw.print(" mLastReportedFreeMem=");
424 pw.print(Formatter.formatFileSize(context, mLastReportedFreeMem));
425 pw.print(" mLastReportedFreeMemTime=");
426 TimeUtils.formatDuration(mLastReportedFreeMemTime, SystemClock.elapsedRealtime(), pw);
427 pw.println();
428
429 pw.print(" mLowMemFlag="); pw.print(mLowMemFlag);
430 pw.print(" mMemFullFlag="); pw.println(mMemFullFlag);
Brian Carlstroma39871e2014-09-29 13:44:04 -0700431 pw.print(" mIsBootImageOnDisk="); pw.print(mIsBootImageOnDisk);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800432
433 pw.print(" mClearSucceeded="); pw.print(mClearSucceeded);
434 pw.print(" mClearingCache="); pw.println(mClearingCache);
435
436 pw.print(" mMemLowThreshold=");
437 pw.print(Formatter.formatFileSize(context, mMemLowThreshold));
438 pw.print(" mMemFullThreshold=");
439 pw.println(Formatter.formatFileSize(context, mMemFullThreshold));
440
441 pw.print(" mMemCacheStartTrimThreshold=");
442 pw.print(Formatter.formatFileSize(context, mMemCacheStartTrimThreshold));
443 pw.print(" mMemCacheTrimToThreshold=");
444 pw.println(Formatter.formatFileSize(context, mMemCacheTrimToThreshold));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 /**
448 * This method sends a notification to NotificationManager to display
449 * an error dialog indicating low disk space and launch the Installer
450 * application
451 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800452 private void sendNotification() {
453 final Context context = getContext();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800454 if(localLOGV) Slog.i(TAG, "Sending low memory notification");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 //log the event to event log with the amount of free storage(in bytes) left on the device
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800456 EventLog.writeEvent(EventLogTags.LOW_STORAGE, mFreeMem);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 // Pack up the values and broadcast them to everyone
Dianne Hackbornf882efa2012-04-11 16:04:12 -0700458 Intent lowMemIntent = new Intent(Environment.isExternalStorageEmulated()
459 ? Settings.ACTION_INTERNAL_STORAGE_SETTINGS
460 : Intent.ACTION_MANAGE_PACKAGE_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 lowMemIntent.putExtra("memory", mFreeMem);
462 lowMemIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Doug Zongker3161795b2009-10-07 15:14:03 -0700463 NotificationManager mNotificationMgr =
Adam Lesinski182f73f2013-12-05 16:48:06 -0800464 (NotificationManager)context.getSystemService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 Context.NOTIFICATION_SERVICE);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800466 CharSequence title = context.getText(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 com.android.internal.R.string.low_internal_storage_view_title);
Brian Carlstroma39871e2014-09-29 13:44:04 -0700468 CharSequence details = context.getText(mIsBootImageOnDisk
469 ? com.android.internal.R.string.low_internal_storage_view_text
470 : com.android.internal.R.string.low_internal_storage_view_text_no_boot);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800471 PendingIntent intent = PendingIntent.getActivityAsUser(context, 0, lowMemIntent, 0,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700472 null, UserHandle.CURRENT);
Brian Carlstroma39871e2014-09-29 13:44:04 -0700473 Notification notification = new Notification.Builder(context)
474 .setSmallIcon(com.android.internal.R.drawable.stat_notify_disk_full)
475 .setTicker(title)
Alan Viverette4a357cd2015-03-18 18:37:18 -0700476 .setColor(context.getColor(
Brian Carlstroma39871e2014-09-29 13:44:04 -0700477 com.android.internal.R.color.system_notification_accent_color))
478 .setContentTitle(title)
479 .setContentText(details)
480 .setContentIntent(intent)
481 .setStyle(new Notification.BigTextStyle()
482 .bigText(details))
483 .setVisibility(Notification.VISIBILITY_PUBLIC)
484 .setCategory(Notification.CATEGORY_SYSTEM)
485 .build();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 notification.flags |= Notification.FLAG_NO_CLEAR;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700487 mNotificationMgr.notifyAsUser(null, LOW_MEMORY_NOTIFICATION_ID, notification,
488 UserHandle.ALL);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800489 context.sendStickyBroadcastAsUser(mStorageLowIntent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 }
491
492 /**
493 * Cancels low storage notification and sends OK intent.
494 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800495 private void cancelNotification() {
496 final Context context = getContext();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800497 if(localLOGV) Slog.i(TAG, "Canceling low memory notification");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 NotificationManager mNotificationMgr =
Adam Lesinski182f73f2013-12-05 16:48:06 -0800499 (NotificationManager)context.getSystemService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 Context.NOTIFICATION_SERVICE);
501 //cancel notification since memory has been freed
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700502 mNotificationMgr.cancelAsUser(null, LOW_MEMORY_NOTIFICATION_ID, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503
Adam Lesinski182f73f2013-12-05 16:48:06 -0800504 context.removeStickyBroadcastAsUser(mStorageLowIntent, UserHandle.ALL);
505 context.sendBroadcastAsUser(mStorageOkIntent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700507
Jake Hambybb371632010-08-23 18:16:48 -0700508 /**
509 * Send a notification when storage is full.
510 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800511 private void sendFullNotification() {
Jake Hambybb371632010-08-23 18:16:48 -0700512 if(localLOGV) Slog.i(TAG, "Sending memory full notification");
Adam Lesinski182f73f2013-12-05 16:48:06 -0800513 getContext().sendStickyBroadcastAsUser(mStorageFullIntent, UserHandle.ALL);
Jake Hambybb371632010-08-23 18:16:48 -0700514 }
515
516 /**
517 * Cancels memory full notification and sends "not full" intent.
518 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800519 private void cancelFullNotification() {
Jake Hambybb371632010-08-23 18:16:48 -0700520 if(localLOGV) Slog.i(TAG, "Canceling memory full notification");
Adam Lesinski182f73f2013-12-05 16:48:06 -0800521 getContext().removeStickyBroadcastAsUser(mStorageFullIntent, UserHandle.ALL);
522 getContext().sendBroadcastAsUser(mStorageNotFullIntent, UserHandle.ALL);
Jake Hambybb371632010-08-23 18:16:48 -0700523 }
524
Adam Lesinski182f73f2013-12-05 16:48:06 -0800525 private static class CacheFileDeletedObserver extends FileObserver {
Jeff Sharkey4b496572012-04-19 14:17:03 -0700526 public CacheFileDeletedObserver() {
527 super(Environment.getDownloadCacheDirectory().getAbsolutePath(), FileObserver.DELETE);
528 }
529
530 @Override
531 public void onEvent(int event, String path) {
532 EventLogTags.writeCacheFileDeleted(path);
533 }
534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535}