blob: b8890aa2aa8e37e9fd2c980f7e222c0862180782 [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) {}
197 }
198
199
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700200 private static class SettingsObserver extends ContentObserver {
201 private int mMsg;
202 private Handler mHandler;
203 SettingsObserver(Handler handler, int msg) {
204 super(handler);
205 mHandler = handler;
206 mMsg = msg;
207 }
208
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700209 void register(Context context) {
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700210 ContentResolver resolver = context.getContentResolver();
211 resolver.registerContentObserver(Settings.Secure.getUriFor(
212 Settings.Secure.THROTTLE_POLLING_SEC), false, this);
213 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700214 Settings.Secure.THROTTLE_THRESHOLD_BYTES), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700215 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700216 Settings.Secure.THROTTLE_VALUE_KBITSPS), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700217 resolver.registerContentObserver(Settings.Secure.getUriFor(
218 Settings.Secure.THROTTLE_RESET_DAY), false, this);
219 resolver.registerContentObserver(Settings.Secure.getUriFor(
220 Settings.Secure.THROTTLE_NOTIFICATION_TYPE), false, this);
221 resolver.registerContentObserver(Settings.Secure.getUriFor(
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700222 Settings.Secure.THROTTLE_HELP_URI), false, this);
Robert Greenwaltd1055a22010-05-25 15:54:52 -0700223 resolver.registerContentObserver(Settings.Secure.getUriFor(
224 Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC), false, this);
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700225 }
226
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700227 void unregister(Context context) {
228 final ContentResolver resolver = context.getContentResolver();
229 resolver.unregisterContentObserver(this);
230 }
231
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700232 @Override
233 public void onChange(boolean selfChange) {
234 mHandler.obtainMessage(mMsg).sendToTarget();
235 }
236 }
237
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700238 private void enforceAccessPermission() {
239 mContext.enforceCallingOrSelfPermission(
240 android.Manifest.permission.ACCESS_NETWORK_STATE,
241 "ThrottleService");
242 }
243
Robert Greenwalt05d06732010-04-19 11:10:38 -0700244 private long ntpToWallTime(long ntpTime) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700245 // get time quickly without worrying about trusted state
246 long bestNow = mTime.hasCache() ? mTime.currentTimeMillis()
247 : System.currentTimeMillis();
Robert Greenwalt05d06732010-04-19 11:10:38 -0700248 long localNow = System.currentTimeMillis();
249 return localNow + (ntpTime - bestNow);
250 }
251
Irfan Sheriffcf282362010-04-16 16:53:20 -0700252 // TODO - fetch for the iface
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700253 // return time in the local, system wall time, correcting for the use of ntp
Robert Greenwalt05d06732010-04-19 11:10:38 -0700254
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700255 public long getResetTime(String iface) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700256 enforceAccessPermission();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700257 long resetTime = 0;
Irfan Sheriffcf282362010-04-16 16:53:20 -0700258 if (mRecorder != null) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700259 resetTime = mRecorder.getPeriodEnd();
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700260 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700261 resetTime = ntpToWallTime(resetTime);
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700262 return resetTime;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700263 }
Irfan Sheriffcf282362010-04-16 16:53:20 -0700264
265 // TODO - fetch for the iface
Robert Greenwalt05d06732010-04-19 11:10:38 -0700266 // return time in the local, system wall time, correcting for the use of ntp
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700267 public long getPeriodStartTime(String iface) {
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700268 long startTime = 0;
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700269 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700270 if (mRecorder != null) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700271 startTime = mRecorder.getPeriodStart();
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700272 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700273 startTime = ntpToWallTime(startTime);
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700274 return startTime;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700275 }
276 //TODO - a better name? getCliffByteCountThreshold?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700277 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700278 public long getCliffThreshold(String iface, int cliff) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700279 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700280 if (cliff == 1) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700281 return mPolicyThreshold.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700282 }
283 return 0;
284 }
285 // TODO - a better name? getThrottleRate?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700286 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700287 public int getCliffLevel(String iface, int cliff) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700288 enforceAccessPermission();
Irfan Sheriffcf282362010-04-16 16:53:20 -0700289 if (cliff == 1) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700290 return mPolicyThrottleValue.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700291 }
292 return 0;
293 }
294
Irfan Sheriffc9b68512010-04-08 14:12:33 -0700295 public String getHelpUri() {
296 enforceAccessPermission();
297 return Settings.Secure.getString(mContext.getContentResolver(),
298 Settings.Secure.THROTTLE_HELP_URI);
299 }
300
Irfan Sheriffcf282362010-04-16 16:53:20 -0700301 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700302 public long getByteCount(String iface, int dir, int period, int ago) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700303 enforceAccessPermission();
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700304 if ((period == ThrottleManager.PERIOD_CYCLE) && (mRecorder != null)) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700305 if (dir == ThrottleManager.DIRECTION_TX) return mRecorder.getPeriodTx(ago);
306 if (dir == ThrottleManager.DIRECTION_RX) return mRecorder.getPeriodRx(ago);
307 }
308 return 0;
309 }
310
311 // TODO - a better name - getCurrentThrottleRate?
Irfan Sheriffcf282362010-04-16 16:53:20 -0700312 // TODO - fetch for the iface
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700313 public int getThrottle(String iface) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700314 enforceAccessPermission();
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700315 if (mThrottleIndex.get() == 1) {
316 return mPolicyThrottleValue.get();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700317 }
318 return 0;
319 }
320
321 void systemReady() {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700322 if (VDBG) Slog.v(TAG, "systemReady");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700323 mContext.registerReceiver(
324 new BroadcastReceiver() {
325 @Override
326 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700327 dispatchPoll();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700328 }
329 }, new IntentFilter(ACTION_POLL));
330
331 mContext.registerReceiver(
332 new BroadcastReceiver() {
333 @Override
334 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700335 dispatchReset();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700336 }
337 }, new IntentFilter(ACTION_RESET));
338
Robert Greenwaltc76c15e2010-06-16 14:42:16 -0700339 // use a new thread as we don't want to stall the system for file writes
340 mThread = new HandlerThread(TAG);
341 mThread.start();
342 mHandler = new MyHandler(mThread.getLooper());
343 mHandler.obtainMessage(EVENT_REBOOT_RECOVERY).sendToTarget();
344
345 mInterfaceObserver = new InterfaceObserver(mHandler, EVENT_IFACE_UP, mIface);
346 try {
347 mNMService.registerObserver(mInterfaceObserver);
348 } catch (RemoteException e) {
349 Slog.e(TAG, "Could not register InterfaceObserver " + e);
350 }
351
352 mSettingsObserver = new SettingsObserver(mHandler, EVENT_POLICY_CHANGED);
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700353 mSettingsObserver.register(mContext);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700354 }
355
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700356 void shutdown() {
357 // TODO: eventually connect with ShutdownThread to persist stats during
358 // graceful shutdown.
359
360 if (mThread != null) {
361 mThread.quit();
362 }
363
364 if (mSettingsObserver != null) {
365 mSettingsObserver.unregister(mContext);
366 }
367
368 if (mPollStickyBroadcast != null) {
369 mContext.removeStickyBroadcast(mPollStickyBroadcast);
370 }
371 }
372
373 void dispatchPoll() {
374 mHandler.obtainMessage(EVENT_POLL_ALARM).sendToTarget();
375 }
376
377 void dispatchReset() {
378 mHandler.obtainMessage(EVENT_RESET_ALARM).sendToTarget();
379 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700380
381 private static final int EVENT_REBOOT_RECOVERY = 0;
382 private static final int EVENT_POLICY_CHANGED = 1;
383 private static final int EVENT_POLL_ALARM = 2;
384 private static final int EVENT_RESET_ALARM = 3;
Robert Greenwaltfee46832010-05-06 12:25:13 -0700385 private static final int EVENT_IFACE_UP = 4;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700386 private class MyHandler extends Handler {
387 public MyHandler(Looper l) {
388 super(l);
389 }
390
391 @Override
392 public void handleMessage(Message msg) {
393 switch (msg.what) {
394 case EVENT_REBOOT_RECOVERY:
395 onRebootRecovery();
396 break;
397 case EVENT_POLICY_CHANGED:
398 onPolicyChanged();
399 break;
400 case EVENT_POLL_ALARM:
401 onPollAlarm();
402 break;
403 case EVENT_RESET_ALARM:
404 onResetAlarm();
Robert Greenwaltfee46832010-05-06 12:25:13 -0700405 break;
406 case EVENT_IFACE_UP:
407 onIfaceUp();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700408 }
409 }
410
411 private void onRebootRecovery() {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700412 if (VDBG) Slog.v(TAG, "onRebootRecovery");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700413 // check for sim change TODO
414 // reregister for notification of policy change
415
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700416 mThrottleIndex.set(THROTTLE_INDEX_UNINITIALIZED);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700417
418 mRecorder = new DataRecorder(mContext, ThrottleService.this);
419
420 // get policy
421 mHandler.obtainMessage(EVENT_POLICY_CHANGED).sendToTarget();
Robert Greenwaltfb9896b2010-04-22 15:39:38 -0700422
423 // if we poll now we won't have network connectivity or even imsi access
424 // queue up a poll to happen in a little while - after ntp and imsi are avail
425 // TODO - make this callback based (ie, listen for notificaitons)
426 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_POLL_ALARM),
427 INITIAL_POLL_DELAY_SEC * 1000);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700428 }
429
430 // check for new policy info (threshold limit/value/etc)
431 private void onPolicyChanged() {
432 boolean testing = SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true");
433
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700434 int pollingPeriod = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700435 R.integer.config_datause_polling_period_sec);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700436 mPolicyPollPeriodSec = Settings.Secure.getInt(mContext.getContentResolver(),
437 Settings.Secure.THROTTLE_POLLING_SEC, pollingPeriod);
438
439 // TODO - remove testing stuff?
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700440 long defaultThreshold = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700441 R.integer.config_datause_threshold_bytes);
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700442 int defaultValue = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700443 R.integer.config_datause_throttle_kbitsps);
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700444 long threshold = Settings.Secure.getLong(mContext.getContentResolver(),
445 Settings.Secure.THROTTLE_THRESHOLD_BYTES, defaultThreshold);
446 int value = Settings.Secure.getInt(mContext.getContentResolver(),
447 Settings.Secure.THROTTLE_VALUE_KBITSPS, defaultValue);
448
449 mPolicyThreshold.set(threshold);
450 mPolicyThrottleValue.set(value);
451 if (testing) {
452 mPolicyPollPeriodSec = TESTING_POLLING_PERIOD_SEC;
453 mPolicyThreshold.set(TESTING_THRESHOLD);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700454 }
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700455
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700456 mPolicyResetDay = Settings.Secure.getInt(mContext.getContentResolver(),
457 Settings.Secure.THROTTLE_RESET_DAY, -1);
458 if (mPolicyResetDay == -1 ||
459 ((mPolicyResetDay < 1) || (mPolicyResetDay > 28))) {
460 Random g = new Random();
461 mPolicyResetDay = 1 + g.nextInt(28); // 1-28
462 Settings.Secure.putInt(mContext.getContentResolver(),
463 Settings.Secure.THROTTLE_RESET_DAY, mPolicyResetDay);
464 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700465 if (mIface == null) {
466 mPolicyThreshold.set(0);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700467 }
468
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700469 int defaultNotificationType = mContext.getResources().getInteger(
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700470 R.integer.config_datause_notification_type);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700471 mPolicyNotificationsAllowedMask = Settings.Secure.getInt(mContext.getContentResolver(),
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700472 Settings.Secure.THROTTLE_NOTIFICATION_TYPE, defaultNotificationType);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700473
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700474 final int maxNtpCacheAgeSec = Settings.Secure.getInt(mContext.getContentResolver(),
475 Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC,
476 (int) (MAX_NTP_CACHE_AGE / 1000));
477 mMaxNtpCacheAge = maxNtpCacheAgeSec * 1000;
Robert Greenwaltd1055a22010-05-25 15:54:52 -0700478
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700479 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700480 Slog.d(TAG, "onPolicyChanged testing=" + testing +", period=" +
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700481 mPolicyPollPeriodSec + ", threshold=" + mPolicyThreshold.get() +
482 ", value=" + mPolicyThrottleValue.get() + ", resetDay=" + mPolicyResetDay +
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700483 ", noteType=" + mPolicyNotificationsAllowedMask + ", mMaxNtpCacheAge=" +
484 mMaxNtpCacheAge);
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700485 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700486
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700487 // force updates
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700488 mThrottleIndex.set(THROTTLE_INDEX_UNINITIALIZED);
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700489
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700490 onResetAlarm();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700491
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700492 onPollAlarm();
493
Robert Greenwalt81aa0971d2010-04-09 09:36:09 -0700494 Intent broadcast = new Intent(ThrottleManager.POLICY_CHANGED_ACTION);
495 mContext.sendBroadcast(broadcast);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700496 }
497
498 private void onPollAlarm() {
499 long now = SystemClock.elapsedRealtime();
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700500 long next = now + mPolicyPollPeriodSec * 1000;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700501
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700502 // when trusted cache outdated, try refreshing
503 if (mTime.getCacheAge() > mMaxNtpCacheAge) {
504 if (mTime.forceRefresh()) {
505 if (VDBG) Slog.d(TAG, "updated trusted time, reseting alarm");
506 dispatchReset();
507 }
508 }
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700509
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700510 long incRead = 0;
511 long incWrite = 0;
512 try {
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700513 final NetworkStats stats = mNMService.getNetworkStatsSummary();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700514 final int index = stats.findIndex(
515 mIface, NetworkStats.UID_ALL, NetworkStats.TAG_NONE);
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700516
517 if (index != -1) {
Jeff Sharkeyd37948f2011-07-12 13:57:00 -0700518 final NetworkStats.Entry entry = stats.getValues(index, null);
519 incRead = entry.rxBytes - mLastRead;
520 incWrite = entry.txBytes - mLastWrite;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700521 } else {
522 // missing iface, assume stats are 0
523 Slog.w(TAG, "unable to find stats for iface " + mIface);
524 }
525
Robert Greenwalt8c7e6092010-04-14 17:31:20 -0700526 // handle iface resets - on some device the 3g iface comes and goes and gets
527 // totals reset to 0. Deal with it
528 if ((incRead < 0) || (incWrite < 0)) {
529 incRead += mLastRead;
530 incWrite += mLastWrite;
531 mLastRead = 0;
532 mLastWrite = 0;
533 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700534 } catch (RemoteException e) {
535 Slog.e(TAG, "got remoteException in onPollAlarm:" + e);
536 }
Robert Greenwalt5f996892010-04-08 16:19:24 -0700537 // don't count this data if we're roaming.
538 boolean roaming = "true".equals(
539 SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING));
540 if (!roaming) {
541 mRecorder.addData(incRead, incWrite);
542 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700543
544 long periodRx = mRecorder.getPeriodRx(0);
545 long periodTx = mRecorder.getPeriodTx(0);
546 long total = periodRx + periodTx;
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700547 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700548 Slog.d(TAG, "onPollAlarm - roaming =" + roaming +
Robert Greenwalt5f996892010-04-08 16:19:24 -0700549 ", read =" + incRead + ", written =" + incWrite + ", new total =" + total);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700550 }
551 mLastRead += incRead;
552 mLastWrite += incWrite;
553
554 checkThrottleAndPostNotification(total);
555
556 Intent broadcast = new Intent(ThrottleManager.THROTTLE_POLL_ACTION);
557 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_READ, periodRx);
558 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_WRITE, periodTx);
Robert Greenwalt05d06732010-04-19 11:10:38 -0700559 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_START, getPeriodStartTime(mIface));
560 broadcast.putExtra(ThrottleManager.EXTRA_CYCLE_END, getResetTime(mIface));
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700561 mContext.sendStickyBroadcast(broadcast);
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700562 mPollStickyBroadcast = broadcast;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700563
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700564 mAlarmManager.cancel(mPendingPollIntent);
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700565 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700566 }
567
Robert Greenwaltfee46832010-05-06 12:25:13 -0700568 private void onIfaceUp() {
569 // if we were throttled before, be sure and set it again - the iface went down
570 // (and may have disappeared all together) and these settings were lost
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700571 if (mThrottleIndex.get() == 1) {
Robert Greenwaltfee46832010-05-06 12:25:13 -0700572 try {
573 mNMService.setInterfaceThrottle(mIface, -1, -1);
574 mNMService.setInterfaceThrottle(mIface,
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700575 mPolicyThrottleValue.get(), mPolicyThrottleValue.get());
Robert Greenwaltfee46832010-05-06 12:25:13 -0700576 } catch (Exception e) {
577 Slog.e(TAG, "error setting Throttle: " + e);
578 }
579 }
580 }
581
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700582 private void checkThrottleAndPostNotification(long currentTotal) {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700583 // is throttling enabled?
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700584 long threshold = mPolicyThreshold.get();
585 if (threshold == 0) {
Robert Greenwaltcce83372010-04-23 17:35:29 -0700586 clearThrottleAndNotification();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700587 return;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700588 }
589
590 // have we spoken with an ntp server yet?
591 // this is controversial, but we'd rather err towards not throttling
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700592 if (!mTime.hasCache()) {
593 Slog.w(TAG, "missing trusted time, skipping throttle check");
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700594 return;
595 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700596
597 // check if we need to throttle
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700598 if (currentTotal > threshold) {
599 if (mThrottleIndex.get() != 1) {
600 mThrottleIndex.set(1);
601 if (DBG) Slog.d(TAG, "Threshold " + threshold + " exceeded!");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700602 try {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700603 mNMService.setInterfaceThrottle(mIface,
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700604 mPolicyThrottleValue.get(), mPolicyThrottleValue.get());
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700605 } catch (Exception e) {
606 Slog.e(TAG, "error setting Throttle: " + e);
607 }
608
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700609 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700610
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700611 postNotification(R.string.throttled_notification_title,
612 R.string.throttled_notification_message,
613 R.drawable.stat_sys_throttled,
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700614 Notification.FLAG_ONGOING_EVENT);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700615
616 Intent broadcast = new Intent(ThrottleManager.THROTTLE_ACTION);
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700617 broadcast.putExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL,
618 mPolicyThrottleValue.get());
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700619 mContext.sendStickyBroadcast(broadcast);
620
621 } // else already up!
622 } else {
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700623 clearThrottleAndNotification();
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700624 if ((mPolicyNotificationsAllowedMask & NOTIFICATION_WARNING) != 0) {
625 // check if we should warn about throttle
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700626 // pretend we only have 1/2 the time remaining that we actually do
627 // if our burn rate in the period so far would have us exceed the limit
628 // in that 1/2 window, warn the user.
629 // this gets more generous in the early to middle period and converges back
630 // to the limit as we move toward the period end.
631
632 // adding another factor - it must be greater than the total cap/4
633 // else we may get false alarms very early in the period.. in the first
634 // tenth of a percent of the period if we used more than a tenth of a percent
635 // of the cap we'd get a warning and that's not desired.
636 long start = mRecorder.getPeriodStart();
637 long end = mRecorder.getPeriodEnd();
638 long periodLength = end - start;
639 long now = System.currentTimeMillis();
640 long timeUsed = now - start;
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700641 long warningThreshold = 2*threshold*timeUsed/(timeUsed+periodLength);
642 if ((currentTotal > warningThreshold) && (currentTotal > threshold/4)) {
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700643 if (mWarningNotificationSent == false) {
644 mWarningNotificationSent = true;
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700645 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
646 postNotification(R.string.throttle_warning_notification_title,
647 R.string.throttle_warning_notification_message,
648 R.drawable.stat_sys_throttled,
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700649 0);
650 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700651 } else {
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700652 if (mWarningNotificationSent == true) {
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700653 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
Robert Greenwalte2c0ce02010-04-09 12:31:46 -0700654 mWarningNotificationSent =false;
655 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700656 }
657 }
658 }
659 }
660
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700661 private void postNotification(int titleInt, int messageInt, int icon, int flags) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700662 Intent intent = new Intent();
663 // TODO - fix up intent
Robert Greenwalt2a7b7302010-04-12 14:56:31 -0700664 intent.setClassName("com.android.phone", "com.android.phone.DataUsage");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700665 intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
666
667 PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
668
669 Resources r = Resources.getSystem();
670 CharSequence title = r.getText(titleInt);
671 CharSequence message = r.getText(messageInt);
672 if (mThrottlingNotification == null) {
673 mThrottlingNotification = new Notification();
674 mThrottlingNotification.when = 0;
675 // TODO - fixup icon
676 mThrottlingNotification.icon = icon;
677 mThrottlingNotification.defaults &= ~Notification.DEFAULT_SOUND;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700678 }
Robert Greenwaltc87dc6d2010-04-08 16:00:26 -0700679 mThrottlingNotification.flags = flags;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700680 mThrottlingNotification.tickerText = title;
681 mThrottlingNotification.setLatestEventInfo(mContext, title, message, pi);
682
683 mNotificationManager.notify(mThrottlingNotification.icon, mThrottlingNotification);
684 }
685
686
Robert Greenwalt39e163f2010-05-07 16:52:17 -0700687 private void clearThrottleAndNotification() {
688 if (mThrottleIndex.get() != THROTTLE_INDEX_UNTHROTTLED) {
689 mThrottleIndex.set(THROTTLE_INDEX_UNTHROTTLED);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700690 try {
Robert Greenwaltd3bb93f2010-04-12 19:20:55 -0700691 mNMService.setInterfaceThrottle(mIface, -1, -1);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700692 } catch (Exception e) {
693 Slog.e(TAG, "error clearing Throttle: " + e);
694 }
695 Intent broadcast = new Intent(ThrottleManager.THROTTLE_ACTION);
696 broadcast.putExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL, -1);
697 mContext.sendStickyBroadcast(broadcast);
Robert Greenwalt5bf16d62010-04-23 13:15:44 -0700698 mNotificationManager.cancel(R.drawable.stat_sys_throttled);
699 mWarningNotificationSent = false;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700700 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700701 }
702
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700703 private Calendar calculatePeriodEnd(long now) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700704 Calendar end = GregorianCalendar.getInstance();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700705 end.setTimeInMillis(now);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700706 int day = end.get(Calendar.DAY_OF_MONTH);
707 end.set(Calendar.DAY_OF_MONTH, mPolicyResetDay);
708 end.set(Calendar.HOUR_OF_DAY, 0);
709 end.set(Calendar.MINUTE, 0);
Robert Greenwalt8c7e6092010-04-14 17:31:20 -0700710 end.set(Calendar.SECOND, 0);
711 end.set(Calendar.MILLISECOND, 0);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700712 if (day >= mPolicyResetDay) {
713 int month = end.get(Calendar.MONTH);
714 if (month == Calendar.DECEMBER) {
715 end.set(Calendar.YEAR, end.get(Calendar.YEAR) + 1);
716 month = Calendar.JANUARY - 1;
717 }
718 end.set(Calendar.MONTH, month + 1);
719 }
720
721 // TODO - remove!
722 if (SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true")) {
723 end = GregorianCalendar.getInstance();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700724 end.setTimeInMillis(now);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700725 end.add(Calendar.SECOND, TESTING_RESET_PERIOD_SEC);
726 }
727 return end;
728 }
729 private Calendar calculatePeriodStart(Calendar end) {
730 Calendar start = (Calendar)end.clone();
731 int month = end.get(Calendar.MONTH);
732 if (end.get(Calendar.MONTH) == Calendar.JANUARY) {
733 month = Calendar.DECEMBER + 1;
734 start.set(Calendar.YEAR, start.get(Calendar.YEAR) - 1);
735 }
736 start.set(Calendar.MONTH, month - 1);
737
738 // TODO - remove!!
739 if (SystemProperties.get(TESTING_ENABLED_PROPERTY).equals("true")) {
740 start = (Calendar)end.clone();
741 start.add(Calendar.SECOND, -TESTING_RESET_PERIOD_SEC);
742 }
743 return start;
744 }
745
746 private void onResetAlarm() {
Robert Greenwalt687f2a02010-06-08 10:10:54 -0700747 if (VDBG || (mPolicyThreshold.get() != 0)) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700748 Slog.d(TAG, "onResetAlarm - last period had " + mRecorder.getPeriodRx(0) +
749 " bytes read and " + mRecorder.getPeriodTx(0) + " written");
750 }
751
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700752 // when trusted cache outdated, try refreshing
753 if (mTime.getCacheAge() > mMaxNtpCacheAge) {
754 mTime.forceRefresh();
755 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700756
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700757 // as long as we have a trusted time cache, we always reset alarms,
758 // even if the refresh above failed.
759 if (mTime.hasCache()) {
760 final long now = mTime.currentTimeMillis();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700761 Calendar end = calculatePeriodEnd(now);
762 Calendar start = calculatePeriodStart(end);
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700763
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700764 if (mRecorder.setNextPeriod(start, end)) {
Robert Greenwalt05d06732010-04-19 11:10:38 -0700765 onPollAlarm();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700766 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700767
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700768 mAlarmManager.cancel(mPendingResetIntent);
769 long offset = end.getTimeInMillis() - now;
770 // use Elapsed realtime so clock changes don't fool us.
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700771 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME,
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700772 SystemClock.elapsedRealtime() + offset,
773 mPendingResetIntent);
774 } else {
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700775 if (VDBG) Slog.d(TAG, "no trusted time, not resetting period");
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700776 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700777 }
778 }
779
780 // records bytecount data for a given time and accumulates it into larger time windows
781 // for logging and other purposes
782 //
783 // since time can be changed (user or network action) we will have to track the time of the
784 // last recording and deal with it.
785 private static class DataRecorder {
786 long[] mPeriodRxData;
787 long[] mPeriodTxData;
788 int mCurrentPeriod;
789 int mPeriodCount;
790
791 Calendar mPeriodStart;
792 Calendar mPeriodEnd;
793
794 ThrottleService mParent;
795 Context mContext;
Robert Greenwalte6e98822010-04-15 08:27:14 -0700796 String mImsi = null;
797
798 TelephonyManager mTelephonyManager;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700799
800 DataRecorder(Context context, ThrottleService parent) {
801 mContext = context;
802 mParent = parent;
803
Robert Greenwalte6e98822010-04-15 08:27:14 -0700804 mTelephonyManager = (TelephonyManager)mContext.getSystemService(
805 Context.TELEPHONY_SERVICE);
806
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700807 synchronized (mParent) {
808 mPeriodCount = 6;
809 mPeriodRxData = new long[mPeriodCount];
810 mPeriodTxData = new long[mPeriodCount];
811
812 mPeriodStart = Calendar.getInstance();
813 mPeriodEnd = Calendar.getInstance();
814
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700815 retrieve();
816 }
817 }
818
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700819 boolean setNextPeriod(Calendar start, Calendar end) {
Robert Greenwalte6e98822010-04-15 08:27:14 -0700820 // TODO - how would we deal with a dual-IMSI device?
821 checkForSubscriberId();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700822 boolean startNewPeriod = true;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700823
Robert Greenwalt27fba672010-04-26 12:29:14 -0700824 if (start.equals(mPeriodStart) && end.equals(mPeriodEnd)) {
825 // same endpoints - keep collecting
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700826 if (VDBG) {
Robert Greenwalt27fba672010-04-26 12:29:14 -0700827 Slog.d(TAG, "same period (" + start.getTimeInMillis() + "," +
828 end.getTimeInMillis() +") - ammending data");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700829 }
Robert Greenwalt27fba672010-04-26 12:29:14 -0700830 startNewPeriod = false;
831 } else {
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700832 if (VDBG) {
Robert Greenwalt27fba672010-04-26 12:29:14 -0700833 if(start.equals(mPeriodEnd) || start.after(mPeriodEnd)) {
834 Slog.d(TAG, "next period (" + start.getTimeInMillis() + "," +
835 end.getTimeInMillis() + ") - old end was " +
836 mPeriodEnd.getTimeInMillis() + ", following");
837 } else {
838 Slog.d(TAG, "new period (" + start.getTimeInMillis() + "," +
839 end.getTimeInMillis() + ") replacing old (" +
840 mPeriodStart.getTimeInMillis() + "," +
841 mPeriodEnd.getTimeInMillis() + ")");
842 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700843 }
844 synchronized (mParent) {
845 ++mCurrentPeriod;
846 if (mCurrentPeriod >= mPeriodCount) mCurrentPeriod = 0;
847 mPeriodRxData[mCurrentPeriod] = 0;
848 mPeriodTxData[mCurrentPeriod] = 0;
849 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700850 }
851 setPeriodStart(start);
852 setPeriodEnd(end);
853 record();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700854 return startNewPeriod;
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700855 }
856
857 public long getPeriodEnd() {
858 synchronized (mParent) {
859 return mPeriodEnd.getTimeInMillis();
860 }
861 }
862
863 private void setPeriodEnd(Calendar end) {
864 synchronized (mParent) {
865 mPeriodEnd = end;
866 }
867 }
868
869 public long getPeriodStart() {
870 synchronized (mParent) {
871 return mPeriodStart.getTimeInMillis();
872 }
873 }
874
875 private void setPeriodStart(Calendar start) {
876 synchronized (mParent) {
877 mPeriodStart = start;
878 }
879 }
880
881 public int getPeriodCount() {
882 synchronized (mParent) {
883 return mPeriodCount;
884 }
885 }
886
887 private void zeroData(int field) {
888 synchronized (mParent) {
889 for(int period = 0; period<mPeriodCount; period++) {
890 mPeriodRxData[period] = 0;
891 mPeriodTxData[period] = 0;
892 }
893 mCurrentPeriod = 0;
894 }
895
896 }
897
898 // if time moves backward accumulate all read/write that's lost into the now
899 // otherwise time moved forward.
900 void addData(long bytesRead, long bytesWritten) {
Robert Greenwalte6e98822010-04-15 08:27:14 -0700901 checkForSubscriberId();
Robert Greenwalt7171ea82010-04-14 22:37:12 -0700902
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700903 synchronized (mParent) {
904 mPeriodRxData[mCurrentPeriod] += bytesRead;
905 mPeriodTxData[mCurrentPeriod] += bytesWritten;
906 }
907 record();
908 }
909
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700910 private File getDataFile() {
911 File dataDir = Environment.getDataDirectory();
912 File throttleDir = new File(dataDir, "system/throttle");
913 throttleDir.mkdirs();
Robert Greenwalte6e98822010-04-15 08:27:14 -0700914 String mImsi = mTelephonyManager.getSubscriberId();
915 File dataFile;
916 if (mImsi == null) {
917 dataFile = useMRUFile(throttleDir);
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700918 if (VDBG) Slog.v(TAG, "imsi not available yet, using " + dataFile);
Robert Greenwalte6e98822010-04-15 08:27:14 -0700919 } else {
920 String imsiHash = Integer.toString(mImsi.hashCode());
921 dataFile = new File(throttleDir, imsiHash);
922 }
923 // touch the file so it's not LRU
924 dataFile.setLastModified(System.currentTimeMillis());
925 checkAndDeleteLRUDataFile(throttleDir);
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700926 return dataFile;
927 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700928
Robert Greenwalte6e98822010-04-15 08:27:14 -0700929 // TODO - get broadcast (TelephonyIntents.ACTION_SIM_STATE_CHANGED) instead of polling
930 private void checkForSubscriberId() {
931 if (mImsi != null) return;
932
933 mImsi = mTelephonyManager.getSubscriberId();
934 if (mImsi == null) return;
935
Robert Greenwalt5a671d02010-06-07 16:43:16 -0700936 if (VDBG) Slog.d(TAG, "finally have imsi - retreiving data");
Robert Greenwalte6e98822010-04-15 08:27:14 -0700937 retrieve();
938 }
939
940 private final static int MAX_SIMS_SUPPORTED = 3;
941
942 private void checkAndDeleteLRUDataFile(File dir) {
943 File[] files = dir.listFiles();
944
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700945 if (files == null || files.length <= MAX_SIMS_SUPPORTED) return;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700946 if (DBG) Slog.d(TAG, "Too many data files");
Robert Greenwalte6e98822010-04-15 08:27:14 -0700947 do {
948 File oldest = null;
949 for (File f : files) {
950 if ((oldest == null) || (oldest.lastModified() > f.lastModified())) {
951 oldest = f;
952 }
953 }
954 if (oldest == null) return;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700955 if (DBG) Slog.d(TAG, " deleting " + oldest);
Robert Greenwalte6e98822010-04-15 08:27:14 -0700956 oldest.delete();
957 files = dir.listFiles();
958 } while (files.length > MAX_SIMS_SUPPORTED);
959 }
960
961 private File useMRUFile(File dir) {
962 File newest = null;
963 File[] files = dir.listFiles();
964
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -0700965 if (files != null) {
966 for (File f : files) {
967 if ((newest == null) || (newest.lastModified() < f.lastModified())) {
968 newest = f;
969 }
Robert Greenwalte6e98822010-04-15 08:27:14 -0700970 }
971 }
972 if (newest == null) {
973 newest = new File(dir, "temp");
974 }
975 return newest;
976 }
977
978
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700979 private static final int DATA_FILE_VERSION = 1;
980
981 private void record() {
982 // 1 int version
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700983 // 1 int mPeriodCount
984 // 13*6 long[PERIOD_COUNT] mPeriodRxData
985 // 13*6 long[PERIOD_COUNT] mPeriodTxData
986 // 1 int mCurrentPeriod
987 // 13 long periodStartMS
988 // 13 long periodEndMS
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700989 // 200 chars max
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700990 StringBuilder builder = new StringBuilder();
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700991 builder.append(DATA_FILE_VERSION);
992 builder.append(":");
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700993 builder.append(mPeriodCount);
994 builder.append(":");
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700995 for(int i = 0; i < mPeriodCount; i++) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -0700996 builder.append(mPeriodRxData[i]);
997 builder.append(":");
998 }
Robert Greenwaltb8912f52010-04-09 17:27:26 -0700999 for(int i = 0; i < mPeriodCount; i++) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001000 builder.append(mPeriodTxData[i]);
1001 builder.append(":");
1002 }
1003 builder.append(mCurrentPeriod);
1004 builder.append(":");
1005 builder.append(mPeriodStart.getTimeInMillis());
1006 builder.append(":");
1007 builder.append(mPeriodEnd.getTimeInMillis());
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001008
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001009 BufferedWriter out = null;
1010 try {
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001011 out = new BufferedWriter(new FileWriter(getDataFile()), 256);
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001012 out.write(builder.toString());
1013 } catch (IOException e) {
1014 Slog.e(TAG, "Error writing data file");
1015 return;
1016 } finally {
1017 if (out != null) {
1018 try {
1019 out.close();
1020 } catch (Exception e) {}
1021 }
1022 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001023 }
1024
1025 private void retrieve() {
Robert Greenwalt05d06732010-04-19 11:10:38 -07001026 // clean out any old data first. If we fail to read we don't want old stuff
1027 zeroData(0);
1028
Robert Greenwaltb8912f52010-04-09 17:27:26 -07001029 File f = getDataFile();
1030 byte[] buffer;
1031 FileInputStream s = null;
1032 try {
1033 buffer = new byte[(int)f.length()];
1034 s = new FileInputStream(f);
1035 s.read(buffer);
1036 } catch (IOException e) {
1037 Slog.e(TAG, "Error reading data file");
1038 return;
1039 } finally {
1040 if (s != null) {
1041 try {
1042 s.close();
1043 } catch (Exception e) {}
1044 }
1045 }
1046 String data = new String(buffer);
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001047 if (data == null || data.length() == 0) {
1048 if (DBG) Slog.d(TAG, "data file empty");
1049 return;
1050 }
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001051 String[] parsed = data.split(":");
1052 int parsedUsed = 0;
1053 if (parsed.length < 6) {
1054 Slog.e(TAG, "reading data file with insufficient length - ignoring");
1055 return;
1056 }
1057
Robert Greenwalt9e3983f2010-05-11 07:06:13 -07001058 int periodCount;
1059 long[] periodRxData;
1060 long[] periodTxData;
1061 int currentPeriod;
1062 Calendar periodStart;
1063 Calendar periodEnd;
1064 try {
1065 if (Integer.parseInt(parsed[parsedUsed++]) != DATA_FILE_VERSION) {
1066 Slog.e(TAG, "reading data file with bad version - ignoring");
1067 return;
1068 }
1069
1070 periodCount = Integer.parseInt(parsed[parsedUsed++]);
1071 if (parsed.length != 5 + (2 * periodCount)) {
1072 Slog.e(TAG, "reading data file with bad length (" + parsed.length +
1073 " != " + (5 + (2 * periodCount)) + ") - ignoring");
1074 return;
1075 }
1076 periodRxData = new long[periodCount];
1077 for (int i = 0; i < periodCount; i++) {
1078 periodRxData[i] = Long.parseLong(parsed[parsedUsed++]);
1079 }
1080 periodTxData = new long[periodCount];
1081 for (int i = 0; i < periodCount; i++) {
1082 periodTxData[i] = Long.parseLong(parsed[parsedUsed++]);
1083 }
1084
1085 currentPeriod = Integer.parseInt(parsed[parsedUsed++]);
1086
1087 periodStart = new GregorianCalendar();
1088 periodStart.setTimeInMillis(Long.parseLong(parsed[parsedUsed++]));
1089 periodEnd = new GregorianCalendar();
1090 periodEnd.setTimeInMillis(Long.parseLong(parsed[parsedUsed++]));
1091 } catch (Exception e) {
1092 Slog.e(TAG, "Error parsing data file - ignoring");
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001093 return;
1094 }
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001095 synchronized (mParent) {
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001096 mPeriodCount = periodCount;
1097 mPeriodRxData = periodRxData;
1098 mPeriodTxData = periodTxData;
Robert Greenwalt9e3983f2010-05-11 07:06:13 -07001099 mCurrentPeriod = currentPeriod;
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001100 mPeriodStart = periodStart;
1101 mPeriodEnd = periodEnd;
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001102 }
1103 }
1104
1105 long getPeriodRx(int which) {
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001106 synchronized (mParent) {
1107 if (which > mPeriodCount) return 0;
1108 which = mCurrentPeriod - which;
1109 if (which < 0) which += mPeriodCount;
1110 return mPeriodRxData[which];
1111 }
1112 }
1113 long getPeriodTx(int which) {
1114 synchronized (mParent) {
1115 if (which > mPeriodCount) return 0;
1116 which = mCurrentPeriod - which;
1117 if (which < 0) which += mPeriodCount;
1118 return mPeriodTxData[which];
1119 }
1120 }
1121 }
1122
1123 @Override
1124 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1125 if (mContext.checkCallingOrSelfPermission(
1126 android.Manifest.permission.DUMP)
1127 != PackageManager.PERMISSION_GRANTED) {
1128 pw.println("Permission Denial: can't dump ThrottleService " +
1129 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1130 Binder.getCallingUid());
1131 return;
1132 }
1133 pw.println();
1134
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001135 pw.println("The threshold is " + mPolicyThreshold.get() +
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001136 ", after which you experince throttling to " +
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001137 mPolicyThrottleValue.get() + "kbps");
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001138 pw.println("Current period is " +
1139 (mRecorder.getPeriodEnd() - mRecorder.getPeriodStart())/1000 + " seconds long " +
Robert Greenwalt7171ea82010-04-14 22:37:12 -07001140 "and ends in " + (getResetTime(mIface) - System.currentTimeMillis()) / 1000 +
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001141 " seconds.");
1142 pw.println("Polling every " + mPolicyPollPeriodSec + " seconds");
Robert Greenwalt39e163f2010-05-07 16:52:17 -07001143 pw.println("Current Throttle Index is " + mThrottleIndex.get());
Jeff Sharkeyb7342ac2011-04-25 23:44:11 -07001144 pw.println("mMaxNtpCacheAge=" + mMaxNtpCacheAge);
Robert Greenwalt8c7e6092010-04-14 17:31:20 -07001145
Robert Greenwalt9e696c22010-04-01 14:45:18 -07001146 for (int i = 0; i < mRecorder.getPeriodCount(); i++) {
1147 pw.println(" Period[" + i + "] - read:" + mRecorder.getPeriodRx(i) + ", written:" +
1148 mRecorder.getPeriodTx(i));
1149 }
1150 }
1151}