blob: afdec9ffddc32466dcc15b3f9784929047e3ccda [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
Dmitri Plotnikovd6bd6b92017-01-27 16:42:12 -080019import android.app.NotificationChannel;
Adam Lesinski182f73f2013-12-05 16:48:06 -080020import com.android.server.EventLogTags;
21import com.android.server.SystemService;
Fyodor Kupoloveeea67b2015-02-23 17:14:45 -080022import com.android.server.pm.InstructionSets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.app.Notification;
24import android.app.NotificationManager;
25import android.app.PendingIntent;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.pm.IPackageDataObserver;
30import android.content.pm.IPackageManager;
Dianne Hackborn197a0c82012-07-12 14:46:04 -070031import android.content.pm.PackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.os.Binder;
Dianne Hackbornf882efa2012-04-11 16:04:12 -070033import android.os.Environment;
Jeff Sharkey4b496572012-04-19 14:17:03 -070034import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080036import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.RemoteException;
39import android.os.ServiceManager;
40import android.os.StatFs;
41import android.os.SystemClock;
42import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070043import android.os.UserHandle;
Jeff Sharkeybe722152013-02-15 16:56:38 -080044import android.os.storage.StorageManager;
Doug Zongker43866e02010-01-07 12:09:54 -080045import android.provider.Settings;
Dianne Hackborn197a0c82012-07-12 14:46:04 -070046import android.text.format.Formatter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080048import android.util.Slog;
Dianne Hackborn197a0c82012-07-12 14:46:04 -070049import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050
Jeff Sharkeybe722152013-02-15 16:56:38 -080051import java.io.File;
52import java.io.FileDescriptor;
53import java.io.PrintWriter;
54
Brian Carlstroma39871e2014-09-29 13:44:04 -070055import dalvik.system.VMRuntime;
56
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057/**
Doug Zongker43866e02010-01-07 12:09:54 -080058 * This class implements a service to monitor the amount of disk
59 * storage space on the device. If the free storage on device is less
60 * than a tunable threshold value (a secure settings parameter;
61 * default 10%) a low memory notification is displayed to alert the
62 * user. If the user clicks on the low memory notification the
63 * Application Manager application gets launched to let the user free
64 * storage space.
65 *
66 * Event log events: A low memory event with the free storage on
67 * device in bytes is logged to the event log when the device goes low
68 * on storage space. The amount of free storage on the device is
69 * periodically logged to the event log. The log interval is a secure
70 * settings parameter with a default value of 12 hours. When the free
71 * storage differential goes below a threshold (again a secure
72 * settings parameter with a default value of 2MB), the free memory is
73 * logged to the event log.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 */
Adam Lesinski182f73f2013-12-05 16:48:06 -080075public class DeviceStorageMonitorService extends SystemService {
76 static final String TAG = "DeviceStorageMonitorService";
Jeff Sharkeybe722152013-02-15 16:56:38 -080077
Jeff Sharkey529f91f2015-04-18 20:23:13 -070078 // TODO: extend to watch and manage caches on all private volumes
79
Adam Lesinski182f73f2013-12-05 16:48:06 -080080 static final boolean DEBUG = false;
81 static final boolean localLOGV = false;
Jeff Sharkeybe722152013-02-15 16:56:38 -080082
Adam Lesinski182f73f2013-12-05 16:48:06 -080083 static final int DEVICE_MEMORY_WHAT = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 private static final int MONITOR_INTERVAL = 1; //in minutes
85 private static final int LOW_MEMORY_NOTIFICATION_ID = 1;
Jeff Sharkeybe722152013-02-15 16:56:38 -080086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 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 -080088 private static final long DEFAULT_DISK_FREE_CHANGE_REPORTING_THRESHOLD = 2 * 1024 * 1024; // 2MB
89 private static final long DEFAULT_CHECK_INTERVAL = MONITOR_INTERVAL*60*1000;
Jeff Sharkeybe722152013-02-15 16:56:38 -080090
Richard Uhlerd42fe852016-08-12 13:51:51 -070091 // com.android.internal.R.string.low_internal_storage_view_text_no_boot
92 // hard codes 250MB in the message as the storage space required for the
93 // boot image.
94 private static final long BOOT_IMAGE_STORAGE_REQUIREMENT = 250 * 1024 * 1024;
95
Doug Zongker3161795b2009-10-07 15:14:03 -070096 private long mFreeMem; // on /data
Dianne Hackborn197a0c82012-07-12 14:46:04 -070097 private long mFreeMemAfterLastCacheClear; // on /data
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private long mLastReportedFreeMem;
99 private long mLastReportedFreeMemTime;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800100 boolean mLowMemFlag=false;
Jake Hambybb371632010-08-23 18:16:48 -0700101 private boolean mMemFullFlag=false;
Brian Carlstroma39871e2014-09-29 13:44:04 -0700102 private final boolean mIsBootImageOnDisk;
Jeff Brownb880d882014-02-10 19:47:07 -0800103 private final ContentResolver mResolver;
104 private final long mTotalMemory; // on /data
105 private final StatFs mDataFileStats;
106 private final StatFs mSystemFileStats;
107 private final StatFs mCacheFileStats;
Jeff Sharkeybe722152013-02-15 16:56:38 -0800108
109 private static final File DATA_PATH = Environment.getDataDirectory();
110 private static final File SYSTEM_PATH = Environment.getRootDirectory();
111 private static final File CACHE_PATH = Environment.getDownloadCacheDirectory();
112
Doug Zongker3161795b2009-10-07 15:14:03 -0700113 private long mThreadStartTime = -1;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 boolean mClearSucceeded = false;
115 boolean mClearingCache;
Jeff Brownb880d882014-02-10 19:47:07 -0800116 private final Intent mStorageLowIntent;
117 private final Intent mStorageOkIntent;
118 private final Intent mStorageFullIntent;
119 private final Intent mStorageNotFullIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 private CachePackageDataObserver mClearCacheObserver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 private CacheFileDeletedObserver mCacheFileDeletedObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private static final int _TRUE = 1;
123 private static final int _FALSE = 0;
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700124 // This is the raw threshold that has been set at which we consider
125 // storage to be low.
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 long mMemLowThreshold;
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700127 // This is the threshold at which we start trying to flush caches
128 // to get below the low threshold limit. It is less than the low
129 // threshold; we will allow storage to get a bit beyond the limit
130 // before flushing and checking if we are actually low.
131 private long mMemCacheStartTrimThreshold;
132 // This is the threshold that we try to get to when deleting cache
133 // files. This is greater than the low threshold so that we will flush
134 // more files than absolutely needed, to reduce the frequency that
135 // flushing takes place.
136 private long mMemCacheTrimToThreshold;
Jeff Sharkeybe722152013-02-15 16:56:38 -0800137 private long mMemFullThreshold;
Doug Zongker3161795b2009-10-07 15:14:03 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 /**
140 * This string is used for ServiceManager access to this class.
141 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 static final String SERVICE = "devicestoragemonitor";
Doug Zongker3161795b2009-10-07 15:14:03 -0700143
Dmitri Plotnikovd6bd6b92017-01-27 16:42:12 -0800144 private static final String NOTIFICATION_CHANNEL_ID = SERVICE;
145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 /**
Doug Zongker3161795b2009-10-07 15:14:03 -0700147 * Handler that checks the amount of disk space on the device and sends a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 * notification if the device runs low on disk space
149 */
Jeff Brownb880d882014-02-10 19:47:07 -0800150 private final Handler mHandler = new Handler() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 @Override
152 public void handleMessage(Message msg) {
Jake Hambybb371632010-08-23 18:16:48 -0700153 //don't handle an invalid message
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 if (msg.what != DEVICE_MEMORY_WHAT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800155 Slog.e(TAG, "Will not process invalid message");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 return;
157 }
158 checkMemory(msg.arg1 == _TRUE);
159 }
160 };
Doug Zongker3161795b2009-10-07 15:14:03 -0700161
Adam Lesinski182f73f2013-12-05 16:48:06 -0800162 private class CachePackageDataObserver extends IPackageDataObserver.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 public void onRemoveCompleted(String packageName, boolean succeeded) {
164 mClearSucceeded = succeeded;
165 mClearingCache = false;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800166 if(localLOGV) Slog.i(TAG, " Clear succeeded:"+mClearSucceeded
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 +", mClearingCache:"+mClearingCache+" Forcing memory check");
168 postCheckMemoryMsg(false, 0);
Doug Zongker3161795b2009-10-07 15:14:03 -0700169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700171
Adam Lesinski182f73f2013-12-05 16:48:06 -0800172 private void restatDataDir() {
Doug Zongker3161795b2009-10-07 15:14:03 -0700173 try {
Jeff Sharkeybe722152013-02-15 16:56:38 -0800174 mDataFileStats.restat(DATA_PATH.getAbsolutePath());
Doug Zongker3161795b2009-10-07 15:14:03 -0700175 mFreeMem = (long) mDataFileStats.getAvailableBlocks() *
176 mDataFileStats.getBlockSize();
177 } catch (IllegalArgumentException e) {
178 // use the old value of mFreeMem
179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 // Allow freemem to be overridden by debug.freemem for testing
181 String debugFreeMem = SystemProperties.get("debug.freemem");
182 if (!"".equals(debugFreeMem)) {
183 mFreeMem = Long.parseLong(debugFreeMem);
184 }
Doug Zongker43866e02010-01-07 12:09:54 -0800185 // Read the log interval from secure settings
Jeff Sharkeybe722152013-02-15 16:56:38 -0800186 long freeMemLogInterval = Settings.Global.getLong(mResolver,
Jeff Sharkey625239a2012-09-26 22:03:49 -0700187 Settings.Global.SYS_FREE_STORAGE_LOG_INTERVAL,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 DEFAULT_FREE_STORAGE_LOG_INTERVAL_IN_MINUTES)*60*1000;
189 //log the amount of free memory in event log
190 long currTime = SystemClock.elapsedRealtime();
Doug Zongker3161795b2009-10-07 15:14:03 -0700191 if((mLastReportedFreeMemTime == 0) ||
192 (currTime-mLastReportedFreeMemTime) >= freeMemLogInterval) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 mLastReportedFreeMemTime = currTime;
Doug Zongker3161795b2009-10-07 15:14:03 -0700194 long mFreeSystem = -1, mFreeCache = -1;
195 try {
Jeff Sharkeybe722152013-02-15 16:56:38 -0800196 mSystemFileStats.restat(SYSTEM_PATH.getAbsolutePath());
Doug Zongker3161795b2009-10-07 15:14:03 -0700197 mFreeSystem = (long) mSystemFileStats.getAvailableBlocks() *
198 mSystemFileStats.getBlockSize();
199 } catch (IllegalArgumentException e) {
200 // ignore; report -1
201 }
202 try {
Jeff Sharkeybe722152013-02-15 16:56:38 -0800203 mCacheFileStats.restat(CACHE_PATH.getAbsolutePath());
Doug Zongker3161795b2009-10-07 15:14:03 -0700204 mFreeCache = (long) mCacheFileStats.getAvailableBlocks() *
205 mCacheFileStats.getBlockSize();
206 } catch (IllegalArgumentException e) {
207 // ignore; report -1
208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800209 EventLog.writeEvent(EventLogTags.FREE_STORAGE_LEFT,
Doug Zongker3161795b2009-10-07 15:14:03 -0700210 mFreeMem, mFreeSystem, mFreeCache);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 }
Doug Zongker43866e02010-01-07 12:09:54 -0800212 // Read the reporting threshold from secure settings
Jeff Sharkeybe722152013-02-15 16:56:38 -0800213 long threshold = Settings.Global.getLong(mResolver,
Jeff Sharkey625239a2012-09-26 22:03:49 -0700214 Settings.Global.DISK_FREE_CHANGE_REPORTING_THRESHOLD,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 DEFAULT_DISK_FREE_CHANGE_REPORTING_THRESHOLD);
216 // If mFree changed significantly log the new value
217 long delta = mFreeMem - mLastReportedFreeMem;
218 if (delta > threshold || delta < -threshold) {
219 mLastReportedFreeMem = mFreeMem;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800220 EventLog.writeEvent(EventLogTags.FREE_STORAGE_CHANGED, mFreeMem);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 }
222 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700223
Adam Lesinski182f73f2013-12-05 16:48:06 -0800224 private void clearCache() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 if (mClearCacheObserver == null) {
226 // Lazy instantiation
227 mClearCacheObserver = new CachePackageDataObserver();
228 }
229 mClearingCache = true;
230 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800231 if (localLOGV) Slog.i(TAG, "Clearing cache");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 IPackageManager.Stub.asInterface(ServiceManager.getService("package")).
Jeff Sharkey529f91f2015-04-18 20:23:13 -0700233 freeStorageAndNotify(null, mMemCacheTrimToThreshold, mClearCacheObserver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800235 Slog.w(TAG, "Failed to get handle for PackageManger Exception: "+e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 mClearingCache = false;
237 mClearSucceeded = false;
238 }
239 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700240
Adam Lesinski182f73f2013-12-05 16:48:06 -0800241 void checkMemory(boolean checkCache) {
Doug Zongker3161795b2009-10-07 15:14:03 -0700242 //if the thread that was started to clear cache is still running do nothing till its
243 //finished clearing cache. Ideally this flag could be modified by clearCache
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // and should be accessed via a lock but even if it does this test will fail now and
245 //hopefully the next time this flag will be set to the correct value.
246 if(mClearingCache) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800247 if(localLOGV) Slog.i(TAG, "Thread already running just skip");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 //make sure the thread is not hung for too long
249 long diffTime = System.currentTimeMillis() - mThreadStartTime;
250 if(diffTime > (10*60*1000)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800251 Slog.w(TAG, "Thread that clears cache file seems to run for ever");
Doug Zongker3161795b2009-10-07 15:14:03 -0700252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 } else {
254 restatDataDir();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800255 if (localLOGV) Slog.v(TAG, "freeMemory="+mFreeMem);
Doug Zongker3161795b2009-10-07 15:14:03 -0700256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 //post intent to NotificationManager to display icon if necessary
Jake Hambybb371632010-08-23 18:16:48 -0700258 if (mFreeMem < mMemLowThreshold) {
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700259 if (checkCache) {
260 // We are allowed to clear cache files at this point to
261 // try to get down below the limit, because this is not
262 // the initial call after a cache clear has been attempted.
263 // In this case we will try a cache clear if our free
264 // space has gone below the cache clear limit.
265 if (mFreeMem < mMemCacheStartTrimThreshold) {
266 // We only clear the cache if the free storage has changed
267 // a significant amount since the last time.
268 if ((mFreeMemAfterLastCacheClear-mFreeMem)
269 >= ((mMemLowThreshold-mMemCacheStartTrimThreshold)/4)) {
270 // See if clearing cache helps
271 // Note that clearing cache is asynchronous and so we do a
272 // memory check again once the cache has been cleared.
273 mThreadStartTime = System.currentTimeMillis();
274 mClearSucceeded = false;
275 clearCache();
276 }
277 }
278 } else {
279 // This is a call from after clearing the cache. Note
280 // the amount of free storage at this point.
281 mFreeMemAfterLastCacheClear = mFreeMem;
282 if (!mLowMemFlag) {
283 // We tried to clear the cache, but that didn't get us
284 // below the low storage limit. Tell the user.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800285 Slog.i(TAG, "Running low on memory. Sending notification");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 sendNotification();
287 mLowMemFlag = true;
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700288 } else {
289 if (localLOGV) Slog.v(TAG, "Running low on memory " +
290 "notification already sent. do nothing");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 }
293 } else {
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700294 mFreeMemAfterLastCacheClear = mFreeMem;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 if (mLowMemFlag) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800296 Slog.i(TAG, "Memory available. Cancelling notification");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 cancelNotification();
298 mLowMemFlag = false;
299 }
300 }
Richard Uhlerd42fe852016-08-12 13:51:51 -0700301 if (!mLowMemFlag && !mIsBootImageOnDisk && mFreeMem < BOOT_IMAGE_STORAGE_REQUIREMENT) {
Brian Carlstroma39871e2014-09-29 13:44:04 -0700302 Slog.i(TAG, "No boot image on disk due to lack of space. Sending notification");
303 sendNotification();
Richard Uhlerd42fe852016-08-12 13:51:51 -0700304 mLowMemFlag = true;
Brian Carlstroma39871e2014-09-29 13:44:04 -0700305 }
Jake Hambybb371632010-08-23 18:16:48 -0700306 if (mFreeMem < mMemFullThreshold) {
307 if (!mMemFullFlag) {
308 sendFullNotification();
309 mMemFullFlag = true;
310 }
311 } else {
312 if (mMemFullFlag) {
313 cancelFullNotification();
314 mMemFullFlag = false;
315 }
316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800318 if(localLOGV) Slog.i(TAG, "Posting Message again");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 //keep posting messages to itself periodically
320 postCheckMemoryMsg(true, DEFAULT_CHECK_INTERVAL);
321 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700322
Adam Lesinski182f73f2013-12-05 16:48:06 -0800323 void postCheckMemoryMsg(boolean clearCache, long delay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 // Remove queued messages
325 mHandler.removeMessages(DEVICE_MEMORY_WHAT);
326 mHandler.sendMessageDelayed(mHandler.obtainMessage(DEVICE_MEMORY_WHAT,
327 clearCache ?_TRUE : _FALSE, 0),
328 delay);
329 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700330
Jeff Brownb880d882014-02-10 19:47:07 -0800331 public DeviceStorageMonitorService(Context context) {
332 super(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 mLastReportedFreeMemTime = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800334 mResolver = context.getContentResolver();
Brian Carlstroma39871e2014-09-29 13:44:04 -0700335 mIsBootImageOnDisk = isBootImageOnDisk();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 //create StatFs object
Jeff Sharkeybe722152013-02-15 16:56:38 -0800337 mDataFileStats = new StatFs(DATA_PATH.getAbsolutePath());
338 mSystemFileStats = new StatFs(SYSTEM_PATH.getAbsolutePath());
339 mCacheFileStats = new StatFs(CACHE_PATH.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 //initialize total storage on device
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700341 mTotalMemory = (long)mDataFileStats.getBlockCount() *
342 mDataFileStats.getBlockSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 mStorageLowIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_LOW);
Christopher Tate42a386b2016-11-07 12:21:21 -0800344 mStorageLowIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
345 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 mStorageOkIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_OK);
Christopher Tate42a386b2016-11-07 12:21:21 -0800347 mStorageOkIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
348 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jake Hambybb371632010-08-23 18:16:48 -0700349 mStorageFullIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_FULL);
350 mStorageFullIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
351 mStorageNotFullIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_NOT_FULL);
352 mStorageNotFullIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800353 }
Jeff Sharkeybe722152013-02-15 16:56:38 -0800354
Brian Carlstroma39871e2014-09-29 13:44:04 -0700355 private static boolean isBootImageOnDisk() {
Fyodor Kupoloveeea67b2015-02-23 17:14:45 -0800356 for (String instructionSet : InstructionSets.getAllDexCodeInstructionSets()) {
Brian Carlstroma39871e2014-09-29 13:44:04 -0700357 if (!VMRuntime.isBootClassPathOnDisk(instructionSet)) {
358 return false;
359 }
360 }
361 return true;
362 }
363
Jeff Brownb880d882014-02-10 19:47:07 -0800364 /**
365 * Initializes the disk space threshold value and posts an empty message to
366 * kickstart the process.
367 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800368 @Override
369 public void onStart() {
Jake Hambybb371632010-08-23 18:16:48 -0700370 // cache storage thresholds
Dmitri Plotnikovd6bd6b92017-01-27 16:42:12 -0800371 Context context = getContext();
372 final StorageManager sm = StorageManager.from(context);
Jeff Sharkeybe722152013-02-15 16:56:38 -0800373 mMemLowThreshold = sm.getStorageLowBytes(DATA_PATH);
374 mMemFullThreshold = sm.getStorageFullBytes(DATA_PATH);
375
Dianne Hackborn197a0c82012-07-12 14:46:04 -0700376 mMemCacheStartTrimThreshold = ((mMemLowThreshold*3)+mMemFullThreshold)/4;
377 mMemCacheTrimToThreshold = mMemLowThreshold
378 + ((mMemLowThreshold-mMemCacheStartTrimThreshold)*2);
379 mFreeMemAfterLastCacheClear = mTotalMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 checkMemory(true);
Jeff Sharkey4b496572012-04-19 14:17:03 -0700381
382 mCacheFileDeletedObserver = new CacheFileDeletedObserver();
383 mCacheFileDeletedObserver.startWatching();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800384
Dmitri Plotnikovd6bd6b92017-01-27 16:42:12 -0800385 // Ensure that the notification channel is set up
386 NotificationManager notificationMgr =
387 (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
388 PackageManager packageManager = context.getPackageManager();
389 boolean isTv = packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
390
391 int importance = isTv
392 ? NotificationManager.IMPORTANCE_HIGH // Do not change: this is TV-specific
393 : NotificationManager.IMPORTANCE_LOW;
394 notificationMgr.createNotificationChannel(
395 new NotificationChannel(NOTIFICATION_CHANNEL_ID,
396 context.getString(
397 com.android.internal.R.string.device_storage_monitor_notification_channel),
398 importance));
399
Adam Lesinski182f73f2013-12-05 16:48:06 -0800400 publishBinderService(SERVICE, mRemoteService);
401 publishLocalService(DeviceStorageMonitorInternal.class, mLocalService);
402 }
403
404 private final DeviceStorageMonitorInternal mLocalService = new DeviceStorageMonitorInternal() {
405 @Override
406 public void checkMemory() {
407 // force an early check
408 postCheckMemoryMsg(true, 0);
409 }
410
411 @Override
412 public boolean isMemoryLow() {
Richard Uhlerd42fe852016-08-12 13:51:51 -0700413 return mLowMemFlag;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800414 }
415
416 @Override
417 public long getMemoryLowThreshold() {
418 return mMemLowThreshold;
419 }
420 };
421
422 private final IBinder mRemoteService = new Binder() {
423 @Override
424 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
425 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
426 != PackageManager.PERMISSION_GRANTED) {
427
428 pw.println("Permission Denial: can't dump " + SERVICE + " from from pid="
429 + Binder.getCallingPid()
430 + ", uid=" + Binder.getCallingUid());
431 return;
432 }
433
434 dumpImpl(pw);
435 }
436 };
437
438 void dumpImpl(PrintWriter pw) {
439 final Context context = getContext();
440
441 pw.println("Current DeviceStorageMonitor state:");
442
443 pw.print(" mFreeMem="); pw.print(Formatter.formatFileSize(context, mFreeMem));
444 pw.print(" mTotalMemory=");
445 pw.println(Formatter.formatFileSize(context, mTotalMemory));
446
447 pw.print(" mFreeMemAfterLastCacheClear=");
448 pw.println(Formatter.formatFileSize(context, mFreeMemAfterLastCacheClear));
449
450 pw.print(" mLastReportedFreeMem=");
451 pw.print(Formatter.formatFileSize(context, mLastReportedFreeMem));
452 pw.print(" mLastReportedFreeMemTime=");
453 TimeUtils.formatDuration(mLastReportedFreeMemTime, SystemClock.elapsedRealtime(), pw);
454 pw.println();
455
456 pw.print(" mLowMemFlag="); pw.print(mLowMemFlag);
457 pw.print(" mMemFullFlag="); pw.println(mMemFullFlag);
Brian Carlstroma39871e2014-09-29 13:44:04 -0700458 pw.print(" mIsBootImageOnDisk="); pw.print(mIsBootImageOnDisk);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800459
460 pw.print(" mClearSucceeded="); pw.print(mClearSucceeded);
461 pw.print(" mClearingCache="); pw.println(mClearingCache);
462
463 pw.print(" mMemLowThreshold=");
464 pw.print(Formatter.formatFileSize(context, mMemLowThreshold));
465 pw.print(" mMemFullThreshold=");
466 pw.println(Formatter.formatFileSize(context, mMemFullThreshold));
467
468 pw.print(" mMemCacheStartTrimThreshold=");
469 pw.print(Formatter.formatFileSize(context, mMemCacheStartTrimThreshold));
470 pw.print(" mMemCacheTrimToThreshold=");
471 pw.println(Formatter.formatFileSize(context, mMemCacheTrimToThreshold));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 /**
475 * This method sends a notification to NotificationManager to display
476 * an error dialog indicating low disk space and launch the Installer
477 * application
478 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800479 private void sendNotification() {
480 final Context context = getContext();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800481 if(localLOGV) Slog.i(TAG, "Sending low memory notification");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 //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 -0800483 EventLog.writeEvent(EventLogTags.LOW_STORAGE, mFreeMem);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 // Pack up the values and broadcast them to everyone
Daniel Nishi690346b2016-06-17 10:21:48 -0700485 Intent lowMemIntent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 lowMemIntent.putExtra("memory", mFreeMem);
487 lowMemIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Dmitri Plotnikovd6bd6b92017-01-27 16:42:12 -0800488 NotificationManager notificationMgr =
Adam Lesinski182f73f2013-12-05 16:48:06 -0800489 (NotificationManager)context.getSystemService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 Context.NOTIFICATION_SERVICE);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800491 CharSequence title = context.getText(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 com.android.internal.R.string.low_internal_storage_view_title);
Brian Carlstroma39871e2014-09-29 13:44:04 -0700493 CharSequence details = context.getText(mIsBootImageOnDisk
494 ? com.android.internal.R.string.low_internal_storage_view_text
495 : com.android.internal.R.string.low_internal_storage_view_text_no_boot);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800496 PendingIntent intent = PendingIntent.getActivityAsUser(context, 0, lowMemIntent, 0,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700497 null, UserHandle.CURRENT);
Brian Carlstroma39871e2014-09-29 13:44:04 -0700498 Notification notification = new Notification.Builder(context)
499 .setSmallIcon(com.android.internal.R.drawable.stat_notify_disk_full)
500 .setTicker(title)
Alan Viverette4a357cd2015-03-18 18:37:18 -0700501 .setColor(context.getColor(
Brian Carlstroma39871e2014-09-29 13:44:04 -0700502 com.android.internal.R.color.system_notification_accent_color))
503 .setContentTitle(title)
504 .setContentText(details)
505 .setContentIntent(intent)
506 .setStyle(new Notification.BigTextStyle()
507 .bigText(details))
508 .setVisibility(Notification.VISIBILITY_PUBLIC)
509 .setCategory(Notification.CATEGORY_SYSTEM)
Dmitri Plotnikovd6bd6b92017-01-27 16:42:12 -0800510 .setChannel(NOTIFICATION_CHANNEL_ID)
511 .extend(new Notification.TvExtender())
Brian Carlstroma39871e2014-09-29 13:44:04 -0700512 .build();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 notification.flags |= Notification.FLAG_NO_CLEAR;
Dmitri Plotnikovd6bd6b92017-01-27 16:42:12 -0800514 notificationMgr.notifyAsUser(null, LOW_MEMORY_NOTIFICATION_ID, notification,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700515 UserHandle.ALL);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800516 context.sendStickyBroadcastAsUser(mStorageLowIntent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 }
518
519 /**
520 * Cancels low storage notification and sends OK intent.
521 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800522 private void cancelNotification() {
523 final Context context = getContext();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800524 if(localLOGV) Slog.i(TAG, "Canceling low memory notification");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 NotificationManager mNotificationMgr =
Adam Lesinski182f73f2013-12-05 16:48:06 -0800526 (NotificationManager)context.getSystemService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 Context.NOTIFICATION_SERVICE);
528 //cancel notification since memory has been freed
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700529 mNotificationMgr.cancelAsUser(null, LOW_MEMORY_NOTIFICATION_ID, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530
Adam Lesinski182f73f2013-12-05 16:48:06 -0800531 context.removeStickyBroadcastAsUser(mStorageLowIntent, UserHandle.ALL);
532 context.sendBroadcastAsUser(mStorageOkIntent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700534
Jake Hambybb371632010-08-23 18:16:48 -0700535 /**
536 * Send a notification when storage is full.
537 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800538 private void sendFullNotification() {
Jake Hambybb371632010-08-23 18:16:48 -0700539 if(localLOGV) Slog.i(TAG, "Sending memory full notification");
Adam Lesinski182f73f2013-12-05 16:48:06 -0800540 getContext().sendStickyBroadcastAsUser(mStorageFullIntent, UserHandle.ALL);
Jake Hambybb371632010-08-23 18:16:48 -0700541 }
542
543 /**
544 * Cancels memory full notification and sends "not full" intent.
545 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800546 private void cancelFullNotification() {
Jake Hambybb371632010-08-23 18:16:48 -0700547 if(localLOGV) Slog.i(TAG, "Canceling memory full notification");
Adam Lesinski182f73f2013-12-05 16:48:06 -0800548 getContext().removeStickyBroadcastAsUser(mStorageFullIntent, UserHandle.ALL);
549 getContext().sendBroadcastAsUser(mStorageNotFullIntent, UserHandle.ALL);
Jake Hambybb371632010-08-23 18:16:48 -0700550 }
551
Adam Lesinski182f73f2013-12-05 16:48:06 -0800552 private static class CacheFileDeletedObserver extends FileObserver {
Jeff Sharkey4b496572012-04-19 14:17:03 -0700553 public CacheFileDeletedObserver() {
554 super(Environment.getDownloadCacheDirectory().getAbsolutePath(), FileObserver.DELETE);
555 }
556
557 @Override
558 public void onEvent(int event, String path) {
559 EventLogTags.writeCacheFileDeleted(path);
560 }
561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562}