blob: 7266d7dd4f1dfdc39afa27fa2858d70db6cba223 [file] [log] [blame]
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001/*
2 * Copyright (C) 2007 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
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070019import com.android.internal.R;
20import com.android.internal.telephony.TelephonyProperties;
21
Robert Greenwalt9e696c22010-04-01 14:45:18 -070022import android.app.AlarmManager;
23import android.app.Notification;
24import android.app.NotificationManager;
25import android.app.PendingIntent;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070026import android.content.BroadcastReceiver;
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -070027import android.content.ContentResolver;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070028import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.PackageManager;
32import android.content.res.Resources;
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -070033import android.database.ContentObserver;
Robert Greenwaltfee46832010-05-06 12:25:13 -070034import android.net.INetworkManagementEventObserver;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070035import android.net.IThrottleManager;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070036import android.net.NetworkStats;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070037import android.net.ThrottleManager;
38import android.os.Binder;
Robert Greenwaltb8912f52010-04-09 17:27:26 -070039import android.os.Environment;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070040import android.os.Handler;
41import android.os.HandlerThread;
42import android.os.IBinder;
43import android.os.INetworkManagementService;
44import android.os.Looper;
45import android.os.Message;
46import android.os.RemoteException;
47import android.os.ServiceManager;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.provider.Settings;
Robert Greenwalte6e98822010-04-15 08:27:14 -070051import android.telephony.TelephonyManager;
Robert Greenwaltfee46832010-05-06 12:25:13 -070052import android.text.TextUtils;
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070053import android.util.NtpTrustedTime;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070054import android.util.Slog;
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070055import android.util.TrustedTime;
Robert Greenwalt5f996892010-04-08 16:19:24 -070056
Robert Greenwaltb8912f52010-04-09 17:27:26 -070057import java.io.BufferedWriter;
58import java.io.File;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070059import java.io.FileDescriptor;
Robert Greenwaltb8912f52010-04-09 17:27:26 -070060import java.io.FileInputStream;
61import java.io.FileWriter;
62import java.io.IOException;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070063import java.io.PrintWriter;
64import java.util.Calendar;
65import java.util.GregorianCalendar;
Robert Greenwalt7171ea82010-04-14 22:37:12 -070066import java.util.Properties;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070067import java.util.Random;
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070068import java.util.concurrent.atomic.AtomicInteger;
69import java.util.concurrent.atomic.AtomicLong;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070070
71// TODO - add comments - reference the ThrottleManager for public API
72public class ThrottleService extends IThrottleManager.Stub {
73
74 private static final String TESTING_ENABLED_PROPERTY = "persist.throttle.testing";
75
76 private static final String TAG = "ThrottleService";
Robert Greenwaltbf7de392010-04-21 17:09:38 -070077 private static final boolean DBG = true;
78 private static final boolean VDBG = false;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070079 private Handler mHandler;
80 private HandlerThread mThread;
81
82 private Context mContext;
83
Robert Greenwaltfb9896b2010-04-22 15:39:38 -070084 private static final int INITIAL_POLL_DELAY_SEC = 90;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070085 private static final int TESTING_POLLING_PERIOD_SEC = 60 * 1;
Robert Greenwalt7171ea82010-04-14 22:37:12 -070086 private static final int TESTING_RESET_PERIOD_SEC = 60 * 10;
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -070087 private static final long TESTING_THRESHOLD = 1 * 1024 * 1024;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070088
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070089 private static final long MAX_NTP_CACHE_AGE = 24 * 60 * 60 * 1000;
90 private static final long MAX_NTP_FETCH_WAIT = 20 * 1000;
91
92 private long mMaxNtpCacheAge = MAX_NTP_CACHE_AGE;
93
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -070094 private int mPolicyPollPeriodSec;
Robert Greenwalt39e163f2010-05-07 16:52:17 -070095 private AtomicLong mPolicyThreshold;
96 private AtomicInteger mPolicyThrottleValue;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070097 private int mPolicyResetDay; // 1-28
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -070098 private int mPolicyNotificationsAllowedMask;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070099
100 private long mLastRead; // read byte count from last poll
101 private long mLastWrite; // write byte count from last poll
102
103 private static final String ACTION_POLL = "com.android.server.ThrottleManager.action.POLL";
104 private static int POLL_REQUEST = 0;
105 private PendingIntent mPendingPollIntent;
106 private static final String ACTION_RESET = "com.android.server.ThorottleManager.action.RESET";
107 private static int RESET_REQUEST = 1;
108 private PendingIntent mPendingResetIntent;
109
110 private INetworkManagementService mNMService;
111 private AlarmManager mAlarmManager;
112 private NotificationManager mNotificationManager;
113
114 private DataRecorder mRecorder;
115
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700116 private String mIface;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700117
118 private static final int NOTIFICATION_WARNING = 2;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700119
120 private Notification mThrottlingNotification;
121 private boolean mWarningNotificationSent = false;
122
Robert Greenwaltfee46832010-05-06 12:25:13 -0700123 private InterfaceObserver mInterfaceObserver;
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700124 private SettingsObserver mSettingsObserver;
125
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700126 private AtomicInteger mThrottleIndex; // 0 for none, 1 for first throttle val, 2 for next, etc
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700127 private static final int THROTTLE_INDEX_UNINITIALIZED = -1;
128 private static final int THROTTLE_INDEX_UNTHROTTLED = 0;
129
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700130 private static final String PROPERTIES_FILE = "/etc/gps.conf";
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700131
132 private Intent mPollStickyBroadcast;
133
134 private TrustedTime mTime;
135
136 private static INetworkManagementService getNetworkManagementService() {
137 final IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
138 return INetworkManagementService.Stub.asInterface(b);
139 }
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700140
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700141 public ThrottleService(Context context) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700142 // TODO: move to using cached NtpTrustedTime
143 this(context, getNetworkManagementService(), new NtpTrustedTime(),
144 context.getResources().getString(R.string.config_datause_iface));
145 }
146
147 public ThrottleService(Context context, INetworkManagementService nmService, TrustedTime time,
148 String iface) {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700149 if (VDBG) Slog.v(TAG, "Starting ThrottleService");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700150 mContext = context;
151
Robert Greenwalt24488bd2010-05-10 16:56:43 -0700152 mPolicyThreshold = new AtomicLong();
153 mPolicyThrottleValue = new AtomicInteger();
154 mThrottleIndex = new AtomicInteger();
155
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700156 mIface = iface;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700157 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
158 Intent pollIntent = new Intent(ACTION_POLL, null);
159 mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
160 Intent resetIntent = new Intent(ACTION_RESET, null);
161 mPendingResetIntent = PendingIntent.getBroadcast(mContext, RESET_REQUEST, resetIntent, 0);
162
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700163 mNMService = nmService;
164 mTime = time;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700165
166 mNotificationManager = (NotificationManager)mContext.getSystemService(
167 Context.NOTIFICATION_SERVICE);
168 }
169
Robert Greenwaltfee46832010-05-06 12:25:13 -0700170 private static class InterfaceObserver extends INetworkManagementEventObserver.Stub {
171 private int mMsg;
172 private Handler mHandler;
173 private String mIface;
174
175 InterfaceObserver(Handler handler, int msg, String iface) {
176 super();
177 mHandler = handler;
178 mMsg = msg;
179 mIface = iface;
180 }
181
Wink Saville1a7e6712011-01-09 12:16:38 -0800182 public void interfaceLinkStatusChanged(String iface, boolean link) {
Robert Greenwaltfee46832010-05-06 12:25:13 -0700183 if (link) {
184 if (TextUtils.equals(iface, mIface)) {
185 mHandler.obtainMessage(mMsg).sendToTarget();
186 }
187 }
188 }
189
190 public void interfaceAdded(String iface) {
191 // TODO - an interface added in the UP state should also trigger a StatusChanged
192 // notification..
193 if (TextUtils.equals(iface, mIface)) {
194 mHandler.obtainMessage(mMsg).sendToTarget();
195 }
196 }
197
198 public void interfaceRemoved(String iface) {}
199 }
200
201
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700202 private static class SettingsObserver extends ContentObserver {
203 private int mMsg;
204 private Handler mHandler;
205 SettingsObserver(Handler handler, int msg) {
206 super(handler);
207 mHandler = handler;
208 mMsg = msg;
209 }
210
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700211 void register(Context context) {
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700212 ContentResolver resolver = context.getContentResolver();
213 resolver.registerContentObserver(Settings.Secure.getUriFor(
214 Settings.Secure.THROTTLE_POLLING_SEC), false, this);
215 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700216 Settings.Secure.THROTTLE_THRESHOLD_BYTES), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700217 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700218 Settings.Secure.THROTTLE_VALUE_KBITSPS), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700219 resolver.registerContentObserver(Settings.Secure.getUriFor(
220 Settings.Secure.THROTTLE_RESET_DAY), false, this);
221 resolver.registerContentObserver(Settings.Secure.getUriFor(
222 Settings.Secure.THROTTLE_NOTIFICATION_TYPE), false, this);
223 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700224 Settings.Secure.THROTTLE_HELP_URI), false, this);
Robert Greenwaltd1055a22010-05-25 15:54:52 -0700225 resolver.registerContentObserver(Settings.Secure.getUriFor(
226 Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700227 }
228
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700229 void unregister(Context context) {
230 final ContentResolver resolver = context.getContentResolver();
231 resolver.unregisterContentObserver(this);
232 }
233
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700234 @Override
235 public void onChange(boolean selfChange) {
236 mHandler.obtainMessage(mMsg).sendToTarget();
237 }
238 }
239
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700240 private void enforceAccessPermission() {
241 mContext.enforceCallingOrSelfPermission(
242 android.Manifest.permission.ACCESS_NETWORK_STATE,
243 "ThrottleService");
244 }
245
Robert Greenwalt05d06732010-04-19 11:10:38 -0700246 private long ntpToWallTime(long ntpTime) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700247 // get time quickly without worrying about trusted state
248 long bestNow = mTime.hasCache() ? mTime.currentTimeMillis()
249 : System.currentTimeMillis();
Robert Greenwalt05d06732010-04-19 11:10:38 -0700250 long localNow = System.currentTimeMillis();
251 return localNow + (ntpTime - bestNow);
252 }
253
Irfan Sheriffcf282362010-04-16 16:53:20 -0700254 // TODO - fetch for the iface
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700255 // return time in the local, system wall time, correcting for the use of ntp
Robert Greenwalt05d06732010-04-19 11:10:38 -0700256
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700257 public long getResetTime(String iface) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700258 enforceAccessPermission();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700259 long resetTime = 0;
Irfan Sheriffcf282362010-04-16 16:53:20 -0700260 if (mRecorder != null) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700261 resetTime = mRecorder.getPeriodEnd();
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700262 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700263 resetTime = ntpToWallTime(resetTime);
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700264 return resetTime;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700265 }
Irfan Sheriffcf282362010-04-16 16:53:20 -0700266
267 // TODO - fetch for the iface
Robert Greenwalt05d06732010-04-19 11:10:38 -0700268 // return time in the local, system wall time, correcting for the use of ntp
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700269 public long getPeriodStartTime(String iface) {
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700270 long startTime = 0;
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700271 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700272 if (mRecorder != null) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700273 startTime = mRecorder.getPeriodStart();
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700274 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700275 startTime = ntpToWallTime(startTime);
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700276 return startTime;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700277 }
278 //TODO - a better name? getCliffByteCountThreshold?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700279 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700280 public long getCliffThreshold(String iface, int cliff) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700281 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700282 if (cliff == 1) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700283 return mPolicyThreshold.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700284 }
285 return 0;
286 }
287 // TODO - a better name? getThrottleRate?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700288 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700289 public int getCliffLevel(String iface, int cliff) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700290 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700291 if (cliff == 1) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700292 return mPolicyThrottleValue.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700293 }
294 return 0;
295 }
296
Irfan Sheriffc9b68512010-04-08 14:12:33 -0700297 public String getHelpUri() {
298 enforceAccessPermission();
299 return Settings.Secure.getString(mContext.getContentResolver(),
300 Settings.Secure.THROTTLE_HELP_URI);
301 }
302
Irfan Sheriffcf282362010-04-16 16:53:20 -0700303 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700304 public long getByteCount(String iface, int dir, int period, int ago) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700305 enforceAccessPermission();
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700306 if ((period == ThrottleManager.PERIOD_CYCLE) && (mRecorder != null)) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700307 if (dir == ThrottleManager.DIRECTION_TX) return mRecorder.getPeriodTx(ago);
308 if (dir == ThrottleManager.DIRECTION_RX) return mRecorder.getPeriodRx(ago);
309 }
310 return 0;
311 }
312
313 // TODO - a better name - getCurrentThrottleRate?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700314 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700315 public int getThrottle(String iface) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700316 enforceAccessPermission();
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700317 if (mThrottleIndex.get() == 1) {
318 return mPolicyThrottleValue.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700319 }
320 return 0;
321 }
322
323 void systemReady() {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700324 if (VDBG) Slog.v(TAG, "systemReady");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700325 mContext.registerReceiver(
326 new BroadcastReceiver() {
327 @Override
328 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700329 dispatchPoll();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700330 }
331 }, new IntentFilter(ACTION_POLL));
332
333 mContext.registerReceiver(
334 new BroadcastReceiver() {
335 @Override
336 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700337 dispatchReset();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700338 }
339 }, new IntentFilter(ACTION_RESET));
340
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700341 FileInputStream stream = null;
342 try {
343 Properties properties = new Properties();
344 File file = new File(PROPERTIES_FILE);
345 stream = new FileInputStream(file);
346 properties.load(stream);
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700347 final String ntpServer = properties.getProperty("NTP_SERVER", null);
348 if (mTime instanceof NtpTrustedTime) {
349 ((NtpTrustedTime) mTime).setNtpServer(ntpServer, MAX_NTP_FETCH_WAIT);
350 }
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700351 } catch (IOException e) {
352 Slog.e(TAG, "Could not open GPS configuration file " + PROPERTIES_FILE);
353 } finally {
354 if (stream != null) {
355 try {
356 stream.close();
357 } catch (Exception e) {}
358 }
359 }
Robert Greenwaltc76c15e2010-06-16 14:42:16 -0700360
361 // use a new thread as we don't want to stall the system for file writes
362 mThread = new HandlerThread(TAG);
363 mThread.start();
364 mHandler = new MyHandler(mThread.getLooper());
365 mHandler.obtainMessage(EVENT_REBOOT_RECOVERY).sendToTarget();
366
367 mInterfaceObserver = new InterfaceObserver(mHandler, EVENT_IFACE_UP, mIface);
368 try {
369 mNMService.registerObserver(mInterfaceObserver);
370 } catch (RemoteException e) {
371 Slog.e(TAG, "Could not register InterfaceObserver " + e);
372 }
373
374 mSettingsObserver = new SettingsObserver(mHandler, EVENT_POLICY_CHANGED);
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700375 mSettingsObserver.register(mContext);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700376 }
377
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700378 void shutdown() {
379 // TODO: eventually connect with ShutdownThread to persist stats during
380 // graceful shutdown.
381
382 if (mThread != null) {
383 mThread.quit();
384 }
385
386 if (mSettingsObserver != null) {
387 mSettingsObserver.unregister(mContext);
388 }
389
390 if (mPollStickyBroadcast != null) {
391 mContext.removeStickyBroadcast(mPollStickyBroadcast);
392 }
393 }
394
395 void dispatchPoll() {
396 mHandler.obtainMessage(EVENT_POLL_ALARM).sendToTarget();
397 }
398
399 void dispatchReset() {
400 mHandler.obtainMessage(EVENT_RESET_ALARM).sendToTarget();
401 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700402
403 private static final int EVENT_REBOOT_RECOVERY = 0;
404 private static final int EVENT_POLICY_CHANGED = 1;
405 private static final int EVENT_POLL_ALARM = 2;
406 private static final int EVENT_RESET_ALARM = 3;
Robert Greenwaltfee46832010-05-06 12:25:13 -0700407 private static final int EVENT_IFACE_UP = 4;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700408 private class MyHandler extends Handler {
409 public MyHandler(Looper l) {
410 super(l);
411 }
412
413 @Override
414 public void handleMessage(Message msg) {
415 switch (msg.what) {
416 case EVENT_REBOOT_RECOVERY:
417 onRebootRecovery();
418 break;
419 case EVENT_POLICY_CHANGED:
420 onPolicyChanged();
421 break;
422 case EVENT_POLL_ALARM:
423 onPollAlarm();
424 break;
425 case EVENT_RESET_ALARM:
426 onResetAlarm();
Robert Greenwaltfee46832010-05-06 12:25:13 -0700427 break;
428 case EVENT_IFACE_UP:
429 onIfaceUp();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700430 }
431 }
432
433 private void onRebootRecovery() {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700434 if (VDBG) Slog.v(TAG, "onRebootRecovery");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700435 // check for sim change TODO
436 // reregister for notification of policy change
437
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700438 mThrottleIndex.set(THROTTLE_INDEX_UNINITIALIZED);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700439
440 mRecorder = new DataRecorder(mContext, ThrottleService.this);
441
442 // get policy
443 mHandler.obtainMessage(EVENT_POLICY_CHANGED).sendToTarget();
Robert Greenwaltfb9896b2010-04-22 15:39:38 -0700444
445 // if we poll now we won't have network connectivity or even imsi access
446 // queue up a poll to happen in a little while - after ntp and imsi are avail
447 // TODO - make this callback based (ie, listen for notificaitons)
448 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_POLL_ALARM),
449 INITIAL_POLL_DELAY_SEC * 1000);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700450 }
451
452 // check for new policy info (threshold limit/value/etc)
453 private void onPolicyChanged() {
454 boolean testing = SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true");
455
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700456 int pollingPeriod = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700457 R.integer.config_datause_polling_period_sec);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700458 mPolicyPollPeriodSec = Settings.Secure.getInt(mContext.getContentResolver(),
459 Settings.Secure.THROTTLE_POLLING_SEC, pollingPeriod);
460
461 // TODO - remove testing stuff?
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700462 long defaultThreshold = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700463 R.integer.config_datause_threshold_bytes);
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700464 int defaultValue = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700465 R.integer.config_datause_throttle_kbitsps);
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700466 long threshold = Settings.Secure.getLong(mContext.getContentResolver(),
467 Settings.Secure.THROTTLE_THRESHOLD_BYTES, defaultThreshold);
468 int value = Settings.Secure.getInt(mContext.getContentResolver(),
469 Settings.Secure.THROTTLE_VALUE_KBITSPS, defaultValue);
470
471 mPolicyThreshold.set(threshold);
472 mPolicyThrottleValue.set(value);
473 if (testing) {
474 mPolicyPollPeriodSec = TESTING_POLLING_PERIOD_SEC;
475 mPolicyThreshold.set(TESTING_THRESHOLD);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700476 }
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700477
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700478 mPolicyResetDay = Settings.Secure.getInt(mContext.getContentResolver(),
479 Settings.Secure.THROTTLE_RESET_DAY, -1);
480 if (mPolicyResetDay == -1 ||
481 ((mPolicyResetDay < 1) || (mPolicyResetDay > 28))) {
482 Random g = new Random();
483 mPolicyResetDay = 1 + g.nextInt(28); // 1-28
484 Settings.Secure.putInt(mContext.getContentResolver(),
485 Settings.Secure.THROTTLE_RESET_DAY, mPolicyResetDay);
486 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700487 if (mIface == null) {
488 mPolicyThreshold.set(0);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700489 }
490
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700491 int defaultNotificationType = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700492 R.integer.config_datause_notification_type);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700493 mPolicyNotificationsAllowedMask = Settings.Secure.getInt(mContext.getContentResolver(),
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700494 Settings.Secure.THROTTLE_NOTIFICATION_TYPE, defaultNotificationType);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700495
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700496 final int maxNtpCacheAgeSec = Settings.Secure.getInt(mContext.getContentResolver(),
497 Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC,
498 (int) (MAX_NTP_CACHE_AGE / 1000));
499 mMaxNtpCacheAge = maxNtpCacheAgeSec * 1000;
Robert Greenwaltd1055a22010-05-25 15:54:52 -0700500
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700501 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700502 Slog.d(TAG, "onPolicyChanged testing=" + testing +", period=" +
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700503 mPolicyPollPeriodSec + ", threshold=" + mPolicyThreshold.get() +
504 ", value=" + mPolicyThrottleValue.get() + ", resetDay=" + mPolicyResetDay +
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700505 ", noteType=" + mPolicyNotificationsAllowedMask + ", mMaxNtpCacheAge=" +
506 mMaxNtpCacheAge);
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700507 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700508
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700509 // force updates
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700510 mThrottleIndex.set(THROTTLE_INDEX_UNINITIALIZED);
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700511
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700512 onResetAlarm();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700513
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700514 onPollAlarm();
515
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700516 Intent broadcast = new Intent(ThrottleManager.POLICY_CHANGED_ACTION);
517 mContext.sendBroadcast(broadcast);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700518 }
519
520 private void onPollAlarm() {
521 long now = SystemClock.elapsedRealtime();
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700522 long next = now + mPolicyPollPeriodSec * 1000;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700523
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700524 // when trusted cache outdated, try refreshing
525 if (mTime.getCacheAge() > mMaxNtpCacheAge) {
526 if (mTime.forceRefresh()) {
527 if (VDBG) Slog.d(TAG, "updated trusted time, reseting alarm");
528 dispatchReset();
529 }
530 }
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700531
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700532 long incRead = 0;
533 long incWrite = 0;
534 try {
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700535 final NetworkStats stats = mNMService.getNetworkStatsSummary();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700536 final int index = stats.findIndex(
537 mIface, NetworkStats.UID_ALL, NetworkStats.TAG_NONE);
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700538
539 if (index != -1) {
540 incRead = stats.rx[index] - mLastRead;
541 incWrite = stats.tx[index] - mLastWrite;
542 } else {
543 // missing iface, assume stats are 0
544 Slog.w(TAG, "unable to find stats for iface " + mIface);
545 }
546
Robert Greenwalt8c7e6092010-04-14 17:31:20 -0700547 // handle iface resets - on some device the 3g iface comes and goes and gets
548 // totals reset to 0. Deal with it
549 if ((incRead < 0) || (incWrite < 0)) {
550 incRead += mLastRead;
551 incWrite += mLastWrite;
552 mLastRead = 0;
553 mLastWrite = 0;
554 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700555 } catch (RemoteException e) {
556 Slog.e(TAG, "got remoteException in onPollAlarm:" + e);
557 }
Robert Greenwalt5f996892010-04-08 16:19:24 -0700558 // don't count this data if we're roaming.
559 boolean roaming = "true".equals(
560 SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING));
561 if (!roaming) {
562 mRecorder.addData(incRead, incWrite);
563 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700564
565 long periodRx = mRecorder.getPeriodRx(0);
566 long periodTx = mRecorder.getPeriodTx(0);
567 long total = periodRx + periodTx;
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700568 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700569 Slog.d(TAG, "onPollAlarm - roaming =" + roaming +
Robert Greenwalt5f996892010-04-08 16:19:24 -0700570 ", read =" + incRead + ", written =" + incWrite + ", new total =" + total);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700571 }
572 mLastRead += incRead;
573 mLastWrite += incWrite;
574
575 checkThrottleAndPostNotification(total);
576
577 Intent broadcast = new Intent(ThrottleManager.THROTTLE_POLL_ACTION);
578 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_READ, periodRx);
579 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_WRITE, periodTx);
Robert Greenwalt05d06732010-04-19 11:10:38 -0700580 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_START, getPeriodStartTime(mIface));
581 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_END, getResetTime(mIface));
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700582 mContext.sendStickyBroadcast(broadcast);
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700583 mPollStickyBroadcast = broadcast;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700584
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700585 mAlarmManager.cancel(mPendingPollIntent);
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700586 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700587 }
588
Robert Greenwaltfee46832010-05-06 12:25:13 -0700589 private void onIfaceUp() {
590 // if we were throttled before, be sure and set it again - the iface went down
591 // (and may have disappeared all together) and these settings were lost
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700592 if (mThrottleIndex.get() == 1) {
Robert Greenwaltfee46832010-05-06 12:25:13 -0700593 try {
594 mNMService.setInterfaceThrottle(mIface, -1, -1);
595 mNMService.setInterfaceThrottle(mIface,
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700596 mPolicyThrottleValue.get(), mPolicyThrottleValue.get());
Robert Greenwaltfee46832010-05-06 12:25:13 -0700597 } catch (Exception e) {
598 Slog.e(TAG, "error setting Throttle: " + e);
599 }
600 }
601 }
602
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700603 private void checkThrottleAndPostNotification(long currentTotal) {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700604 // is throttling enabled?
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700605 long threshold = mPolicyThreshold.get();
606 if (threshold == 0) {
Robert Greenwaltcce83372010-04-23 17:35:29 -0700607 clearThrottleAndNotification();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700608 return;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700609 }
610
611 // have we spoken with an ntp server yet?
612 // this is controversial, but we'd rather err towards not throttling
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700613 if (!mTime.hasCache()) {
614 Slog.w(TAG, "missing trusted time, skipping throttle check");
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700615 return;
616 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700617
618 // check if we need to throttle
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700619 if (currentTotal > threshold) {
620 if (mThrottleIndex.get() != 1) {
621 mThrottleIndex.set(1);
622 if (DBG) Slog.d(TAG, "Threshold " + threshold + " exceeded!");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700623 try {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700624 mNMService.setInterfaceThrottle(mIface,
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700625 mPolicyThrottleValue.get(), mPolicyThrottleValue.get());
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700626 } catch (Exception e) {
627 Slog.e(TAG, "error setting Throttle: " + e);
628 }
629
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700630 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700631
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700632 postNotification(R.string.throttled_notification_title,
633 R.string.throttled_notification_message,
634 R.drawable.stat_sys_throttled,
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700635 Notification.FLAG_ONGOING_EVENT);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700636
637 Intent broadcast = new Intent(ThrottleManager.THROTTLE_ACTION);
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700638 broadcast.putExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL,
639 mPolicyThrottleValue.get());
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700640 mContext.sendStickyBroadcast(broadcast);
641
642 } // else already up!
643 } else {
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700644 clearThrottleAndNotification();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700645 if ((mPolicyNotificationsAllowedMask & NOTIFICATION_WARNING) != 0) {
646 // check if we should warn about throttle
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700647 // pretend we only have 1/2 the time remaining that we actually do
648 // if our burn rate in the period so far would have us exceed the limit
649 // in that 1/2 window, warn the user.
650 // this gets more generous in the early to middle period and converges back
651 // to the limit as we move toward the period end.
652
653 // adding another factor - it must be greater than the total cap/4
654 // else we may get false alarms very early in the period.. in the first
655 // tenth of a percent of the period if we used more than a tenth of a percent
656 // of the cap we'd get a warning and that's not desired.
657 long start = mRecorder.getPeriodStart();
658 long end = mRecorder.getPeriodEnd();
659 long periodLength = end - start;
660 long now = System.currentTimeMillis();
661 long timeUsed = now - start;
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700662 long warningThreshold = 2*threshold*timeUsed/(timeUsed+periodLength);
663 if ((currentTotal > warningThreshold) && (currentTotal > threshold/4)) {
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700664 if (mWarningNotificationSent == false) {
665 mWarningNotificationSent = true;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700666 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
667 postNotification(R.string.throttle_warning_notification_title,
668 R.string.throttle_warning_notification_message,
669 R.drawable.stat_sys_throttled,
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700670 0);
671 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700672 } else {
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700673 if (mWarningNotificationSent == true) {
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700674 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700675 mWarningNotificationSent =false;
676 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700677 }
678 }
679 }
680 }
681
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700682 private void postNotification(int titleInt, int messageInt, int icon, int flags) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700683 Intent intent = new Intent();
684 // TODO - fix up intent
Robert Greenwalt2a7b7302010-04-12 14:56:31 -0700685 intent.setClassName("com.android.phone", "com.android.phone.DataUsage");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700686 intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
687
688 PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
689
690 Resources r = Resources.getSystem();
691 CharSequence title = r.getText(titleInt);
692 CharSequence message = r.getText(messageInt);
693 if (mThrottlingNotification == null) {
694 mThrottlingNotification = new Notification();
695 mThrottlingNotification.when = 0;
696 // TODO - fixup icon
697 mThrottlingNotification.icon = icon;
698 mThrottlingNotification.defaults &= ~Notification.DEFAULT_SOUND;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700699 }
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700700 mThrottlingNotification.flags = flags;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700701 mThrottlingNotification.tickerText = title;
702 mThrottlingNotification.setLatestEventInfo(mContext, title, message, pi);
703
704 mNotificationManager.notify(mThrottlingNotification.icon, mThrottlingNotification);
705 }
706
707
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700708 private void clearThrottleAndNotification() {
709 if (mThrottleIndex.get() != THROTTLE_INDEX_UNTHROTTLED) {
710 mThrottleIndex.set(THROTTLE_INDEX_UNTHROTTLED);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700711 try {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700712 mNMService.setInterfaceThrottle(mIface, -1, -1);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700713 } catch (Exception e) {
714 Slog.e(TAG, "error clearing Throttle: " + e);
715 }
716 Intent broadcast = new Intent(ThrottleManager.THROTTLE_ACTION);
717 broadcast.putExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL, -1);
718 mContext.sendStickyBroadcast(broadcast);
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700719 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
720 mWarningNotificationSent = false;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700721 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700722 }
723
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700724 private Calendar calculatePeriodEnd(long now) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700725 Calendar end = GregorianCalendar.getInstance();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700726 end.setTimeInMillis(now);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700727 int day = end.get(Calendar.DAY_OF_MONTH);
728 end.set(Calendar.DAY_OF_MONTH, mPolicyResetDay);
729 end.set(Calendar.HOUR_OF_DAY, 0);
730 end.set(Calendar.MINUTE, 0);
Robert Greenwalt8c7e6092010-04-14 17:31:20 -0700731 end.set(Calendar.SECOND, 0);
732 end.set(Calendar.MILLISECOND, 0);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700733 if (day >= mPolicyResetDay) {
734 int month = end.get(Calendar.MONTH);
735 if (month == Calendar.DECEMBER) {
736 end.set(Calendar.YEAR, end.get(Calendar.YEAR) + 1);
737 month = Calendar.JANUARY - 1;
738 }
739 end.set(Calendar.MONTH, month + 1);
740 }
741
742 // TODO - remove!
743 if (SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true")) {
744 end = GregorianCalendar.getInstance();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700745 end.setTimeInMillis(now);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700746 end.add(Calendar.SECOND, TESTING_RESET_PERIOD_SEC);
747 }
748 return end;
749 }
750 private Calendar calculatePeriodStart(Calendar end) {
751 Calendar start = (Calendar)end.clone();
752 int month = end.get(Calendar.MONTH);
753 if (end.get(Calendar.MONTH) == Calendar.JANUARY) {
754 month = Calendar.DECEMBER + 1;
755 start.set(Calendar.YEAR, start.get(Calendar.YEAR) - 1);
756 }
757 start.set(Calendar.MONTH, month - 1);
758
759 // TODO - remove!!
760 if (SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true")) {
761 start = (Calendar)end.clone();
762 start.add(Calendar.SECOND, -TESTING_RESET_PERIOD_SEC);
763 }
764 return start;
765 }
766
767 private void onResetAlarm() {
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700768 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700769 Slog.d(TAG, "onResetAlarm - last period had " + mRecorder.getPeriodRx(0) +
770 " bytes read and " + mRecorder.getPeriodTx(0) + " written");
771 }
772
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700773 // when trusted cache outdated, try refreshing
774 if (mTime.getCacheAge() > mMaxNtpCacheAge) {
775 mTime.forceRefresh();
776 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700777
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700778 // as long as we have a trusted time cache, we always reset alarms,
779 // even if the refresh above failed.
780 if (mTime.hasCache()) {
781 final long now = mTime.currentTimeMillis();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700782 Calendar end = calculatePeriodEnd(now);
783 Calendar start = calculatePeriodStart(end);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700784
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700785 if (mRecorder.setNextPeriod(start, end)) {
Robert Greenwalt05d06732010-04-19 11:10:38 -0700786 onPollAlarm();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700787 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700788
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700789 mAlarmManager.cancel(mPendingResetIntent);
790 long offset = end.getTimeInMillis() - now;
791 // use Elapsed realtime so clock changes don't fool us.
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700792 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME,
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700793 SystemClock.elapsedRealtime() + offset,
794 mPendingResetIntent);
795 } else {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700796 if (VDBG) Slog.d(TAG, "no trusted time, not resetting period");
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700797 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700798 }
799 }
800
801 // records bytecount data for a given time and accumulates it into larger time windows
802 // for logging and other purposes
803 //
804 // since time can be changed (user or network action) we will have to track the time of the
805 // last recording and deal with it.
806 private static class DataRecorder {
807 long[] mPeriodRxData;
808 long[] mPeriodTxData;
809 int mCurrentPeriod;
810 int mPeriodCount;
811
812 Calendar mPeriodStart;
813 Calendar mPeriodEnd;
814
815 ThrottleService mParent;
816 Context mContext;
Robert Greenwalte6e98822010-04-15 08:27:14 -0700817 String mImsi = null;
818
819 TelephonyManager mTelephonyManager;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700820
821 DataRecorder(Context context, ThrottleService parent) {
822 mContext = context;
823 mParent = parent;
824
Robert Greenwalte6e98822010-04-15 08:27:14 -0700825 mTelephonyManager = (TelephonyManager)mContext.getSystemService(
826 Context.TELEPHONY_SERVICE);
827
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700828 synchronized (mParent) {
829 mPeriodCount = 6;
830 mPeriodRxData = new long[mPeriodCount];
831 mPeriodTxData = new long[mPeriodCount];
832
833 mPeriodStart = Calendar.getInstance();
834 mPeriodEnd = Calendar.getInstance();
835
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700836 retrieve();
837 }
838 }
839
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700840 boolean setNextPeriod(Calendar start, Calendar end) {
Robert Greenwalte6e98822010-04-15 08:27:14 -0700841 // TODO - how would we deal with a dual-IMSI device?
842 checkForSubscriberId();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700843 boolean startNewPeriod = true;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700844
Robert Greenwalt27fba672010-04-26 12:29:14 -0700845 if (start.equals(mPeriodStart) && end.equals(mPeriodEnd)) {
846 // same endpoints - keep collecting
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700847 if (VDBG) {
Robert Greenwalt27fba672010-04-26 12:29:14 -0700848 Slog.d(TAG, "same period (" + start.getTimeInMillis() + "," +
849 end.getTimeInMillis() +") - ammending data");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700850 }
Robert Greenwalt27fba672010-04-26 12:29:14 -0700851 startNewPeriod = false;
852 } else {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700853 if (VDBG) {
Robert Greenwalt27fba672010-04-26 12:29:14 -0700854 if(start.equals(mPeriodEnd) || start.after(mPeriodEnd)) {
855 Slog.d(TAG, "next period (" + start.getTimeInMillis() + "," +
856 end.getTimeInMillis() + ") - old end was " +
857 mPeriodEnd.getTimeInMillis() + ", following");
858 } else {
859 Slog.d(TAG, "new period (" + start.getTimeInMillis() + "," +
860 end.getTimeInMillis() + ") replacing old (" +
861 mPeriodStart.getTimeInMillis() + "," +
862 mPeriodEnd.getTimeInMillis() + ")");
863 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700864 }
865 synchronized (mParent) {
866 ++mCurrentPeriod;
867 if (mCurrentPeriod >= mPeriodCount) mCurrentPeriod = 0;
868 mPeriodRxData[mCurrentPeriod] = 0;
869 mPeriodTxData[mCurrentPeriod] = 0;
870 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700871 }
872 setPeriodStart(start);
873 setPeriodEnd(end);
874 record();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700875 return startNewPeriod;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700876 }
877
878 public long getPeriodEnd() {
879 synchronized (mParent) {
880 return mPeriodEnd.getTimeInMillis();
881 }
882 }
883
884 private void setPeriodEnd(Calendar end) {
885 synchronized (mParent) {
886 mPeriodEnd = end;
887 }
888 }
889
890 public long getPeriodStart() {
891 synchronized (mParent) {
892 return mPeriodStart.getTimeInMillis();
893 }
894 }
895
896 private void setPeriodStart(Calendar start) {
897 synchronized (mParent) {
898 mPeriodStart = start;
899 }
900 }
901
902 public int getPeriodCount() {
903 synchronized (mParent) {
904 return mPeriodCount;
905 }
906 }
907
908 private void zeroData(int field) {
909 synchronized (mParent) {
910 for(int period = 0; period<mPeriodCount; period++) {
911 mPeriodRxData[period] = 0;
912 mPeriodTxData[period] = 0;
913 }
914 mCurrentPeriod = 0;
915 }
916
917 }
918
919 // if time moves backward accumulate all read/write that's lost into the now
920 // otherwise time moved forward.
921 void addData(long bytesRead, long bytesWritten) {
Robert Greenwalte6e98822010-04-15 08:27:14 -0700922 checkForSubscriberId();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700923
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700924 synchronized (mParent) {
925 mPeriodRxData[mCurrentPeriod] += bytesRead;
926 mPeriodTxData[mCurrentPeriod] += bytesWritten;
927 }
928 record();
929 }
930
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700931 private File getDataFile() {
932 File dataDir = Environment.getDataDirectory();
933 File throttleDir = new File(dataDir, "system/throttle");
934 throttleDir.mkdirs();
Robert Greenwalte6e98822010-04-15 08:27:14 -0700935 String mImsi = mTelephonyManager.getSubscriberId();
936 File dataFile;
937 if (mImsi == null) {
938 dataFile = useMRUFile(throttleDir);
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700939 if (VDBG) Slog.v(TAG, "imsi not available yet, using " + dataFile);
Robert Greenwalte6e98822010-04-15 08:27:14 -0700940 } else {
941 String imsiHash = Integer.toString(mImsi.hashCode());
942 dataFile = new File(throttleDir, imsiHash);
943 }
944 // touch the file so it's not LRU
945 dataFile.setLastModified(System.currentTimeMillis());
946 checkAndDeleteLRUDataFile(throttleDir);
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700947 return dataFile;
948 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700949
Robert Greenwalte6e98822010-04-15 08:27:14 -0700950 // TODO - get broadcast (TelephonyIntents.ACTION_SIM_STATE_CHANGED) instead of polling
951 private void checkForSubscriberId() {
952 if (mImsi != null) return;
953
954 mImsi = mTelephonyManager.getSubscriberId();
955 if (mImsi == null) return;
956
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700957 if (VDBG) Slog.d(TAG, "finally have imsi - retreiving data");
Robert Greenwalte6e98822010-04-15 08:27:14 -0700958 retrieve();
959 }
960
961 private final static int MAX_SIMS_SUPPORTED = 3;
962
963 private void checkAndDeleteLRUDataFile(File dir) {
964 File[] files = dir.listFiles();
965
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700966 if (files == null || files.length <= MAX_SIMS_SUPPORTED) return;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700967 if (DBG) Slog.d(TAG, "Too many data files");
Robert Greenwalte6e98822010-04-15 08:27:14 -0700968 do {
969 File oldest = null;
970 for (File f : files) {
971 if ((oldest == null) || (oldest.lastModified() > f.lastModified())) {
972 oldest = f;
973 }
974 }
975 if (oldest == null) return;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700976 if (DBG) Slog.d(TAG, " deleting " + oldest);
Robert Greenwalte6e98822010-04-15 08:27:14 -0700977 oldest.delete();
978 files = dir.listFiles();
979 } while (files.length > MAX_SIMS_SUPPORTED);
980 }
981
982 private File useMRUFile(File dir) {
983 File newest = null;
984 File[] files = dir.listFiles();
985
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700986 if (files != null) {
987 for (File f : files) {
988 if ((newest == null) || (newest.lastModified() < f.lastModified())) {
989 newest = f;
990 }
Robert Greenwalte6e98822010-04-15 08:27:14 -0700991 }
992 }
993 if (newest == null) {
994 newest = new File(dir, "temp");
995 }
996 return newest;
997 }
998
999
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001000 private static final int DATA_FILE_VERSION = 1;
1001
1002 private void record() {
1003 // 1 int version
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001004 // 1 int mPeriodCount
1005 // 13*6 long[PERIOD_COUNT] mPeriodRxData
1006 // 13*6 long[PERIOD_COUNT] mPeriodTxData
1007 // 1 int mCurrentPeriod
1008 // 13 long periodStartMS
1009 // 13 long periodEndMS
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001010 // 200 chars max
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001011 StringBuilder builder = new StringBuilder();
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001012 builder.append(DATA_FILE_VERSION);
1013 builder.append(":");
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001014 builder.append(mPeriodCount);
1015 builder.append(":");
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001016 for(int i = 0; i < mPeriodCount; i++) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001017 builder.append(mPeriodRxData[i]);
1018 builder.append(":");
1019 }
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001020 for(int i = 0; i < mPeriodCount; i++) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001021 builder.append(mPeriodTxData[i]);
1022 builder.append(":");
1023 }
1024 builder.append(mCurrentPeriod);
1025 builder.append(":");
1026 builder.append(mPeriodStart.getTimeInMillis());
1027 builder.append(":");
1028 builder.append(mPeriodEnd.getTimeInMillis());
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001029
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001030 BufferedWriter out = null;
1031 try {
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001032 out = new BufferedWriter(new FileWriter(getDataFile()), 256);
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001033 out.write(builder.toString());
1034 } catch (IOException e) {
1035 Slog.e(TAG, "Error writing data file");
1036 return;
1037 } finally {
1038 if (out != null) {
1039 try {
1040 out.close();
1041 } catch (Exception e) {}
1042 }
1043 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001044 }
1045
1046 private void retrieve() {
Robert Greenwalt05d06732010-04-19 11:10:38 -07001047 // clean out any old data first. If we fail to read we don't want old stuff
1048 zeroData(0);
1049
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001050 File f = getDataFile();
1051 byte[] buffer;
1052 FileInputStream s = null;
1053 try {
1054 buffer = new byte[(int)f.length()];
1055 s = new FileInputStream(f);
1056 s.read(buffer);
1057 } catch (IOException e) {
1058 Slog.e(TAG, "Error reading data file");
1059 return;
1060 } finally {
1061 if (s != null) {
1062 try {
1063 s.close();
1064 } catch (Exception e) {}
1065 }
1066 }
1067 String data = new String(buffer);
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001068 if (data == null || data.length() == 0) {
1069 if (DBG) Slog.d(TAG, "data file empty");
1070 return;
1071 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001072 String[] parsed = data.split(":");
1073 int parsedUsed = 0;
1074 if (parsed.length < 6) {
1075 Slog.e(TAG, "reading data file with insufficient length - ignoring");
1076 return;
1077 }
1078
Robert Greenwalt9e3983f2010-05-11 07:06:13 -07001079 int periodCount;
1080 long[] periodRxData;
1081 long[] periodTxData;
1082 int currentPeriod;
1083 Calendar periodStart;
1084 Calendar periodEnd;
1085 try {
1086 if (Integer.parseInt(parsed[parsedUsed++]) != DATA_FILE_VERSION) {
1087 Slog.e(TAG, "reading data file with bad version - ignoring");
1088 return;
1089 }
1090
1091 periodCount = Integer.parseInt(parsed[parsedUsed++]);
1092 if (parsed.length != 5 + (2 * periodCount)) {
1093 Slog.e(TAG, "reading data file with bad length (" + parsed.length +
1094 " != " + (5 + (2 * periodCount)) + ") - ignoring");
1095 return;
1096 }
1097 periodRxData = new long[periodCount];
1098 for (int i = 0; i < periodCount; i++) {
1099 periodRxData[i] = Long.parseLong(parsed[parsedUsed++]);
1100 }
1101 periodTxData = new long[periodCount];
1102 for (int i = 0; i < periodCount; i++) {
1103 periodTxData[i] = Long.parseLong(parsed[parsedUsed++]);
1104 }
1105
1106 currentPeriod = Integer.parseInt(parsed[parsedUsed++]);
1107
1108 periodStart = new GregorianCalendar();
1109 periodStart.setTimeInMillis(Long.parseLong(parsed[parsedUsed++]));
1110 periodEnd = new GregorianCalendar();
1111 periodEnd.setTimeInMillis(Long.parseLong(parsed[parsedUsed++]));
1112 } catch (Exception e) {
1113 Slog.e(TAG, "Error parsing data file - ignoring");
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001114 return;
1115 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001116 synchronized (mParent) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001117 mPeriodCount = periodCount;
1118 mPeriodRxData = periodRxData;
1119 mPeriodTxData = periodTxData;
Robert Greenwalt9e3983f2010-05-11 07:06:13 -07001120 mCurrentPeriod = currentPeriod;
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001121 mPeriodStart = periodStart;
1122 mPeriodEnd = periodEnd;
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001123 }
1124 }
1125
1126 long getPeriodRx(int which) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001127 synchronized (mParent) {
1128 if (which > mPeriodCount) return 0;
1129 which = mCurrentPeriod - which;
1130 if (which < 0) which += mPeriodCount;
1131 return mPeriodRxData[which];
1132 }
1133 }
1134 long getPeriodTx(int which) {
1135 synchronized (mParent) {
1136 if (which > mPeriodCount) return 0;
1137 which = mCurrentPeriod - which;
1138 if (which < 0) which += mPeriodCount;
1139 return mPeriodTxData[which];
1140 }
1141 }
1142 }
1143
1144 @Override
1145 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1146 if (mContext.checkCallingOrSelfPermission(
1147 android.Manifest.permission.DUMP)
1148 != PackageManager.PERMISSION_GRANTED) {
1149 pw.println("Permission Denial: can't dump ThrottleService " +
1150 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1151 Binder.getCallingUid());
1152 return;
1153 }
1154 pw.println();
1155
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001156 pw.println("The threshold is " + mPolicyThreshold.get() +
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001157 ", after which you experince throttling to " +
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001158 mPolicyThrottleValue.get() + "kbps");
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001159 pw.println("Current period is " +
1160 (mRecorder.getPeriodEnd() - mRecorder.getPeriodStart())/1000 + " seconds long " +
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001161 "and ends in " + (getResetTime(mIface) - System.currentTimeMillis()) / 1000 +
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001162 " seconds.");
1163 pw.println("Polling every " + mPolicyPollPeriodSec + " seconds");
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001164 pw.println("Current Throttle Index is " + mThrottleIndex.get());
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -07001165 pw.println("mMaxNtpCacheAge=" + mMaxNtpCacheAge);
Robert Greenwalt8c7e6092010-04-14 17:31:20 -07001166
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001167 for (int i = 0; i < mRecorder.getPeriodCount(); i++) {
1168 pw.println(" Period[" + i + "] - read:" + mRecorder.getPeriodRx(i) + ", written:" +
1169 mRecorder.getPeriodTx(i));
1170 }
1171 }
1172}