blob: cd649ce4c5548b076243bb127a217a968636adc7 [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
19import android.app.AlarmManager;
20import android.app.Notification;
21import android.app.NotificationManager;
22import android.app.PendingIntent;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070023import android.content.BroadcastReceiver;
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -070024import android.content.ContentResolver;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.pm.PackageManager;
29import android.content.res.Resources;
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -070030import android.database.ContentObserver;
Robert Greenwaltfee46832010-05-06 12:25:13 -070031import android.net.INetworkManagementEventObserver;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070032import android.net.IThrottleManager;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070033import android.net.NetworkStats;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070034import android.net.ThrottleManager;
35import android.os.Binder;
Robert Greenwaltb8912f52010-04-09 17:27:26 -070036import android.os.Environment;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070037import android.os.Handler;
38import android.os.HandlerThread;
39import android.os.IBinder;
40import android.os.INetworkManagementService;
41import android.os.Looper;
42import android.os.Message;
43import android.os.RemoteException;
44import android.os.ServiceManager;
45import android.os.SystemClock;
46import android.os.SystemProperties;
47import android.provider.Settings;
Robert Greenwalte6e98822010-04-15 08:27:14 -070048import android.telephony.TelephonyManager;
Robert Greenwaltfee46832010-05-06 12:25:13 -070049import android.text.TextUtils;
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070050import android.util.NtpTrustedTime;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070051import android.util.Slog;
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070052import android.util.TrustedTime;
Robert Greenwalt5f996892010-04-08 16:19:24 -070053
Jeff Sharkey104344e2011-07-10 14:20:41 -070054import com.android.internal.R;
55import com.android.internal.telephony.TelephonyProperties;
56
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;
66import java.util.Random;
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070067import java.util.concurrent.atomic.AtomicInteger;
68import java.util.concurrent.atomic.AtomicLong;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070069
70// TODO - add comments - reference the ThrottleManager for public API
71public class ThrottleService extends IThrottleManager.Stub {
72
73 private static final String TESTING_ENABLED_PROPERTY = "persist.throttle.testing";
74
75 private static final String TAG = "ThrottleService";
Robert Greenwaltbf7de392010-04-21 17:09:38 -070076 private static final boolean DBG = true;
77 private static final boolean VDBG = false;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070078 private Handler mHandler;
79 private HandlerThread mThread;
80
81 private Context mContext;
82
Robert Greenwaltfb9896b2010-04-22 15:39:38 -070083 private static final int INITIAL_POLL_DELAY_SEC = 90;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070084 private static final int TESTING_POLLING_PERIOD_SEC = 60 * 1;
Robert Greenwalt7171ea82010-04-14 22:37:12 -070085 private static final int TESTING_RESET_PERIOD_SEC = 60 * 10;
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -070086 private static final long TESTING_THRESHOLD = 1 * 1024 * 1024;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070087
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070088 private static final long MAX_NTP_CACHE_AGE = 24 * 60 * 60 * 1000;
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -070089
90 private long mMaxNtpCacheAge = MAX_NTP_CACHE_AGE;
91
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -070092 private int mPolicyPollPeriodSec;
Robert Greenwalt39e163f2010-05-07 16:52:17 -070093 private AtomicLong mPolicyThreshold;
94 private AtomicInteger mPolicyThrottleValue;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070095 private int mPolicyResetDay; // 1-28
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -070096 private int mPolicyNotificationsAllowedMask;
Robert Greenwalt9e696c22010-04-01 14:45:18 -070097
98 private long mLastRead; // read byte count from last poll
99 private long mLastWrite; // write byte count from last poll
100
101 private static final String ACTION_POLL = "com.android.server.ThrottleManager.action.POLL";
102 private static int POLL_REQUEST = 0;
103 private PendingIntent mPendingPollIntent;
104 private static final String ACTION_RESET = "com.android.server.ThorottleManager.action.RESET";
105 private static int RESET_REQUEST = 1;
106 private PendingIntent mPendingResetIntent;
107
108 private INetworkManagementService mNMService;
109 private AlarmManager mAlarmManager;
110 private NotificationManager mNotificationManager;
111
112 private DataRecorder mRecorder;
113
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700114 private String mIface;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700115
116 private static final int NOTIFICATION_WARNING = 2;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700117
118 private Notification mThrottlingNotification;
119 private boolean mWarningNotificationSent = false;
120
Robert Greenwaltfee46832010-05-06 12:25:13 -0700121 private InterfaceObserver mInterfaceObserver;
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700122 private SettingsObserver mSettingsObserver;
123
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700124 private AtomicInteger mThrottleIndex; // 0 for none, 1 for first throttle val, 2 for next, etc
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700125 private static final int THROTTLE_INDEX_UNINITIALIZED = -1;
126 private static final int THROTTLE_INDEX_UNTHROTTLED = 0;
127
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700128 private Intent mPollStickyBroadcast;
129
130 private TrustedTime mTime;
131
132 private static INetworkManagementService getNetworkManagementService() {
133 final IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
134 return INetworkManagementService.Stub.asInterface(b);
135 }
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700136
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700137 public ThrottleService(Context context) {
Jeff Sharkey104344e2011-07-10 14:20:41 -0700138 this(context, getNetworkManagementService(), NtpTrustedTime.getInstance(context),
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700139 context.getResources().getString(R.string.config_datause_iface));
140 }
141
142 public ThrottleService(Context context, INetworkManagementService nmService, TrustedTime time,
143 String iface) {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700144 if (VDBG) Slog.v(TAG, "Starting ThrottleService");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700145 mContext = context;
146
Robert Greenwalt24488bd2010-05-10 16:56:43 -0700147 mPolicyThreshold = new AtomicLong();
148 mPolicyThrottleValue = new AtomicInteger();
149 mThrottleIndex = new AtomicInteger();
150
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700151 mIface = iface;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700152 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
153 Intent pollIntent = new Intent(ACTION_POLL, null);
154 mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
155 Intent resetIntent = new Intent(ACTION_RESET, null);
156 mPendingResetIntent = PendingIntent.getBroadcast(mContext, RESET_REQUEST, resetIntent, 0);
157
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700158 mNMService = nmService;
159 mTime = time;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700160
161 mNotificationManager = (NotificationManager)mContext.getSystemService(
162 Context.NOTIFICATION_SERVICE);
163 }
164
Robert Greenwaltfee46832010-05-06 12:25:13 -0700165 private static class InterfaceObserver extends INetworkManagementEventObserver.Stub {
166 private int mMsg;
167 private Handler mHandler;
168 private String mIface;
169
170 InterfaceObserver(Handler handler, int msg, String iface) {
171 super();
172 mHandler = handler;
173 mMsg = msg;
174 mIface = iface;
175 }
176
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700177 public void interfaceStatusChanged(String iface, boolean up) {
178 if (up) {
Robert Greenwaltfee46832010-05-06 12:25:13 -0700179 if (TextUtils.equals(iface, mIface)) {
180 mHandler.obtainMessage(mMsg).sendToTarget();
181 }
182 }
183 }
184
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700185 public void interfaceLinkStateChanged(String iface, boolean up) {
186 }
187
Robert Greenwaltfee46832010-05-06 12:25:13 -0700188 public void interfaceAdded(String iface) {
189 // TODO - an interface added in the UP state should also trigger a StatusChanged
190 // notification..
191 if (TextUtils.equals(iface, mIface)) {
192 mHandler.obtainMessage(mMsg).sendToTarget();
193 }
194 }
195
196 public void interfaceRemoved(String iface) {}
JP Abgrall12b933d2011-07-14 18:09:22 -0700197 public void limitReached(String limitName, String iface) {}
Robert Greenwaltfee46832010-05-06 12:25:13 -0700198 }
199
200
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700201 private static class SettingsObserver extends ContentObserver {
202 private int mMsg;
203 private Handler mHandler;
204 SettingsObserver(Handler handler, int msg) {
205 super(handler);
206 mHandler = handler;
207 mMsg = msg;
208 }
209
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700210 void register(Context context) {
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700211 ContentResolver resolver = context.getContentResolver();
212 resolver.registerContentObserver(Settings.Secure.getUriFor(
213 Settings.Secure.THROTTLE_POLLING_SEC), false, this);
214 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700215 Settings.Secure.THROTTLE_THRESHOLD_BYTES), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700216 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700217 Settings.Secure.THROTTLE_VALUE_KBITSPS), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700218 resolver.registerContentObserver(Settings.Secure.getUriFor(
219 Settings.Secure.THROTTLE_RESET_DAY), false, this);
220 resolver.registerContentObserver(Settings.Secure.getUriFor(
221 Settings.Secure.THROTTLE_NOTIFICATION_TYPE), false, this);
222 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700223 Settings.Secure.THROTTLE_HELP_URI), false, this);
Robert Greenwaltd1055a22010-05-25 15:54:52 -0700224 resolver.registerContentObserver(Settings.Secure.getUriFor(
225 Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700226 }
227
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700228 void unregister(Context context) {
229 final ContentResolver resolver = context.getContentResolver();
230 resolver.unregisterContentObserver(this);
231 }
232
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700233 @Override
234 public void onChange(boolean selfChange) {
235 mHandler.obtainMessage(mMsg).sendToTarget();
236 }
237 }
238
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700239 private void enforceAccessPermission() {
240 mContext.enforceCallingOrSelfPermission(
241 android.Manifest.permission.ACCESS_NETWORK_STATE,
242 "ThrottleService");
243 }
244
Robert Greenwalt05d06732010-04-19 11:10:38 -0700245 private long ntpToWallTime(long ntpTime) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700246 // get time quickly without worrying about trusted state
247 long bestNow = mTime.hasCache() ? mTime.currentTimeMillis()
248 : System.currentTimeMillis();
Robert Greenwalt05d06732010-04-19 11:10:38 -0700249 long localNow = System.currentTimeMillis();
250 return localNow + (ntpTime - bestNow);
251 }
252
Irfan Sheriffcf282362010-04-16 16:53:20 -0700253 // TODO - fetch for the iface
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700254 // return time in the local, system wall time, correcting for the use of ntp
Robert Greenwalt05d06732010-04-19 11:10:38 -0700255
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700256 public long getResetTime(String iface) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700257 enforceAccessPermission();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700258 long resetTime = 0;
Irfan Sheriffcf282362010-04-16 16:53:20 -0700259 if (mRecorder != null) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700260 resetTime = mRecorder.getPeriodEnd();
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700261 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700262 resetTime = ntpToWallTime(resetTime);
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700263 return resetTime;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700264 }
Irfan Sheriffcf282362010-04-16 16:53:20 -0700265
266 // TODO - fetch for the iface
Robert Greenwalt05d06732010-04-19 11:10:38 -0700267 // return time in the local, system wall time, correcting for the use of ntp
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700268 public long getPeriodStartTime(String iface) {
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700269 long startTime = 0;
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700270 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700271 if (mRecorder != null) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700272 startTime = mRecorder.getPeriodStart();
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700273 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700274 startTime = ntpToWallTime(startTime);
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700275 return startTime;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700276 }
277 //TODO - a better name? getCliffByteCountThreshold?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700278 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700279 public long getCliffThreshold(String iface, int cliff) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700280 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700281 if (cliff == 1) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700282 return mPolicyThreshold.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700283 }
284 return 0;
285 }
286 // TODO - a better name? getThrottleRate?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700287 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700288 public int getCliffLevel(String iface, int cliff) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700289 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700290 if (cliff == 1) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700291 return mPolicyThrottleValue.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700292 }
293 return 0;
294 }
295
Irfan Sheriffc9b68512010-04-08 14:12:33 -0700296 public String getHelpUri() {
297 enforceAccessPermission();
298 return Settings.Secure.getString(mContext.getContentResolver(),
299 Settings.Secure.THROTTLE_HELP_URI);
300 }
301
Irfan Sheriffcf282362010-04-16 16:53:20 -0700302 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700303 public long getByteCount(String iface, int dir, int period, int ago) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700304 enforceAccessPermission();
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700305 if ((period == ThrottleManager.PERIOD_CYCLE) && (mRecorder != null)) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700306 if (dir == ThrottleManager.DIRECTION_TX) return mRecorder.getPeriodTx(ago);
307 if (dir == ThrottleManager.DIRECTION_RX) return mRecorder.getPeriodRx(ago);
308 }
309 return 0;
310 }
311
312 // TODO - a better name - getCurrentThrottleRate?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700313 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700314 public int getThrottle(String iface) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700315 enforceAccessPermission();
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700316 if (mThrottleIndex.get() == 1) {
317 return mPolicyThrottleValue.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700318 }
319 return 0;
320 }
321
322 void systemReady() {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700323 if (VDBG) Slog.v(TAG, "systemReady");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700324 mContext.registerReceiver(
325 new BroadcastReceiver() {
326 @Override
327 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700328 dispatchPoll();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700329 }
330 }, new IntentFilter(ACTION_POLL));
331
332 mContext.registerReceiver(
333 new BroadcastReceiver() {
334 @Override
335 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700336 dispatchReset();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700337 }
338 }, new IntentFilter(ACTION_RESET));
339
Robert Greenwaltc76c15e2010-06-16 14:42:16 -0700340 // use a new thread as we don't want to stall the system for file writes
341 mThread = new HandlerThread(TAG);
342 mThread.start();
343 mHandler = new MyHandler(mThread.getLooper());
344 mHandler.obtainMessage(EVENT_REBOOT_RECOVERY).sendToTarget();
345
346 mInterfaceObserver = new InterfaceObserver(mHandler, EVENT_IFACE_UP, mIface);
347 try {
348 mNMService.registerObserver(mInterfaceObserver);
349 } catch (RemoteException e) {
350 Slog.e(TAG, "Could not register InterfaceObserver " + e);
351 }
352
353 mSettingsObserver = new SettingsObserver(mHandler, EVENT_POLICY_CHANGED);
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700354 mSettingsObserver.register(mContext);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700355 }
356
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700357 void shutdown() {
358 // TODO: eventually connect with ShutdownThread to persist stats during
359 // graceful shutdown.
360
361 if (mThread != null) {
362 mThread.quit();
363 }
364
365 if (mSettingsObserver != null) {
366 mSettingsObserver.unregister(mContext);
367 }
368
369 if (mPollStickyBroadcast != null) {
370 mContext.removeStickyBroadcast(mPollStickyBroadcast);
371 }
372 }
373
374 void dispatchPoll() {
375 mHandler.obtainMessage(EVENT_POLL_ALARM).sendToTarget();
376 }
377
378 void dispatchReset() {
379 mHandler.obtainMessage(EVENT_RESET_ALARM).sendToTarget();
380 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700381
382 private static final int EVENT_REBOOT_RECOVERY = 0;
383 private static final int EVENT_POLICY_CHANGED = 1;
384 private static final int EVENT_POLL_ALARM = 2;
385 private static final int EVENT_RESET_ALARM = 3;
Robert Greenwaltfee46832010-05-06 12:25:13 -0700386 private static final int EVENT_IFACE_UP = 4;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700387 private class MyHandler extends Handler {
388 public MyHandler(Looper l) {
389 super(l);
390 }
391
392 @Override
393 public void handleMessage(Message msg) {
394 switch (msg.what) {
395 case EVENT_REBOOT_RECOVERY:
396 onRebootRecovery();
397 break;
398 case EVENT_POLICY_CHANGED:
399 onPolicyChanged();
400 break;
401 case EVENT_POLL_ALARM:
402 onPollAlarm();
403 break;
404 case EVENT_RESET_ALARM:
405 onResetAlarm();
Robert Greenwaltfee46832010-05-06 12:25:13 -0700406 break;
407 case EVENT_IFACE_UP:
408 onIfaceUp();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700409 }
410 }
411
412 private void onRebootRecovery() {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700413 if (VDBG) Slog.v(TAG, "onRebootRecovery");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700414 // check for sim change TODO
415 // reregister for notification of policy change
416
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700417 mThrottleIndex.set(THROTTLE_INDEX_UNINITIALIZED);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700418
419 mRecorder = new DataRecorder(mContext, ThrottleService.this);
420
421 // get policy
422 mHandler.obtainMessage(EVENT_POLICY_CHANGED).sendToTarget();
Robert Greenwaltfb9896b2010-04-22 15:39:38 -0700423
424 // if we poll now we won't have network connectivity or even imsi access
425 // queue up a poll to happen in a little while - after ntp and imsi are avail
426 // TODO - make this callback based (ie, listen for notificaitons)
427 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_POLL_ALARM),
428 INITIAL_POLL_DELAY_SEC * 1000);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700429 }
430
431 // check for new policy info (threshold limit/value/etc)
432 private void onPolicyChanged() {
433 boolean testing = SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true");
434
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700435 int pollingPeriod = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700436 R.integer.config_datause_polling_period_sec);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700437 mPolicyPollPeriodSec = Settings.Secure.getInt(mContext.getContentResolver(),
438 Settings.Secure.THROTTLE_POLLING_SEC, pollingPeriod);
439
440 // TODO - remove testing stuff?
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700441 long defaultThreshold = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700442 R.integer.config_datause_threshold_bytes);
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700443 int defaultValue = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700444 R.integer.config_datause_throttle_kbitsps);
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700445 long threshold = Settings.Secure.getLong(mContext.getContentResolver(),
446 Settings.Secure.THROTTLE_THRESHOLD_BYTES, defaultThreshold);
447 int value = Settings.Secure.getInt(mContext.getContentResolver(),
448 Settings.Secure.THROTTLE_VALUE_KBITSPS, defaultValue);
449
450 mPolicyThreshold.set(threshold);
451 mPolicyThrottleValue.set(value);
452 if (testing) {
453 mPolicyPollPeriodSec = TESTING_POLLING_PERIOD_SEC;
454 mPolicyThreshold.set(TESTING_THRESHOLD);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700455 }
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700456
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700457 mPolicyResetDay = Settings.Secure.getInt(mContext.getContentResolver(),
458 Settings.Secure.THROTTLE_RESET_DAY, -1);
459 if (mPolicyResetDay == -1 ||
460 ((mPolicyResetDay < 1) || (mPolicyResetDay > 28))) {
461 Random g = new Random();
462 mPolicyResetDay = 1 + g.nextInt(28); // 1-28
463 Settings.Secure.putInt(mContext.getContentResolver(),
464 Settings.Secure.THROTTLE_RESET_DAY, mPolicyResetDay);
465 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700466 if (mIface == null) {
467 mPolicyThreshold.set(0);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700468 }
469
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700470 int defaultNotificationType = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700471 R.integer.config_datause_notification_type);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700472 mPolicyNotificationsAllowedMask = Settings.Secure.getInt(mContext.getContentResolver(),
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700473 Settings.Secure.THROTTLE_NOTIFICATION_TYPE, defaultNotificationType);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700474
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700475 final int maxNtpCacheAgeSec = Settings.Secure.getInt(mContext.getContentResolver(),
476 Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC,
477 (int) (MAX_NTP_CACHE_AGE / 1000));
478 mMaxNtpCacheAge = maxNtpCacheAgeSec * 1000;
Robert Greenwaltd1055a22010-05-25 15:54:52 -0700479
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700480 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700481 Slog.d(TAG, "onPolicyChanged testing=" + testing +", period=" +
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700482 mPolicyPollPeriodSec + ", threshold=" + mPolicyThreshold.get() +
483 ", value=" + mPolicyThrottleValue.get() + ", resetDay=" + mPolicyResetDay +
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700484 ", noteType=" + mPolicyNotificationsAllowedMask + ", mMaxNtpCacheAge=" +
485 mMaxNtpCacheAge);
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700486 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700487
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700488 // force updates
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700489 mThrottleIndex.set(THROTTLE_INDEX_UNINITIALIZED);
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700490
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700491 onResetAlarm();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700492
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700493 onPollAlarm();
494
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700495 Intent broadcast = new Intent(ThrottleManager.POLICY_CHANGED_ACTION);
496 mContext.sendBroadcast(broadcast);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700497 }
498
499 private void onPollAlarm() {
500 long now = SystemClock.elapsedRealtime();
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700501 long next = now + mPolicyPollPeriodSec * 1000;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700502
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700503 // when trusted cache outdated, try refreshing
504 if (mTime.getCacheAge() > mMaxNtpCacheAge) {
505 if (mTime.forceRefresh()) {
506 if (VDBG) Slog.d(TAG, "updated trusted time, reseting alarm");
507 dispatchReset();
508 }
509 }
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700510
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700511 long incRead = 0;
512 long incWrite = 0;
513 try {
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700514 final NetworkStats stats = mNMService.getNetworkStatsSummary();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700515 final int index = stats.findIndex(
516 mIface, NetworkStats.UID_ALL, NetworkStats.TAG_NONE);
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700517
518 if (index != -1) {
Jeff Sharkeyd37948f2011-07-12 13:57:00 -0700519 final NetworkStats.Entry entry = stats.getValues(index, null);
520 incRead = entry.rxBytes - mLastRead;
521 incWrite = entry.txBytes - mLastWrite;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700522 } else {
523 // missing iface, assume stats are 0
524 Slog.w(TAG, "unable to find stats for iface " + mIface);
525 }
526
Robert Greenwalt8c7e6092010-04-14 17:31:20 -0700527 // handle iface resets - on some device the 3g iface comes and goes and gets
528 // totals reset to 0. Deal with it
529 if ((incRead < 0) || (incWrite < 0)) {
530 incRead += mLastRead;
531 incWrite += mLastWrite;
532 mLastRead = 0;
533 mLastWrite = 0;
534 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700535 } catch (RemoteException e) {
536 Slog.e(TAG, "got remoteException in onPollAlarm:" + e);
537 }
Robert Greenwalt5f996892010-04-08 16:19:24 -0700538 // don't count this data if we're roaming.
539 boolean roaming = "true".equals(
540 SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING));
541 if (!roaming) {
542 mRecorder.addData(incRead, incWrite);
543 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700544
545 long periodRx = mRecorder.getPeriodRx(0);
546 long periodTx = mRecorder.getPeriodTx(0);
547 long total = periodRx + periodTx;
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700548 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700549 Slog.d(TAG, "onPollAlarm - roaming =" + roaming +
Robert Greenwalt5f996892010-04-08 16:19:24 -0700550 ", read =" + incRead + ", written =" + incWrite + ", new total =" + total);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700551 }
552 mLastRead += incRead;
553 mLastWrite += incWrite;
554
555 checkThrottleAndPostNotification(total);
556
557 Intent broadcast = new Intent(ThrottleManager.THROTTLE_POLL_ACTION);
558 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_READ, periodRx);
559 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_WRITE, periodTx);
Robert Greenwalt05d06732010-04-19 11:10:38 -0700560 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_START, getPeriodStartTime(mIface));
561 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_END, getResetTime(mIface));
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700562 mContext.sendStickyBroadcast(broadcast);
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700563 mPollStickyBroadcast = broadcast;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700564
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700565 mAlarmManager.cancel(mPendingPollIntent);
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700566 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700567 }
568
Robert Greenwaltfee46832010-05-06 12:25:13 -0700569 private void onIfaceUp() {
570 // if we were throttled before, be sure and set it again - the iface went down
571 // (and may have disappeared all together) and these settings were lost
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700572 if (mThrottleIndex.get() == 1) {
Robert Greenwaltfee46832010-05-06 12:25:13 -0700573 try {
574 mNMService.setInterfaceThrottle(mIface, -1, -1);
575 mNMService.setInterfaceThrottle(mIface,
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700576 mPolicyThrottleValue.get(), mPolicyThrottleValue.get());
Robert Greenwaltfee46832010-05-06 12:25:13 -0700577 } catch (Exception e) {
578 Slog.e(TAG, "error setting Throttle: " + e);
579 }
580 }
581 }
582
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700583 private void checkThrottleAndPostNotification(long currentTotal) {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700584 // is throttling enabled?
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700585 long threshold = mPolicyThreshold.get();
586 if (threshold == 0) {
Robert Greenwaltcce83372010-04-23 17:35:29 -0700587 clearThrottleAndNotification();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700588 return;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700589 }
590
591 // have we spoken with an ntp server yet?
592 // this is controversial, but we'd rather err towards not throttling
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700593 if (!mTime.hasCache()) {
594 Slog.w(TAG, "missing trusted time, skipping throttle check");
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700595 return;
596 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700597
598 // check if we need to throttle
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700599 if (currentTotal > threshold) {
600 if (mThrottleIndex.get() != 1) {
601 mThrottleIndex.set(1);
602 if (DBG) Slog.d(TAG, "Threshold " + threshold + " exceeded!");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700603 try {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700604 mNMService.setInterfaceThrottle(mIface,
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700605 mPolicyThrottleValue.get(), mPolicyThrottleValue.get());
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700606 } catch (Exception e) {
607 Slog.e(TAG, "error setting Throttle: " + e);
608 }
609
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700610 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700611
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700612 postNotification(R.string.throttled_notification_title,
613 R.string.throttled_notification_message,
614 R.drawable.stat_sys_throttled,
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700615 Notification.FLAG_ONGOING_EVENT);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700616
617 Intent broadcast = new Intent(ThrottleManager.THROTTLE_ACTION);
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700618 broadcast.putExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL,
619 mPolicyThrottleValue.get());
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700620 mContext.sendStickyBroadcast(broadcast);
621
622 } // else already up!
623 } else {
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700624 clearThrottleAndNotification();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700625 if ((mPolicyNotificationsAllowedMask & NOTIFICATION_WARNING) != 0) {
626 // check if we should warn about throttle
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700627 // pretend we only have 1/2 the time remaining that we actually do
628 // if our burn rate in the period so far would have us exceed the limit
629 // in that 1/2 window, warn the user.
630 // this gets more generous in the early to middle period and converges back
631 // to the limit as we move toward the period end.
632
633 // adding another factor - it must be greater than the total cap/4
634 // else we may get false alarms very early in the period.. in the first
635 // tenth of a percent of the period if we used more than a tenth of a percent
636 // of the cap we'd get a warning and that's not desired.
637 long start = mRecorder.getPeriodStart();
638 long end = mRecorder.getPeriodEnd();
639 long periodLength = end - start;
640 long now = System.currentTimeMillis();
641 long timeUsed = now - start;
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700642 long warningThreshold = 2*threshold*timeUsed/(timeUsed+periodLength);
643 if ((currentTotal > warningThreshold) && (currentTotal > threshold/4)) {
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700644 if (mWarningNotificationSent == false) {
645 mWarningNotificationSent = true;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700646 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
647 postNotification(R.string.throttle_warning_notification_title,
648 R.string.throttle_warning_notification_message,
649 R.drawable.stat_sys_throttled,
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700650 0);
651 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700652 } else {
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700653 if (mWarningNotificationSent == true) {
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700654 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700655 mWarningNotificationSent =false;
656 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700657 }
658 }
659 }
660 }
661
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700662 private void postNotification(int titleInt, int messageInt, int icon, int flags) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700663 Intent intent = new Intent();
664 // TODO - fix up intent
Robert Greenwalt2a7b7302010-04-12 14:56:31 -0700665 intent.setClassName("com.android.phone", "com.android.phone.DataUsage");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700666 intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
667
668 PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
669
670 Resources r = Resources.getSystem();
671 CharSequence title = r.getText(titleInt);
672 CharSequence message = r.getText(messageInt);
673 if (mThrottlingNotification == null) {
674 mThrottlingNotification = new Notification();
675 mThrottlingNotification.when = 0;
676 // TODO - fixup icon
677 mThrottlingNotification.icon = icon;
678 mThrottlingNotification.defaults &= ~Notification.DEFAULT_SOUND;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700679 }
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700680 mThrottlingNotification.flags = flags;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700681 mThrottlingNotification.tickerText = title;
682 mThrottlingNotification.setLatestEventInfo(mContext, title, message, pi);
683
684 mNotificationManager.notify(mThrottlingNotification.icon, mThrottlingNotification);
685 }
686
687
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700688 private void clearThrottleAndNotification() {
689 if (mThrottleIndex.get() != THROTTLE_INDEX_UNTHROTTLED) {
690 mThrottleIndex.set(THROTTLE_INDEX_UNTHROTTLED);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700691 try {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700692 mNMService.setInterfaceThrottle(mIface, -1, -1);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700693 } catch (Exception e) {
694 Slog.e(TAG, "error clearing Throttle: " + e);
695 }
696 Intent broadcast = new Intent(ThrottleManager.THROTTLE_ACTION);
697 broadcast.putExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL, -1);
698 mContext.sendStickyBroadcast(broadcast);
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700699 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
700 mWarningNotificationSent = false;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700701 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700702 }
703
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700704 private Calendar calculatePeriodEnd(long now) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700705 Calendar end = GregorianCalendar.getInstance();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700706 end.setTimeInMillis(now);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700707 int day = end.get(Calendar.DAY_OF_MONTH);
708 end.set(Calendar.DAY_OF_MONTH, mPolicyResetDay);
709 end.set(Calendar.HOUR_OF_DAY, 0);
710 end.set(Calendar.MINUTE, 0);
Robert Greenwalt8c7e6092010-04-14 17:31:20 -0700711 end.set(Calendar.SECOND, 0);
712 end.set(Calendar.MILLISECOND, 0);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700713 if (day >= mPolicyResetDay) {
714 int month = end.get(Calendar.MONTH);
715 if (month == Calendar.DECEMBER) {
716 end.set(Calendar.YEAR, end.get(Calendar.YEAR) + 1);
717 month = Calendar.JANUARY - 1;
718 }
719 end.set(Calendar.MONTH, month + 1);
720 }
721
722 // TODO - remove!
723 if (SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true")) {
724 end = GregorianCalendar.getInstance();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700725 end.setTimeInMillis(now);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700726 end.add(Calendar.SECOND, TESTING_RESET_PERIOD_SEC);
727 }
728 return end;
729 }
730 private Calendar calculatePeriodStart(Calendar end) {
731 Calendar start = (Calendar)end.clone();
732 int month = end.get(Calendar.MONTH);
733 if (end.get(Calendar.MONTH) == Calendar.JANUARY) {
734 month = Calendar.DECEMBER + 1;
735 start.set(Calendar.YEAR, start.get(Calendar.YEAR) - 1);
736 }
737 start.set(Calendar.MONTH, month - 1);
738
739 // TODO - remove!!
740 if (SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true")) {
741 start = (Calendar)end.clone();
742 start.add(Calendar.SECOND, -TESTING_RESET_PERIOD_SEC);
743 }
744 return start;
745 }
746
747 private void onResetAlarm() {
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700748 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700749 Slog.d(TAG, "onResetAlarm - last period had " + mRecorder.getPeriodRx(0) +
750 " bytes read and " + mRecorder.getPeriodTx(0) + " written");
751 }
752
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700753 // when trusted cache outdated, try refreshing
754 if (mTime.getCacheAge() > mMaxNtpCacheAge) {
755 mTime.forceRefresh();
756 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700757
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700758 // as long as we have a trusted time cache, we always reset alarms,
759 // even if the refresh above failed.
760 if (mTime.hasCache()) {
761 final long now = mTime.currentTimeMillis();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700762 Calendar end = calculatePeriodEnd(now);
763 Calendar start = calculatePeriodStart(end);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700764
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700765 if (mRecorder.setNextPeriod(start, end)) {
Robert Greenwalt05d06732010-04-19 11:10:38 -0700766 onPollAlarm();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700767 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700768
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700769 mAlarmManager.cancel(mPendingResetIntent);
770 long offset = end.getTimeInMillis() - now;
771 // use Elapsed realtime so clock changes don't fool us.
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700772 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME,
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700773 SystemClock.elapsedRealtime() + offset,
774 mPendingResetIntent);
775 } else {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700776 if (VDBG) Slog.d(TAG, "no trusted time, not resetting period");
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700777 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700778 }
779 }
780
781 // records bytecount data for a given time and accumulates it into larger time windows
782 // for logging and other purposes
783 //
784 // since time can be changed (user or network action) we will have to track the time of the
785 // last recording and deal with it.
786 private static class DataRecorder {
787 long[] mPeriodRxData;
788 long[] mPeriodTxData;
789 int mCurrentPeriod;
790 int mPeriodCount;
791
792 Calendar mPeriodStart;
793 Calendar mPeriodEnd;
794
795 ThrottleService mParent;
796 Context mContext;
Robert Greenwalte6e98822010-04-15 08:27:14 -0700797 String mImsi = null;
798
799 TelephonyManager mTelephonyManager;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700800
801 DataRecorder(Context context, ThrottleService parent) {
802 mContext = context;
803 mParent = parent;
804
Robert Greenwalte6e98822010-04-15 08:27:14 -0700805 mTelephonyManager = (TelephonyManager)mContext.getSystemService(
806 Context.TELEPHONY_SERVICE);
807
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700808 synchronized (mParent) {
809 mPeriodCount = 6;
810 mPeriodRxData = new long[mPeriodCount];
811 mPeriodTxData = new long[mPeriodCount];
812
813 mPeriodStart = Calendar.getInstance();
814 mPeriodEnd = Calendar.getInstance();
815
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700816 retrieve();
817 }
818 }
819
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700820 boolean setNextPeriod(Calendar start, Calendar end) {
Robert Greenwalte6e98822010-04-15 08:27:14 -0700821 // TODO - how would we deal with a dual-IMSI device?
822 checkForSubscriberId();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700823 boolean startNewPeriod = true;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700824
Robert Greenwalt27fba672010-04-26 12:29:14 -0700825 if (start.equals(mPeriodStart) && end.equals(mPeriodEnd)) {
826 // same endpoints - keep collecting
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700827 if (VDBG) {
Robert Greenwalt27fba672010-04-26 12:29:14 -0700828 Slog.d(TAG, "same period (" + start.getTimeInMillis() + "," +
829 end.getTimeInMillis() +") - ammending data");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700830 }
Robert Greenwalt27fba672010-04-26 12:29:14 -0700831 startNewPeriod = false;
832 } else {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700833 if (VDBG) {
Robert Greenwalt27fba672010-04-26 12:29:14 -0700834 if(start.equals(mPeriodEnd) || start.after(mPeriodEnd)) {
835 Slog.d(TAG, "next period (" + start.getTimeInMillis() + "," +
836 end.getTimeInMillis() + ") - old end was " +
837 mPeriodEnd.getTimeInMillis() + ", following");
838 } else {
839 Slog.d(TAG, "new period (" + start.getTimeInMillis() + "," +
840 end.getTimeInMillis() + ") replacing old (" +
841 mPeriodStart.getTimeInMillis() + "," +
842 mPeriodEnd.getTimeInMillis() + ")");
843 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700844 }
845 synchronized (mParent) {
846 ++mCurrentPeriod;
847 if (mCurrentPeriod >= mPeriodCount) mCurrentPeriod = 0;
848 mPeriodRxData[mCurrentPeriod] = 0;
849 mPeriodTxData[mCurrentPeriod] = 0;
850 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700851 }
852 setPeriodStart(start);
853 setPeriodEnd(end);
854 record();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700855 return startNewPeriod;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700856 }
857
858 public long getPeriodEnd() {
859 synchronized (mParent) {
860 return mPeriodEnd.getTimeInMillis();
861 }
862 }
863
864 private void setPeriodEnd(Calendar end) {
865 synchronized (mParent) {
866 mPeriodEnd = end;
867 }
868 }
869
870 public long getPeriodStart() {
871 synchronized (mParent) {
872 return mPeriodStart.getTimeInMillis();
873 }
874 }
875
876 private void setPeriodStart(Calendar start) {
877 synchronized (mParent) {
878 mPeriodStart = start;
879 }
880 }
881
882 public int getPeriodCount() {
883 synchronized (mParent) {
884 return mPeriodCount;
885 }
886 }
887
888 private void zeroData(int field) {
889 synchronized (mParent) {
890 for(int period = 0; period<mPeriodCount; period++) {
891 mPeriodRxData[period] = 0;
892 mPeriodTxData[period] = 0;
893 }
894 mCurrentPeriod = 0;
895 }
896
897 }
898
899 // if time moves backward accumulate all read/write that's lost into the now
900 // otherwise time moved forward.
901 void addData(long bytesRead, long bytesWritten) {
Robert Greenwalte6e98822010-04-15 08:27:14 -0700902 checkForSubscriberId();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700903
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700904 synchronized (mParent) {
905 mPeriodRxData[mCurrentPeriod] += bytesRead;
906 mPeriodTxData[mCurrentPeriod] += bytesWritten;
907 }
908 record();
909 }
910
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700911 private File getDataFile() {
912 File dataDir = Environment.getDataDirectory();
913 File throttleDir = new File(dataDir, "system/throttle");
914 throttleDir.mkdirs();
Robert Greenwalte6e98822010-04-15 08:27:14 -0700915 String mImsi = mTelephonyManager.getSubscriberId();
916 File dataFile;
917 if (mImsi == null) {
918 dataFile = useMRUFile(throttleDir);
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700919 if (VDBG) Slog.v(TAG, "imsi not available yet, using " + dataFile);
Robert Greenwalte6e98822010-04-15 08:27:14 -0700920 } else {
921 String imsiHash = Integer.toString(mImsi.hashCode());
922 dataFile = new File(throttleDir, imsiHash);
923 }
924 // touch the file so it's not LRU
925 dataFile.setLastModified(System.currentTimeMillis());
926 checkAndDeleteLRUDataFile(throttleDir);
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700927 return dataFile;
928 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700929
Robert Greenwalte6e98822010-04-15 08:27:14 -0700930 // TODO - get broadcast (TelephonyIntents.ACTION_SIM_STATE_CHANGED) instead of polling
931 private void checkForSubscriberId() {
932 if (mImsi != null) return;
933
934 mImsi = mTelephonyManager.getSubscriberId();
935 if (mImsi == null) return;
936
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700937 if (VDBG) Slog.d(TAG, "finally have imsi - retreiving data");
Robert Greenwalte6e98822010-04-15 08:27:14 -0700938 retrieve();
939 }
940
941 private final static int MAX_SIMS_SUPPORTED = 3;
942
943 private void checkAndDeleteLRUDataFile(File dir) {
944 File[] files = dir.listFiles();
945
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700946 if (files == null || files.length <= MAX_SIMS_SUPPORTED) return;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700947 if (DBG) Slog.d(TAG, "Too many data files");
Robert Greenwalte6e98822010-04-15 08:27:14 -0700948 do {
949 File oldest = null;
950 for (File f : files) {
951 if ((oldest == null) || (oldest.lastModified() > f.lastModified())) {
952 oldest = f;
953 }
954 }
955 if (oldest == null) return;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700956 if (DBG) Slog.d(TAG, " deleting " + oldest);
Robert Greenwalte6e98822010-04-15 08:27:14 -0700957 oldest.delete();
958 files = dir.listFiles();
959 } while (files.length > MAX_SIMS_SUPPORTED);
960 }
961
962 private File useMRUFile(File dir) {
963 File newest = null;
964 File[] files = dir.listFiles();
965
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700966 if (files != null) {
967 for (File f : files) {
968 if ((newest == null) || (newest.lastModified() < f.lastModified())) {
969 newest = f;
970 }
Robert Greenwalte6e98822010-04-15 08:27:14 -0700971 }
972 }
973 if (newest == null) {
974 newest = new File(dir, "temp");
975 }
976 return newest;
977 }
978
979
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700980 private static final int DATA_FILE_VERSION = 1;
981
982 private void record() {
983 // 1 int version
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700984 // 1 int mPeriodCount
985 // 13*6 long[PERIOD_COUNT] mPeriodRxData
986 // 13*6 long[PERIOD_COUNT] mPeriodTxData
987 // 1 int mCurrentPeriod
988 // 13 long periodStartMS
989 // 13 long periodEndMS
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700990 // 200 chars max
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700991 StringBuilder builder = new StringBuilder();
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700992 builder.append(DATA_FILE_VERSION);
993 builder.append(":");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700994 builder.append(mPeriodCount);
995 builder.append(":");
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700996 for(int i = 0; i < mPeriodCount; i++) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700997 builder.append(mPeriodRxData[i]);
998 builder.append(":");
999 }
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001000 for(int i = 0; i < mPeriodCount; i++) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001001 builder.append(mPeriodTxData[i]);
1002 builder.append(":");
1003 }
1004 builder.append(mCurrentPeriod);
1005 builder.append(":");
1006 builder.append(mPeriodStart.getTimeInMillis());
1007 builder.append(":");
1008 builder.append(mPeriodEnd.getTimeInMillis());
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001009
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001010 BufferedWriter out = null;
1011 try {
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001012 out = new BufferedWriter(new FileWriter(getDataFile()), 256);
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001013 out.write(builder.toString());
1014 } catch (IOException e) {
1015 Slog.e(TAG, "Error writing data file");
1016 return;
1017 } finally {
1018 if (out != null) {
1019 try {
1020 out.close();
1021 } catch (Exception e) {}
1022 }
1023 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001024 }
1025
1026 private void retrieve() {
Robert Greenwalt05d06732010-04-19 11:10:38 -07001027 // clean out any old data first. If we fail to read we don't want old stuff
1028 zeroData(0);
1029
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001030 File f = getDataFile();
1031 byte[] buffer;
1032 FileInputStream s = null;
1033 try {
1034 buffer = new byte[(int)f.length()];
1035 s = new FileInputStream(f);
1036 s.read(buffer);
1037 } catch (IOException e) {
1038 Slog.e(TAG, "Error reading data file");
1039 return;
1040 } finally {
1041 if (s != null) {
1042 try {
1043 s.close();
1044 } catch (Exception e) {}
1045 }
1046 }
1047 String data = new String(buffer);
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001048 if (data == null || data.length() == 0) {
1049 if (DBG) Slog.d(TAG, "data file empty");
1050 return;
1051 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001052 String[] parsed = data.split(":");
1053 int parsedUsed = 0;
1054 if (parsed.length < 6) {
1055 Slog.e(TAG, "reading data file with insufficient length - ignoring");
1056 return;
1057 }
1058
Robert Greenwalt9e3983f2010-05-11 07:06:13 -07001059 int periodCount;
1060 long[] periodRxData;
1061 long[] periodTxData;
1062 int currentPeriod;
1063 Calendar periodStart;
1064 Calendar periodEnd;
1065 try {
1066 if (Integer.parseInt(parsed[parsedUsed++]) != DATA_FILE_VERSION) {
1067 Slog.e(TAG, "reading data file with bad version - ignoring");
1068 return;
1069 }
1070
1071 periodCount = Integer.parseInt(parsed[parsedUsed++]);
1072 if (parsed.length != 5 + (2 * periodCount)) {
1073 Slog.e(TAG, "reading data file with bad length (" + parsed.length +
1074 " != " + (5 + (2 * periodCount)) + ") - ignoring");
1075 return;
1076 }
1077 periodRxData = new long[periodCount];
1078 for (int i = 0; i < periodCount; i++) {
1079 periodRxData[i] = Long.parseLong(parsed[parsedUsed++]);
1080 }
1081 periodTxData = new long[periodCount];
1082 for (int i = 0; i < periodCount; i++) {
1083 periodTxData[i] = Long.parseLong(parsed[parsedUsed++]);
1084 }
1085
1086 currentPeriod = Integer.parseInt(parsed[parsedUsed++]);
1087
1088 periodStart = new GregorianCalendar();
1089 periodStart.setTimeInMillis(Long.parseLong(parsed[parsedUsed++]));
1090 periodEnd = new GregorianCalendar();
1091 periodEnd.setTimeInMillis(Long.parseLong(parsed[parsedUsed++]));
1092 } catch (Exception e) {
1093 Slog.e(TAG, "Error parsing data file - ignoring");
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001094 return;
1095 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001096 synchronized (mParent) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001097 mPeriodCount = periodCount;
1098 mPeriodRxData = periodRxData;
1099 mPeriodTxData = periodTxData;
Robert Greenwalt9e3983f2010-05-11 07:06:13 -07001100 mCurrentPeriod = currentPeriod;
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001101 mPeriodStart = periodStart;
1102 mPeriodEnd = periodEnd;
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001103 }
1104 }
1105
1106 long getPeriodRx(int which) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001107 synchronized (mParent) {
1108 if (which > mPeriodCount) return 0;
1109 which = mCurrentPeriod - which;
1110 if (which < 0) which += mPeriodCount;
1111 return mPeriodRxData[which];
1112 }
1113 }
1114 long getPeriodTx(int which) {
1115 synchronized (mParent) {
1116 if (which > mPeriodCount) return 0;
1117 which = mCurrentPeriod - which;
1118 if (which < 0) which += mPeriodCount;
1119 return mPeriodTxData[which];
1120 }
1121 }
1122 }
1123
1124 @Override
1125 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1126 if (mContext.checkCallingOrSelfPermission(
1127 android.Manifest.permission.DUMP)
1128 != PackageManager.PERMISSION_GRANTED) {
1129 pw.println("Permission Denial: can't dump ThrottleService " +
1130 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1131 Binder.getCallingUid());
1132 return;
1133 }
1134 pw.println();
1135
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001136 pw.println("The threshold is " + mPolicyThreshold.get() +
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001137 ", after which you experince throttling to " +
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001138 mPolicyThrottleValue.get() + "kbps");
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001139 pw.println("Current period is " +
1140 (mRecorder.getPeriodEnd() - mRecorder.getPeriodStart())/1000 + " seconds long " +
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001141 "and ends in " + (getResetTime(mIface) - System.currentTimeMillis()) / 1000 +
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001142 " seconds.");
1143 pw.println("Polling every " + mPolicyPollPeriodSec + " seconds");
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001144 pw.println("Current Throttle Index is " + mThrottleIndex.get());
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -07001145 pw.println("mMaxNtpCacheAge=" + mMaxNtpCacheAge);
Robert Greenwalt8c7e6092010-04-14 17:31:20 -07001146
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001147 for (int i = 0; i < mRecorder.getPeriodCount(); i++) {
1148 pw.println(" Period[" + i + "] - read:" + mRecorder.getPeriodRx(i) + ", written:" +
1149 mRecorder.getPeriodTx(i));
1150 }
1151 }
1152}