blob: 510ff62ed514e4fc830083ae2453e6c8b6f76903 [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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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 Greenwalt81aa0972010-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();
536 final int index = stats.findIndex(mIface, NetworkStats.UID_ALL);
537
538 if (index != -1) {
539 incRead = stats.rx[index] - mLastRead;
540 incWrite = stats.tx[index] - mLastWrite;
541 } else {
542 // missing iface, assume stats are 0
543 Slog.w(TAG, "unable to find stats for iface " + mIface);
544 }
545
Robert Greenwalt8c7e6092010-04-14 17:31:20 -0700546 // handle iface resets - on some device the 3g iface comes and goes and gets
547 // totals reset to 0. Deal with it
548 if ((incRead < 0) || (incWrite < 0)) {
549 incRead += mLastRead;
550 incWrite += mLastWrite;
551 mLastRead = 0;
552 mLastWrite = 0;
553 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700554 } catch (RemoteException e) {
555 Slog.e(TAG, "got remoteException in onPollAlarm:" + e);
556 }
Robert Greenwalt5f996892010-04-08 16:19:24 -0700557 // don't count this data if we're roaming.
558 boolean roaming = "true".equals(
559 SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING));
560 if (!roaming) {
561 mRecorder.addData(incRead, incWrite);
562 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700563
564 long periodRx = mRecorder.getPeriodRx(0);
565 long periodTx = mRecorder.getPeriodTx(0);
566 long total = periodRx + periodTx;
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700567 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700568 Slog.d(TAG, "onPollAlarm - roaming =" + roaming +
Robert Greenwalt5f996892010-04-08 16:19:24 -0700569 ", read =" + incRead + ", written =" + incWrite + ", new total =" + total);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700570 }
571 mLastRead += incRead;
572 mLastWrite += incWrite;
573
574 checkThrottleAndPostNotification(total);
575
576 Intent broadcast = new Intent(ThrottleManager.THROTTLE_POLL_ACTION);
577 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_READ, periodRx);
578 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_WRITE, periodTx);
Robert Greenwalt05d06732010-04-19 11:10:38 -0700579 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_START, getPeriodStartTime(mIface));
580 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_END, getResetTime(mIface));
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700581 mContext.sendStickyBroadcast(broadcast);
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700582 mPollStickyBroadcast = broadcast;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700583
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700584 mAlarmManager.cancel(mPendingPollIntent);
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700585 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700586 }
587
Robert Greenwaltfee46832010-05-06 12:25:13 -0700588 private void onIfaceUp() {
589 // if we were throttled before, be sure and set it again - the iface went down
590 // (and may have disappeared all together) and these settings were lost
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700591 if (mThrottleIndex.get() == 1) {
Robert Greenwaltfee46832010-05-06 12:25:13 -0700592 try {
593 mNMService.setInterfaceThrottle(mIface, -1, -1);
594 mNMService.setInterfaceThrottle(mIface,
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700595 mPolicyThrottleValue.get(), mPolicyThrottleValue.get());
Robert Greenwaltfee46832010-05-06 12:25:13 -0700596 } catch (Exception e) {
597 Slog.e(TAG, "error setting Throttle: " + e);
598 }
599 }
600 }
601
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700602 private void checkThrottleAndPostNotification(long currentTotal) {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700603 // is throttling enabled?
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700604 long threshold = mPolicyThreshold.get();
605 if (threshold == 0) {
Robert Greenwaltcce83372010-04-23 17:35:29 -0700606 clearThrottleAndNotification();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700607 return;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700608 }
609
610 // have we spoken with an ntp server yet?
611 // this is controversial, but we'd rather err towards not throttling
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700612 if (!mTime.hasCache()) {
613 Slog.w(TAG, "missing trusted time, skipping throttle check");
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700614 return;
615 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700616
617 // check if we need to throttle
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700618 if (currentTotal > threshold) {
619 if (mThrottleIndex.get() != 1) {
620 mThrottleIndex.set(1);
621 if (DBG) Slog.d(TAG, "Threshold " + threshold + " exceeded!");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700622 try {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700623 mNMService.setInterfaceThrottle(mIface,
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700624 mPolicyThrottleValue.get(), mPolicyThrottleValue.get());
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700625 } catch (Exception e) {
626 Slog.e(TAG, "error setting Throttle: " + e);
627 }
628
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700629 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700630
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700631 postNotification(R.string.throttled_notification_title,
632 R.string.throttled_notification_message,
633 R.drawable.stat_sys_throttled,
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700634 Notification.FLAG_ONGOING_EVENT);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700635
636 Intent broadcast = new Intent(ThrottleManager.THROTTLE_ACTION);
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700637 broadcast.putExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL,
638 mPolicyThrottleValue.get());
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700639 mContext.sendStickyBroadcast(broadcast);
640
641 } // else already up!
642 } else {
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700643 clearThrottleAndNotification();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700644 if ((mPolicyNotificationsAllowedMask & NOTIFICATION_WARNING) != 0) {
645 // check if we should warn about throttle
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700646 // pretend we only have 1/2 the time remaining that we actually do
647 // if our burn rate in the period so far would have us exceed the limit
648 // in that 1/2 window, warn the user.
649 // this gets more generous in the early to middle period and converges back
650 // to the limit as we move toward the period end.
651
652 // adding another factor - it must be greater than the total cap/4
653 // else we may get false alarms very early in the period.. in the first
654 // tenth of a percent of the period if we used more than a tenth of a percent
655 // of the cap we'd get a warning and that's not desired.
656 long start = mRecorder.getPeriodStart();
657 long end = mRecorder.getPeriodEnd();
658 long periodLength = end - start;
659 long now = System.currentTimeMillis();
660 long timeUsed = now - start;
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700661 long warningThreshold = 2*threshold*timeUsed/(timeUsed+periodLength);
662 if ((currentTotal > warningThreshold) && (currentTotal > threshold/4)) {
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700663 if (mWarningNotificationSent == false) {
664 mWarningNotificationSent = true;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700665 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
666 postNotification(R.string.throttle_warning_notification_title,
667 R.string.throttle_warning_notification_message,
668 R.drawable.stat_sys_throttled,
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700669 0);
670 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700671 } else {
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700672 if (mWarningNotificationSent == true) {
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700673 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700674 mWarningNotificationSent =false;
675 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700676 }
677 }
678 }
679 }
680
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700681 private void postNotification(int titleInt, int messageInt, int icon, int flags) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700682 Intent intent = new Intent();
683 // TODO - fix up intent
Robert Greenwalt2a7b7302010-04-12 14:56:31 -0700684 intent.setClassName("com.android.phone", "com.android.phone.DataUsage");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700685 intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
686
687 PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
688
689 Resources r = Resources.getSystem();
690 CharSequence title = r.getText(titleInt);
691 CharSequence message = r.getText(messageInt);
692 if (mThrottlingNotification == null) {
693 mThrottlingNotification = new Notification();
694 mThrottlingNotification.when = 0;
695 // TODO - fixup icon
696 mThrottlingNotification.icon = icon;
697 mThrottlingNotification.defaults &= ~Notification.DEFAULT_SOUND;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700698 }
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700699 mThrottlingNotification.flags = flags;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700700 mThrottlingNotification.tickerText = title;
701 mThrottlingNotification.setLatestEventInfo(mContext, title, message, pi);
702
703 mNotificationManager.notify(mThrottlingNotification.icon, mThrottlingNotification);
704 }
705
706
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700707 private void clearThrottleAndNotification() {
708 if (mThrottleIndex.get() != THROTTLE_INDEX_UNTHROTTLED) {
709 mThrottleIndex.set(THROTTLE_INDEX_UNTHROTTLED);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700710 try {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700711 mNMService.setInterfaceThrottle(mIface, -1, -1);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700712 } catch (Exception e) {
713 Slog.e(TAG, "error clearing Throttle: " + e);
714 }
715 Intent broadcast = new Intent(ThrottleManager.THROTTLE_ACTION);
716 broadcast.putExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL, -1);
717 mContext.sendStickyBroadcast(broadcast);
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700718 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
719 mWarningNotificationSent = false;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700720 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700721 }
722
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700723 private Calendar calculatePeriodEnd(long now) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700724 Calendar end = GregorianCalendar.getInstance();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700725 end.setTimeInMillis(now);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700726 int day = end.get(Calendar.DAY_OF_MONTH);
727 end.set(Calendar.DAY_OF_MONTH, mPolicyResetDay);
728 end.set(Calendar.HOUR_OF_DAY, 0);
729 end.set(Calendar.MINUTE, 0);
Robert Greenwalt8c7e6092010-04-14 17:31:20 -0700730 end.set(Calendar.SECOND, 0);
731 end.set(Calendar.MILLISECOND, 0);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700732 if (day >= mPolicyResetDay) {
733 int month = end.get(Calendar.MONTH);
734 if (month == Calendar.DECEMBER) {
735 end.set(Calendar.YEAR, end.get(Calendar.YEAR) + 1);
736 month = Calendar.JANUARY - 1;
737 }
738 end.set(Calendar.MONTH, month + 1);
739 }
740
741 // TODO - remove!
742 if (SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true")) {
743 end = GregorianCalendar.getInstance();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700744 end.setTimeInMillis(now);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700745 end.add(Calendar.SECOND, TESTING_RESET_PERIOD_SEC);
746 }
747 return end;
748 }
749 private Calendar calculatePeriodStart(Calendar end) {
750 Calendar start = (Calendar)end.clone();
751 int month = end.get(Calendar.MONTH);
752 if (end.get(Calendar.MONTH) == Calendar.JANUARY) {
753 month = Calendar.DECEMBER + 1;
754 start.set(Calendar.YEAR, start.get(Calendar.YEAR) - 1);
755 }
756 start.set(Calendar.MONTH, month - 1);
757
758 // TODO - remove!!
759 if (SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true")) {
760 start = (Calendar)end.clone();
761 start.add(Calendar.SECOND, -TESTING_RESET_PERIOD_SEC);
762 }
763 return start;
764 }
765
766 private void onResetAlarm() {
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700767 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700768 Slog.d(TAG, "onResetAlarm - last period had " + mRecorder.getPeriodRx(0) +
769 " bytes read and " + mRecorder.getPeriodTx(0) + " written");
770 }
771
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700772 // when trusted cache outdated, try refreshing
773 if (mTime.getCacheAge() > mMaxNtpCacheAge) {
774 mTime.forceRefresh();
775 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700776
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700777 // as long as we have a trusted time cache, we always reset alarms,
778 // even if the refresh above failed.
779 if (mTime.hasCache()) {
780 final long now = mTime.currentTimeMillis();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700781 Calendar end = calculatePeriodEnd(now);
782 Calendar start = calculatePeriodStart(end);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700783
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700784 if (mRecorder.setNextPeriod(start, end)) {
Robert Greenwalt05d06732010-04-19 11:10:38 -0700785 onPollAlarm();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700786 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700787
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700788 mAlarmManager.cancel(mPendingResetIntent);
789 long offset = end.getTimeInMillis() - now;
790 // use Elapsed realtime so clock changes don't fool us.
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700791 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME,
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700792 SystemClock.elapsedRealtime() + offset,
793 mPendingResetIntent);
794 } else {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700795 if (VDBG) Slog.d(TAG, "no trusted time, not resetting period");
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700796 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700797 }
798 }
799
800 // records bytecount data for a given time and accumulates it into larger time windows
801 // for logging and other purposes
802 //
803 // since time can be changed (user or network action) we will have to track the time of the
804 // last recording and deal with it.
805 private static class DataRecorder {
806 long[] mPeriodRxData;
807 long[] mPeriodTxData;
808 int mCurrentPeriod;
809 int mPeriodCount;
810
811 Calendar mPeriodStart;
812 Calendar mPeriodEnd;
813
814 ThrottleService mParent;
815 Context mContext;
Robert Greenwalte6e98822010-04-15 08:27:14 -0700816 String mImsi = null;
817
818 TelephonyManager mTelephonyManager;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700819
820 DataRecorder(Context context, ThrottleService parent) {
821 mContext = context;
822 mParent = parent;
823
Robert Greenwalte6e98822010-04-15 08:27:14 -0700824 mTelephonyManager = (TelephonyManager)mContext.getSystemService(
825 Context.TELEPHONY_SERVICE);
826
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700827 synchronized (mParent) {
828 mPeriodCount = 6;
829 mPeriodRxData = new long[mPeriodCount];
830 mPeriodTxData = new long[mPeriodCount];
831
832 mPeriodStart = Calendar.getInstance();
833 mPeriodEnd = Calendar.getInstance();
834
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700835 retrieve();
836 }
837 }
838
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700839 boolean setNextPeriod(Calendar start, Calendar end) {
Robert Greenwalte6e98822010-04-15 08:27:14 -0700840 // TODO - how would we deal with a dual-IMSI device?
841 checkForSubscriberId();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700842 boolean startNewPeriod = true;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700843
Robert Greenwalt27fba672010-04-26 12:29:14 -0700844 if (start.equals(mPeriodStart) && end.equals(mPeriodEnd)) {
845 // same endpoints - keep collecting
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700846 if (VDBG) {
Robert Greenwalt27fba672010-04-26 12:29:14 -0700847 Slog.d(TAG, "same period (" + start.getTimeInMillis() + "," +
848 end.getTimeInMillis() +") - ammending data");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700849 }
Robert Greenwalt27fba672010-04-26 12:29:14 -0700850 startNewPeriod = false;
851 } else {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700852 if (VDBG) {
Robert Greenwalt27fba672010-04-26 12:29:14 -0700853 if(start.equals(mPeriodEnd) || start.after(mPeriodEnd)) {
854 Slog.d(TAG, "next period (" + start.getTimeInMillis() + "," +
855 end.getTimeInMillis() + ") - old end was " +
856 mPeriodEnd.getTimeInMillis() + ", following");
857 } else {
858 Slog.d(TAG, "new period (" + start.getTimeInMillis() + "," +
859 end.getTimeInMillis() + ") replacing old (" +
860 mPeriodStart.getTimeInMillis() + "," +
861 mPeriodEnd.getTimeInMillis() + ")");
862 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700863 }
864 synchronized (mParent) {
865 ++mCurrentPeriod;
866 if (mCurrentPeriod >= mPeriodCount) mCurrentPeriod = 0;
867 mPeriodRxData[mCurrentPeriod] = 0;
868 mPeriodTxData[mCurrentPeriod] = 0;
869 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700870 }
871 setPeriodStart(start);
872 setPeriodEnd(end);
873 record();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700874 return startNewPeriod;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700875 }
876
877 public long getPeriodEnd() {
878 synchronized (mParent) {
879 return mPeriodEnd.getTimeInMillis();
880 }
881 }
882
883 private void setPeriodEnd(Calendar end) {
884 synchronized (mParent) {
885 mPeriodEnd = end;
886 }
887 }
888
889 public long getPeriodStart() {
890 synchronized (mParent) {
891 return mPeriodStart.getTimeInMillis();
892 }
893 }
894
895 private void setPeriodStart(Calendar start) {
896 synchronized (mParent) {
897 mPeriodStart = start;
898 }
899 }
900
901 public int getPeriodCount() {
902 synchronized (mParent) {
903 return mPeriodCount;
904 }
905 }
906
907 private void zeroData(int field) {
908 synchronized (mParent) {
909 for(int period = 0; period<mPeriodCount; period++) {
910 mPeriodRxData[period] = 0;
911 mPeriodTxData[period] = 0;
912 }
913 mCurrentPeriod = 0;
914 }
915
916 }
917
918 // if time moves backward accumulate all read/write that's lost into the now
919 // otherwise time moved forward.
920 void addData(long bytesRead, long bytesWritten) {
Robert Greenwalte6e98822010-04-15 08:27:14 -0700921 checkForSubscriberId();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700922
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700923 synchronized (mParent) {
924 mPeriodRxData[mCurrentPeriod] += bytesRead;
925 mPeriodTxData[mCurrentPeriod] += bytesWritten;
926 }
927 record();
928 }
929
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700930 private File getDataFile() {
931 File dataDir = Environment.getDataDirectory();
932 File throttleDir = new File(dataDir, "system/throttle");
933 throttleDir.mkdirs();
Robert Greenwalte6e98822010-04-15 08:27:14 -0700934 String mImsi = mTelephonyManager.getSubscriberId();
935 File dataFile;
936 if (mImsi == null) {
937 dataFile = useMRUFile(throttleDir);
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700938 if (VDBG) Slog.v(TAG, "imsi not available yet, using " + dataFile);
Robert Greenwalte6e98822010-04-15 08:27:14 -0700939 } else {
940 String imsiHash = Integer.toString(mImsi.hashCode());
941 dataFile = new File(throttleDir, imsiHash);
942 }
943 // touch the file so it's not LRU
944 dataFile.setLastModified(System.currentTimeMillis());
945 checkAndDeleteLRUDataFile(throttleDir);
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700946 return dataFile;
947 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700948
Robert Greenwalte6e98822010-04-15 08:27:14 -0700949 // TODO - get broadcast (TelephonyIntents.ACTION_SIM_STATE_CHANGED) instead of polling
950 private void checkForSubscriberId() {
951 if (mImsi != null) return;
952
953 mImsi = mTelephonyManager.getSubscriberId();
954 if (mImsi == null) return;
955
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700956 if (VDBG) Slog.d(TAG, "finally have imsi - retreiving data");
Robert Greenwalte6e98822010-04-15 08:27:14 -0700957 retrieve();
958 }
959
960 private final static int MAX_SIMS_SUPPORTED = 3;
961
962 private void checkAndDeleteLRUDataFile(File dir) {
963 File[] files = dir.listFiles();
964
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700965 if (files == null || files.length <= MAX_SIMS_SUPPORTED) return;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700966 if (DBG) Slog.d(TAG, "Too many data files");
Robert Greenwalte6e98822010-04-15 08:27:14 -0700967 do {
968 File oldest = null;
969 for (File f : files) {
970 if ((oldest == null) || (oldest.lastModified() > f.lastModified())) {
971 oldest = f;
972 }
973 }
974 if (oldest == null) return;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700975 if (DBG) Slog.d(TAG, " deleting " + oldest);
Robert Greenwalte6e98822010-04-15 08:27:14 -0700976 oldest.delete();
977 files = dir.listFiles();
978 } while (files.length > MAX_SIMS_SUPPORTED);
979 }
980
981 private File useMRUFile(File dir) {
982 File newest = null;
983 File[] files = dir.listFiles();
984
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700985 if (files != null) {
986 for (File f : files) {
987 if ((newest == null) || (newest.lastModified() < f.lastModified())) {
988 newest = f;
989 }
Robert Greenwalte6e98822010-04-15 08:27:14 -0700990 }
991 }
992 if (newest == null) {
993 newest = new File(dir, "temp");
994 }
995 return newest;
996 }
997
998
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700999 private static final int DATA_FILE_VERSION = 1;
1000
1001 private void record() {
1002 // 1 int version
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001003 // 1 int mPeriodCount
1004 // 13*6 long[PERIOD_COUNT] mPeriodRxData
1005 // 13*6 long[PERIOD_COUNT] mPeriodTxData
1006 // 1 int mCurrentPeriod
1007 // 13 long periodStartMS
1008 // 13 long periodEndMS
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001009 // 200 chars max
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001010 StringBuilder builder = new StringBuilder();
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001011 builder.append(DATA_FILE_VERSION);
1012 builder.append(":");
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001013 builder.append(mPeriodCount);
1014 builder.append(":");
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001015 for(int i = 0; i < mPeriodCount; i++) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001016 builder.append(mPeriodRxData[i]);
1017 builder.append(":");
1018 }
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001019 for(int i = 0; i < mPeriodCount; i++) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001020 builder.append(mPeriodTxData[i]);
1021 builder.append(":");
1022 }
1023 builder.append(mCurrentPeriod);
1024 builder.append(":");
1025 builder.append(mPeriodStart.getTimeInMillis());
1026 builder.append(":");
1027 builder.append(mPeriodEnd.getTimeInMillis());
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001028
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001029 BufferedWriter out = null;
1030 try {
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001031 out = new BufferedWriter(new FileWriter(getDataFile()), 256);
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001032 out.write(builder.toString());
1033 } catch (IOException e) {
1034 Slog.e(TAG, "Error writing data file");
1035 return;
1036 } finally {
1037 if (out != null) {
1038 try {
1039 out.close();
1040 } catch (Exception e) {}
1041 }
1042 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001043 }
1044
1045 private void retrieve() {
Robert Greenwalt05d06732010-04-19 11:10:38 -07001046 // clean out any old data first. If we fail to read we don't want old stuff
1047 zeroData(0);
1048
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001049 File f = getDataFile();
1050 byte[] buffer;
1051 FileInputStream s = null;
1052 try {
1053 buffer = new byte[(int)f.length()];
1054 s = new FileInputStream(f);
1055 s.read(buffer);
1056 } catch (IOException e) {
1057 Slog.e(TAG, "Error reading data file");
1058 return;
1059 } finally {
1060 if (s != null) {
1061 try {
1062 s.close();
1063 } catch (Exception e) {}
1064 }
1065 }
1066 String data = new String(buffer);
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001067 if (data == null || data.length() == 0) {
1068 if (DBG) Slog.d(TAG, "data file empty");
1069 return;
1070 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001071 String[] parsed = data.split(":");
1072 int parsedUsed = 0;
1073 if (parsed.length < 6) {
1074 Slog.e(TAG, "reading data file with insufficient length - ignoring");
1075 return;
1076 }
1077
Robert Greenwalt9e3983f2010-05-11 07:06:13 -07001078 int periodCount;
1079 long[] periodRxData;
1080 long[] periodTxData;
1081 int currentPeriod;
1082 Calendar periodStart;
1083 Calendar periodEnd;
1084 try {
1085 if (Integer.parseInt(parsed[parsedUsed++]) != DATA_FILE_VERSION) {
1086 Slog.e(TAG, "reading data file with bad version - ignoring");
1087 return;
1088 }
1089
1090 periodCount = Integer.parseInt(parsed[parsedUsed++]);
1091 if (parsed.length != 5 + (2 * periodCount)) {
1092 Slog.e(TAG, "reading data file with bad length (" + parsed.length +
1093 " != " + (5 + (2 * periodCount)) + ") - ignoring");
1094 return;
1095 }
1096 periodRxData = new long[periodCount];
1097 for (int i = 0; i < periodCount; i++) {
1098 periodRxData[i] = Long.parseLong(parsed[parsedUsed++]);
1099 }
1100 periodTxData = new long[periodCount];
1101 for (int i = 0; i < periodCount; i++) {
1102 periodTxData[i] = Long.parseLong(parsed[parsedUsed++]);
1103 }
1104
1105 currentPeriod = Integer.parseInt(parsed[parsedUsed++]);
1106
1107 periodStart = new GregorianCalendar();
1108 periodStart.setTimeInMillis(Long.parseLong(parsed[parsedUsed++]));
1109 periodEnd = new GregorianCalendar();
1110 periodEnd.setTimeInMillis(Long.parseLong(parsed[parsedUsed++]));
1111 } catch (Exception e) {
1112 Slog.e(TAG, "Error parsing data file - ignoring");
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001113 return;
1114 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001115 synchronized (mParent) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001116 mPeriodCount = periodCount;
1117 mPeriodRxData = periodRxData;
1118 mPeriodTxData = periodTxData;
Robert Greenwalt9e3983f2010-05-11 07:06:13 -07001119 mCurrentPeriod = currentPeriod;
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001120 mPeriodStart = periodStart;
1121 mPeriodEnd = periodEnd;
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001122 }
1123 }
1124
1125 long getPeriodRx(int which) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001126 synchronized (mParent) {
1127 if (which > mPeriodCount) return 0;
1128 which = mCurrentPeriod - which;
1129 if (which < 0) which += mPeriodCount;
1130 return mPeriodRxData[which];
1131 }
1132 }
1133 long getPeriodTx(int which) {
1134 synchronized (mParent) {
1135 if (which > mPeriodCount) return 0;
1136 which = mCurrentPeriod - which;
1137 if (which < 0) which += mPeriodCount;
1138 return mPeriodTxData[which];
1139 }
1140 }
1141 }
1142
1143 @Override
1144 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1145 if (mContext.checkCallingOrSelfPermission(
1146 android.Manifest.permission.DUMP)
1147 != PackageManager.PERMISSION_GRANTED) {
1148 pw.println("Permission Denial: can't dump ThrottleService " +
1149 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1150 Binder.getCallingUid());
1151 return;
1152 }
1153 pw.println();
1154
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001155 pw.println("The threshold is " + mPolicyThreshold.get() +
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001156 ", after which you experince throttling to " +
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001157 mPolicyThrottleValue.get() + "kbps");
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001158 pw.println("Current period is " +
1159 (mRecorder.getPeriodEnd() - mRecorder.getPeriodStart())/1000 + " seconds long " +
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001160 "and ends in " + (getResetTime(mIface) - System.currentTimeMillis()) / 1000 +
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001161 " seconds.");
1162 pw.println("Polling every " + mPolicyPollPeriodSec + " seconds");
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001163 pw.println("Current Throttle Index is " + mThrottleIndex.get());
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -07001164 pw.println("mMaxNtpCacheAge=" + mMaxNtpCacheAge);
Robert Greenwalt8c7e6092010-04-14 17:31:20 -07001165
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001166 for (int i = 0; i < mRecorder.getPeriodCount(); i++) {
1167 pw.println(" Period[" + i + "] - read:" + mRecorder.getPeriodRx(i) + ", written:" +
1168 mRecorder.getPeriodTx(i));
1169 }
1170 }
1171}