blob: 57af02953415d74d98912f0527cba5fa463abc5b [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
17package com.android.server;
18
19import com.android.server.am.ActivityManagerService;
20import android.app.Notification;
21import android.app.NotificationManager;
22import android.app.PendingIntent;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.IPackageDataObserver;
27import android.content.pm.IPackageManager;
28import android.os.Binder;
29import android.os.Handler;
30import android.os.Message;
31import android.os.Process;
32import android.os.RemoteException;
33import android.os.ServiceManager;
34import android.os.StatFs;
35import android.os.SystemClock;
36import android.os.SystemProperties;
37import android.provider.Settings.Gservices;
38import android.util.Config;
39import android.util.EventLog;
40import android.util.Log;
41import android.provider.Settings;
42
43/**
44 * This class implements a service to monitor the amount of disk storage space
45 * on the device. If the free storage on device is less than a tunable threshold value
Doug Zongker3161795b2009-10-07 15:14:03 -070046 * (default is 10%. this value is a gservices parameter) a low memory notification is
47 * displayed to alert the user. If the user clicks on the low memory notification the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048 * Application Manager application gets launched to let the user free storage space.
49 * Event log events:
50 * A low memory event with the free storage on device in bytes is logged to the event log
51 * when the device goes low on storage space.
52 * The amount of free storage on the device is periodically logged to the event log. The log
53 * interval is a gservices parameter with a default value of 12 hours
54 * When the free storage differential goes below a threshold(again a gservices parameter with
55 * a default value of 2MB), the free memory is logged to the event log
56 */
57class DeviceStorageMonitorService extends Binder {
58 private static final String TAG = "DeviceStorageMonitorService";
59 private static final boolean DEBUG = false;
60 private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
61 private static final int DEVICE_MEMORY_WHAT = 1;
62 private static final int MONITOR_INTERVAL = 1; //in minutes
63 private static final int LOW_MEMORY_NOTIFICATION_ID = 1;
64 private static final int DEFAULT_THRESHOLD_PERCENTAGE = 10;
65 private static final int DEFAULT_FREE_STORAGE_LOG_INTERVAL_IN_MINUTES = 12*60; //in minutes
66 private static final int EVENT_LOG_STORAGE_BELOW_THRESHOLD = 2744;
67 private static final int EVENT_LOG_LOW_STORAGE_NOTIFICATION = 2745;
68 private static final int EVENT_LOG_FREE_STORAGE_LEFT = 2746;
69 private static final long DEFAULT_DISK_FREE_CHANGE_REPORTING_THRESHOLD = 2 * 1024 * 1024; // 2MB
70 private static final long DEFAULT_CHECK_INTERVAL = MONITOR_INTERVAL*60*1000;
Doug Zongker3161795b2009-10-07 15:14:03 -070071 private long mFreeMem; // on /data
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private long mLastReportedFreeMem;
73 private long mLastReportedFreeMemTime;
74 private boolean mLowMemFlag=false;
75 private Context mContext;
76 private ContentResolver mContentResolver;
Doug Zongker3161795b2009-10-07 15:14:03 -070077 private long mTotalMemory; // on /data
78 private StatFs mDataFileStats;
79 private StatFs mSystemFileStats;
80 private StatFs mCacheFileStats;
81 private static final String DATA_PATH = "/data";
82 private static final String SYSTEM_PATH = "/system";
83 private static final String CACHE_PATH = "/cache";
84 private long mThreadStartTime = -1;
85 private boolean mClearSucceeded = false;
86 private boolean mClearingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 private Intent mStorageLowIntent;
88 private Intent mStorageOkIntent;
89 private CachePackageDataObserver mClearCacheObserver;
90 private static final int _TRUE = 1;
91 private static final int _FALSE = 0;
Doug Zongker3161795b2009-10-07 15:14:03 -070092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 /**
94 * This string is used for ServiceManager access to this class.
95 */
96 static final String SERVICE = "devicestoragemonitor";
Doug Zongker3161795b2009-10-07 15:14:03 -070097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 /**
Doug Zongker3161795b2009-10-07 15:14:03 -070099 * Handler that checks the amount of disk space on the device and sends a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 * notification if the device runs low on disk space
101 */
102 Handler mHandler = new Handler() {
103 @Override
104 public void handleMessage(Message msg) {
105 //dont handle an invalid message
106 if (msg.what != DEVICE_MEMORY_WHAT) {
107 Log.e(TAG, "Will not process invalid message");
108 return;
109 }
110 checkMemory(msg.arg1 == _TRUE);
111 }
112 };
Doug Zongker3161795b2009-10-07 15:14:03 -0700113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 class CachePackageDataObserver extends IPackageDataObserver.Stub {
115 public void onRemoveCompleted(String packageName, boolean succeeded) {
116 mClearSucceeded = succeeded;
117 mClearingCache = false;
118 if(localLOGV) Log.i(TAG, " Clear succeeded:"+mClearSucceeded
119 +", mClearingCache:"+mClearingCache+" Forcing memory check");
120 postCheckMemoryMsg(false, 0);
Doug Zongker3161795b2009-10-07 15:14:03 -0700121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private final void restatDataDir() {
Doug Zongker3161795b2009-10-07 15:14:03 -0700125 try {
126 mDataFileStats.restat(DATA_PATH);
127 mFreeMem = (long) mDataFileStats.getAvailableBlocks() *
128 mDataFileStats.getBlockSize();
129 } catch (IllegalArgumentException e) {
130 // use the old value of mFreeMem
131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 // Allow freemem to be overridden by debug.freemem for testing
133 String debugFreeMem = SystemProperties.get("debug.freemem");
134 if (!"".equals(debugFreeMem)) {
135 mFreeMem = Long.parseLong(debugFreeMem);
136 }
137 // Read the log interval from Gservices
138 long freeMemLogInterval = Gservices.getLong(mContentResolver,
139 Gservices.SYS_FREE_STORAGE_LOG_INTERVAL,
140 DEFAULT_FREE_STORAGE_LOG_INTERVAL_IN_MINUTES)*60*1000;
141 //log the amount of free memory in event log
142 long currTime = SystemClock.elapsedRealtime();
Doug Zongker3161795b2009-10-07 15:14:03 -0700143 if((mLastReportedFreeMemTime == 0) ||
144 (currTime-mLastReportedFreeMemTime) >= freeMemLogInterval) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 mLastReportedFreeMemTime = currTime;
Doug Zongker3161795b2009-10-07 15:14:03 -0700146 long mFreeSystem = -1, mFreeCache = -1;
147 try {
148 mSystemFileStats.restat(SYSTEM_PATH);
149 mFreeSystem = (long) mSystemFileStats.getAvailableBlocks() *
150 mSystemFileStats.getBlockSize();
151 } catch (IllegalArgumentException e) {
152 // ignore; report -1
153 }
154 try {
155 mCacheFileStats.restat(CACHE_PATH);
156 mFreeCache = (long) mCacheFileStats.getAvailableBlocks() *
157 mCacheFileStats.getBlockSize();
158 } catch (IllegalArgumentException e) {
159 // ignore; report -1
160 }
161 mCacheFileStats.restat(CACHE_PATH);
162 EventLog.writeEvent(EVENT_LOG_FREE_STORAGE_LEFT,
163 mFreeMem, mFreeSystem, mFreeCache);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 }
165 // Read the reporting threshold from Gservices
166 long threshold = Gservices.getLong(mContentResolver,
167 Gservices.DISK_FREE_CHANGE_REPORTING_THRESHOLD,
168 DEFAULT_DISK_FREE_CHANGE_REPORTING_THRESHOLD);
169 // If mFree changed significantly log the new value
170 long delta = mFreeMem - mLastReportedFreeMem;
171 if (delta > threshold || delta < -threshold) {
172 mLastReportedFreeMem = mFreeMem;
173 EventLog.writeEvent(EVENT_LOG_STORAGE_BELOW_THRESHOLD, mFreeMem);
174 }
175 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 private final void clearCache() {
178 if (mClearCacheObserver == null) {
179 // Lazy instantiation
180 mClearCacheObserver = new CachePackageDataObserver();
181 }
182 mClearingCache = true;
183 try {
184 if (localLOGV) Log.i(TAG, "Clearing cache");
185 IPackageManager.Stub.asInterface(ServiceManager.getService("package")).
186 freeStorageAndNotify(getMemThreshold(), mClearCacheObserver);
187 } catch (RemoteException e) {
188 Log.w(TAG, "Failed to get handle for PackageManger Exception: "+e);
189 mClearingCache = false;
190 mClearSucceeded = false;
191 }
192 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 private final void checkMemory(boolean checkCache) {
Doug Zongker3161795b2009-10-07 15:14:03 -0700195 //if the thread that was started to clear cache is still running do nothing till its
196 //finished clearing cache. Ideally this flag could be modified by clearCache
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 // and should be accessed via a lock but even if it does this test will fail now and
198 //hopefully the next time this flag will be set to the correct value.
199 if(mClearingCache) {
200 if(localLOGV) Log.i(TAG, "Thread already running just skip");
201 //make sure the thread is not hung for too long
202 long diffTime = System.currentTimeMillis() - mThreadStartTime;
203 if(diffTime > (10*60*1000)) {
204 Log.w(TAG, "Thread that clears cache file seems to run for ever");
Doug Zongker3161795b2009-10-07 15:14:03 -0700205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 } else {
207 restatDataDir();
208 if (localLOGV) Log.v(TAG, "freeMemory="+mFreeMem);
Doug Zongker3161795b2009-10-07 15:14:03 -0700209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 //post intent to NotificationManager to display icon if necessary
211 long memThreshold = getMemThreshold();
212 if (mFreeMem < memThreshold) {
213 if (!mLowMemFlag) {
214 if (checkCache) {
215 // See if clearing cache helps
216 // Note that clearing cache is asynchronous and so we do a
217 // memory check again once the cache has been cleared.
218 mThreadStartTime = System.currentTimeMillis();
219 mClearSucceeded = false;
220 clearCache();
221 } else {
222 Log.i(TAG, "Running low on memory. Sending notification");
223 sendNotification();
224 mLowMemFlag = true;
225 }
226 } else {
227 if (localLOGV) Log.v(TAG, "Running low on memory " +
228 "notification already sent. do nothing");
229 }
230 } else {
231 if (mLowMemFlag) {
232 Log.i(TAG, "Memory available. Cancelling notification");
233 cancelNotification();
234 mLowMemFlag = false;
235 }
236 }
237 }
238 if(localLOGV) Log.i(TAG, "Posting Message again");
239 //keep posting messages to itself periodically
240 postCheckMemoryMsg(true, DEFAULT_CHECK_INTERVAL);
241 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 private void postCheckMemoryMsg(boolean clearCache, long delay) {
244 // Remove queued messages
245 mHandler.removeMessages(DEVICE_MEMORY_WHAT);
246 mHandler.sendMessageDelayed(mHandler.obtainMessage(DEVICE_MEMORY_WHAT,
247 clearCache ?_TRUE : _FALSE, 0),
248 delay);
249 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 /*
Doug Zongker3161795b2009-10-07 15:14:03 -0700252 * just query settings to retrieve the memory threshold.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 * Preferred this over using a ContentObserver since Settings.Gservices caches the value
254 * any way
255 */
256 private long getMemThreshold() {
257 int value = Settings.Gservices.getInt(
Doug Zongker3161795b2009-10-07 15:14:03 -0700258 mContentResolver,
259 Settings.Gservices.SYS_STORAGE_THRESHOLD_PERCENTAGE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 DEFAULT_THRESHOLD_PERCENTAGE);
261 if(localLOGV) Log.v(TAG, "Threshold Percentage="+value);
262 //evaluate threshold value
263 return mTotalMemory*value;
264 }
265
266 /**
267 * Constructor to run service. initializes the disk space threshold value
268 * and posts an empty message to kickstart the process.
269 */
270 public DeviceStorageMonitorService(Context context) {
271 mLastReportedFreeMemTime = 0;
272 mContext = context;
273 mContentResolver = mContext.getContentResolver();
274 //create StatFs object
Doug Zongker3161795b2009-10-07 15:14:03 -0700275 mDataFileStats = new StatFs(DATA_PATH);
276 mSystemFileStats = new StatFs(SYSTEM_PATH);
277 mCacheFileStats = new StatFs(CACHE_PATH);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 //initialize total storage on device
Doug Zongker3161795b2009-10-07 15:14:03 -0700279 mTotalMemory = ((long)mDataFileStats.getBlockCount() *
280 mDataFileStats.getBlockSize())/100L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 mStorageLowIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_LOW);
282 mStorageOkIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_OK);
283 checkMemory(true);
284 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286
287 /**
288 * This method sends a notification to NotificationManager to display
289 * an error dialog indicating low disk space and launch the Installer
290 * application
291 */
292 private final void sendNotification() {
293 if(localLOGV) Log.i(TAG, "Sending low memory notification");
294 //log the event to event log with the amount of free storage(in bytes) left on the device
295 EventLog.writeEvent(EVENT_LOG_LOW_STORAGE_NOTIFICATION, mFreeMem);
296 // Pack up the values and broadcast them to everyone
297 Intent lowMemIntent = new Intent(Intent.ACTION_MANAGE_PACKAGE_STORAGE);
298 lowMemIntent.putExtra("memory", mFreeMem);
299 lowMemIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Doug Zongker3161795b2009-10-07 15:14:03 -0700300 NotificationManager mNotificationMgr =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 (NotificationManager)mContext.getSystemService(
302 Context.NOTIFICATION_SERVICE);
303 CharSequence title = mContext.getText(
304 com.android.internal.R.string.low_internal_storage_view_title);
305 CharSequence details = mContext.getText(
306 com.android.internal.R.string.low_internal_storage_view_text);
307 PendingIntent intent = PendingIntent.getActivity(mContext, 0, lowMemIntent, 0);
308 Notification notification = new Notification();
309 notification.icon = com.android.internal.R.drawable.stat_notify_disk_full;
310 notification.tickerText = title;
311 notification.flags |= Notification.FLAG_NO_CLEAR;
312 notification.setLatestEventInfo(mContext, title, details, intent);
313 mNotificationMgr.notify(LOW_MEMORY_NOTIFICATION_ID, notification);
314 mContext.sendStickyBroadcast(mStorageLowIntent);
315 }
316
317 /**
318 * Cancels low storage notification and sends OK intent.
319 */
320 private final void cancelNotification() {
321 if(localLOGV) Log.i(TAG, "Canceling low memory notification");
322 NotificationManager mNotificationMgr =
323 (NotificationManager)mContext.getSystemService(
324 Context.NOTIFICATION_SERVICE);
325 //cancel notification since memory has been freed
326 mNotificationMgr.cancel(LOW_MEMORY_NOTIFICATION_ID);
327
328 mContext.removeStickyBroadcast(mStorageLowIntent);
329 mContext.sendBroadcast(mStorageOkIntent);
330 }
Doug Zongker3161795b2009-10-07 15:14:03 -0700331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 public void updateMemory() {
333 int callingUid = getCallingUid();
334 if(callingUid != Process.SYSTEM_UID) {
335 return;
336 }
337 // force an early check
338 postCheckMemoryMsg(true, 0);
339 }
340}