blob: 546f2be0770a43f1ae031625ede77e3f4308a69a [file] [log] [blame]
Jeff Sharkey75279902011-05-24 18:39:45 -07001/*
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07002 * Copyright (C) 2011 The Android Open Source Project
Jeff Sharkey75279902011-05-24 18:39:45 -07003 *
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.net;
18
Jeff Sharkeya63ba592011-07-19 23:47:12 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey63d27a92011-08-03 17:04:22 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey75279902011-05-24 18:39:45 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey63d27a92011-08-03 17:04:22 -070022import static android.Manifest.permission.MODIFY_NETWORK_ACCOUNTING;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070024import static android.content.Intent.ACTION_SHUTDOWN;
25import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -070026import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.EXTRA_UID;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -070028import static android.net.ConnectivityManager.ACTION_TETHER_STATE_CHANGED;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070029import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey234766a2012-04-10 19:48:07 -070030import static android.net.ConnectivityManager.isNetworkTypeMobile;
Jeff Sharkeyd4dd7712012-03-16 11:11:54 -070031import static android.net.NetworkIdentity.COMBINE_SUBTYPE_ENABLED;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -070032import static android.net.NetworkStats.IFACE_ALL;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070033import static android.net.NetworkStats.SET_ALL;
34import static android.net.NetworkStats.SET_DEFAULT;
35import static android.net.NetworkStats.SET_FOREGROUND;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070036import static android.net.NetworkStats.TAG_NONE;
Jeff Sharkey75279902011-05-24 18:39:45 -070037import static android.net.NetworkStats.UID_ALL;
Jeff Sharkey234766a2012-04-10 19:48:07 -070038import static android.net.NetworkTemplate.buildTemplateMobileWildcard;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070039import static android.net.NetworkTemplate.buildTemplateWifiWildcard;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -070040import static android.net.TrafficStats.KB_IN_BYTES;
Jeff Sharkey241dde22012-02-03 14:50:07 -080041import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey023c05a2012-09-14 13:09:57 -070042import static android.provider.Settings.Global.NETSTATS_DEV_BUCKET_DURATION;
43import static android.provider.Settings.Global.NETSTATS_DEV_DELETE_AGE;
44import static android.provider.Settings.Global.NETSTATS_DEV_PERSIST_BYTES;
45import static android.provider.Settings.Global.NETSTATS_DEV_ROTATE_AGE;
46import static android.provider.Settings.Global.NETSTATS_GLOBAL_ALERT_BYTES;
47import static android.provider.Settings.Global.NETSTATS_POLL_INTERVAL;
48import static android.provider.Settings.Global.NETSTATS_REPORT_XT_OVER_DEV;
49import static android.provider.Settings.Global.NETSTATS_SAMPLE_ENABLED;
50import static android.provider.Settings.Global.NETSTATS_TIME_CACHE_MAX_AGE;
51import static android.provider.Settings.Global.NETSTATS_UID_BUCKET_DURATION;
52import static android.provider.Settings.Global.NETSTATS_UID_DELETE_AGE;
53import static android.provider.Settings.Global.NETSTATS_UID_PERSIST_BYTES;
54import static android.provider.Settings.Global.NETSTATS_UID_ROTATE_AGE;
55import static android.provider.Settings.Global.NETSTATS_UID_TAG_BUCKET_DURATION;
56import static android.provider.Settings.Global.NETSTATS_UID_TAG_DELETE_AGE;
57import static android.provider.Settings.Global.NETSTATS_UID_TAG_PERSIST_BYTES;
58import static android.provider.Settings.Global.NETSTATS_UID_TAG_ROTATE_AGE;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import static android.telephony.PhoneStateListener.LISTEN_DATA_CONNECTION_STATE;
60import static android.telephony.PhoneStateListener.LISTEN_NONE;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -070061import static android.text.format.DateUtils.DAY_IN_MILLIS;
62import static android.text.format.DateUtils.HOUR_IN_MILLIS;
63import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070064import static android.text.format.DateUtils.SECOND_IN_MILLIS;
Jeff Sharkey234766a2012-04-10 19:48:07 -070065import static com.android.internal.util.ArrayUtils.appendElement;
66import static com.android.internal.util.ArrayUtils.contains;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070068import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070069import static com.android.server.NetworkManagementSocketTagger.resetKernelUidStats;
70import static com.android.server.NetworkManagementSocketTagger.setKernelCounterSet;
Jeff Sharkey75279902011-05-24 18:39:45 -070071
72import android.app.AlarmManager;
73import android.app.IAlarmManager;
74import android.app.PendingIntent;
75import android.content.BroadcastReceiver;
Jeff Sharkey39ebc212011-06-11 17:25:42 -070076import android.content.ContentResolver;
Jeff Sharkey75279902011-05-24 18:39:45 -070077import android.content.Context;
78import android.content.Intent;
79import android.content.IntentFilter;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -070080import android.content.pm.ApplicationInfo;
81import android.content.pm.PackageManager;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070082import android.net.IConnectivityManager;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070083import android.net.INetworkManagementEventObserver;
Jeff Sharkey75279902011-05-24 18:39:45 -070084import android.net.INetworkStatsService;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -070085import android.net.INetworkStatsSession;
Jeff Sharkey63abc372012-01-11 18:38:16 -080086import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070087import android.net.NetworkIdentity;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070088import android.net.NetworkInfo;
89import android.net.NetworkState;
Jeff Sharkey75279902011-05-24 18:39:45 -070090import android.net.NetworkStats;
Jeff Sharkey5a7bcf32012-01-10 17:24:44 -080091import android.net.NetworkStats.NonMonotonicObserver;
Jeff Sharkey75279902011-05-24 18:39:45 -070092import android.net.NetworkStatsHistory;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070093import android.net.NetworkTemplate;
Jeff Sharkey63abc372012-01-11 18:38:16 -080094import android.net.TrafficStats;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070095import android.os.Binder;
Jeff Sharkey163e6442011-10-31 16:37:52 -070096import android.os.DropBoxManager;
Jeff Sharkey3f391352011-06-05 17:42:53 -070097import android.os.Environment;
Jeff Sharkey75279902011-05-24 18:39:45 -070098import android.os.Handler;
99import android.os.HandlerThread;
100import android.os.INetworkManagementService;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700101import android.os.Message;
Jeff Sharkey62489262011-07-17 12:53:28 -0700102import android.os.PowerManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700103import android.os.RemoteException;
104import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700105import android.os.UserHandle;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700106import android.provider.Settings;
Jeff Sharkey625239a2012-09-26 22:03:49 -0700107import android.provider.Settings.Global;
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700108import android.telephony.PhoneStateListener;
Jeff Sharkey75279902011-05-24 18:39:45 -0700109import android.telephony.TelephonyManager;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -0700110import android.util.EventLog;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700111import android.util.Log;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700112import android.util.MathUtils;
Jeff Sharkey75279902011-05-24 18:39:45 -0700113import android.util.NtpTrustedTime;
114import android.util.Slog;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700115import android.util.SparseIntArray;
Jeff Sharkey75279902011-05-24 18:39:45 -0700116import android.util.TrustedTime;
117
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800118import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700119import com.android.internal.util.ArrayUtils;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800120import com.android.internal.util.FileRotator;
121import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -0700122import com.android.server.EventLogTags;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700123import com.android.server.connectivity.Tethering;
Jeff Sharkey75279902011-05-24 18:39:45 -0700124import com.google.android.collect.Maps;
125
Jeff Sharkey3f391352011-06-05 17:42:53 -0700126import java.io.File;
Jeff Sharkey75279902011-05-24 18:39:45 -0700127import java.io.FileDescriptor;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700128import java.io.IOException;
Jeff Sharkey75279902011-05-24 18:39:45 -0700129import java.io.PrintWriter;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700130import java.util.Arrays;
Jeff Sharkey75279902011-05-24 18:39:45 -0700131import java.util.HashMap;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700132import java.util.HashSet;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700133import java.util.List;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700134
Jeff Sharkey75279902011-05-24 18:39:45 -0700135/**
136 * Collect and persist detailed network statistics, and provide this data to
137 * other system services.
138 */
139public class NetworkStatsService extends INetworkStatsService.Stub {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700140 private static final String TAG = "NetworkStats";
Jeff Sharkey706498d2012-02-06 17:35:07 -0800141 private static final boolean LOGV = false;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700142
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700143 private static final int MSG_PERFORM_POLL = 1;
144 private static final int MSG_UPDATE_IFACES = 2;
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -0800145 private static final int MSG_REGISTER_GLOBAL_ALERT = 3;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700146
147 /** Flags to control detail level of poll event. */
Jeff Sharkey905b5892011-09-30 15:19:49 -0700148 private static final int FLAG_PERSIST_NETWORK = 0x1;
149 private static final int FLAG_PERSIST_UID = 0x2;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700150 private static final int FLAG_PERSIST_ALL = FLAG_PERSIST_NETWORK | FLAG_PERSIST_UID;
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700151 private static final int FLAG_PERSIST_FORCE = 0x100;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700152
Jeff Sharkey163e6442011-10-31 16:37:52 -0700153 private static final String TAG_NETSTATS_ERROR = "netstats_error";
154
Jeff Sharkey75279902011-05-24 18:39:45 -0700155 private final Context mContext;
156 private final INetworkManagementService mNetworkManager;
157 private final IAlarmManager mAlarmManager;
158 private final TrustedTime mTime;
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700159 private final TelephonyManager mTeleManager;
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700160 private final NetworkStatsSettings mSettings;
Jeff Sharkey75279902011-05-24 18:39:45 -0700161
Jeff Sharkey63abc372012-01-11 18:38:16 -0800162 private final File mSystemDir;
163 private final File mBaseDir;
164
Jeff Sharkey62489262011-07-17 12:53:28 -0700165 private final PowerManager.WakeLock mWakeLock;
166
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700167 private IConnectivityManager mConnManager;
168
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800169 @VisibleForTesting
Jeff Sharkey3f391352011-06-05 17:42:53 -0700170 public static final String ACTION_NETWORK_STATS_POLL =
Jeff Sharkey75279902011-05-24 18:39:45 -0700171 "com.android.server.action.NETWORK_STATS_POLL";
Jeff Sharkey497e4432011-06-14 17:27:29 -0700172 public static final String ACTION_NETWORK_STATS_UPDATED =
173 "com.android.server.action.NETWORK_STATS_UPDATED";
Jeff Sharkey75279902011-05-24 18:39:45 -0700174
175 private PendingIntent mPollIntent;
176
Jeff Sharkey63abc372012-01-11 18:38:16 -0800177 private static final String PREFIX_DEV = "dev";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700178 private static final String PREFIX_XT = "xt";
Jeff Sharkey63abc372012-01-11 18:38:16 -0800179 private static final String PREFIX_UID = "uid";
180 private static final String PREFIX_UID_TAG = "uid_tag";
181
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700182 /**
183 * Settings that can be changed externally.
184 */
185 public interface NetworkStatsSettings {
186 public long getPollInterval();
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700187 public long getTimeCacheMaxAge();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800188 public boolean getSampleEnabled();
Jeff Sharkey70c70532012-05-16 14:51:19 -0700189 public boolean getReportXtOverDev();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800190
191 public static class Config {
192 public final long bucketDuration;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800193 public final long rotateAgeMillis;
194 public final long deleteAgeMillis;
195
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700196 public Config(long bucketDuration, long rotateAgeMillis, long deleteAgeMillis) {
Jeff Sharkey63abc372012-01-11 18:38:16 -0800197 this.bucketDuration = bucketDuration;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800198 this.rotateAgeMillis = rotateAgeMillis;
199 this.deleteAgeMillis = deleteAgeMillis;
200 }
201 }
202
203 public Config getDevConfig();
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700204 public Config getXtConfig();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800205 public Config getUidConfig();
206 public Config getUidTagConfig();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700207
208 public long getGlobalAlertBytes(long def);
209 public long getDevPersistBytes(long def);
210 public long getXtPersistBytes(long def);
211 public long getUidPersistBytes(long def);
212 public long getUidTagPersistBytes(long def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700213 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700214
215 private final Object mStatsLock = new Object();
216
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700217 /** Set of currently active ifaces. */
218 private HashMap<String, NetworkIdentitySet> mActiveIfaces = Maps.newHashMap();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800219 /** Current default active iface. */
220 private String mActiveIface;
Jeff Sharkey234766a2012-04-10 19:48:07 -0700221 /** Set of any ifaces associated with mobile networks since boot. */
222 private String[] mMobileIfaces = new String[0];
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700223
Jeff Sharkey63abc372012-01-11 18:38:16 -0800224 private final DropBoxNonMonotonicObserver mNonMonotonicObserver =
225 new DropBoxNonMonotonicObserver();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700226
Jeff Sharkey63abc372012-01-11 18:38:16 -0800227 private NetworkStatsRecorder mDevRecorder;
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700228 private NetworkStatsRecorder mXtRecorder;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800229 private NetworkStatsRecorder mUidRecorder;
230 private NetworkStatsRecorder mUidTagRecorder;
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700231
Jeff Sharkey63abc372012-01-11 18:38:16 -0800232 /** Cached {@link #mDevRecorder} stats. */
233 private NetworkStatsCollection mDevStatsCached;
Jeff Sharkey70c70532012-05-16 14:51:19 -0700234 /** Cached {@link #mXtRecorder} stats. */
235 private NetworkStatsCollection mXtStatsCached;
Jeff Sharkey75279902011-05-24 18:39:45 -0700236
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700237 /** Current counter sets for each UID. */
238 private SparseIntArray mActiveUidCounterSet = new SparseIntArray();
239
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700240 /** Data layer operation counters for splicing into other structures. */
Jeff Sharkey63abc372012-01-11 18:38:16 -0800241 private NetworkStats mUidOperations = new NetworkStats(0L, 10);
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700242
Jeff Sharkey75279902011-05-24 18:39:45 -0700243 private final HandlerThread mHandlerThread;
244 private final Handler mHandler;
245
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800246 private boolean mSystemReady;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700247 private long mPersistThreshold = 2 * MB_IN_BYTES;
248 private long mGlobalAlertBytes;
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800249
Jeff Sharkey75279902011-05-24 18:39:45 -0700250 public NetworkStatsService(
251 Context context, INetworkManagementService networkManager, IAlarmManager alarmManager) {
Jeff Sharkey104344e2011-07-10 14:20:41 -0700252 this(context, networkManager, alarmManager, NtpTrustedTime.getInstance(context),
Jeff Sharkey63abc372012-01-11 18:38:16 -0800253 getDefaultSystemDir(), new DefaultNetworkStatsSettings(context));
Jeff Sharkey3f391352011-06-05 17:42:53 -0700254 }
255
Jeff Sharkey63abc372012-01-11 18:38:16 -0800256 private static File getDefaultSystemDir() {
Jeff Sharkey3f391352011-06-05 17:42:53 -0700257 return new File(Environment.getDataDirectory(), "system");
Jeff Sharkey75279902011-05-24 18:39:45 -0700258 }
259
260 public NetworkStatsService(Context context, INetworkManagementService networkManager,
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700261 IAlarmManager alarmManager, TrustedTime time, File systemDir,
262 NetworkStatsSettings settings) {
Jeff Sharkey75279902011-05-24 18:39:45 -0700263 mContext = checkNotNull(context, "missing Context");
264 mNetworkManager = checkNotNull(networkManager, "missing INetworkManagementService");
265 mAlarmManager = checkNotNull(alarmManager, "missing IAlarmManager");
266 mTime = checkNotNull(time, "missing TrustedTime");
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700267 mTeleManager = checkNotNull(TelephonyManager.getDefault(), "missing TelephonyManager");
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700268 mSettings = checkNotNull(settings, "missing NetworkStatsSettings");
Jeff Sharkey75279902011-05-24 18:39:45 -0700269
Jeff Sharkey62489262011-07-17 12:53:28 -0700270 final PowerManager powerManager = (PowerManager) context.getSystemService(
271 Context.POWER_SERVICE);
272 mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
273
Jeff Sharkey75279902011-05-24 18:39:45 -0700274 mHandlerThread = new HandlerThread(TAG);
275 mHandlerThread.start();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700276 mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700277
Jeff Sharkey63abc372012-01-11 18:38:16 -0800278 mSystemDir = checkNotNull(systemDir);
279 mBaseDir = new File(systemDir, "netstats");
280 mBaseDir.mkdirs();
Jeff Sharkey75279902011-05-24 18:39:45 -0700281 }
282
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 public void bindConnectivityManager(IConnectivityManager connManager) {
284 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
285 }
286
Jeff Sharkey75279902011-05-24 18:39:45 -0700287 public void systemReady() {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800288 mSystemReady = true;
289
Jeff Sharkey418d12d2011-12-13 15:38:03 -0800290 if (!isBandwidthControlEnabled()) {
291 Slog.w(TAG, "bandwidth controls disabled, unable to track stats");
292 return;
293 }
294
Jeff Sharkey63abc372012-01-11 18:38:16 -0800295 // create data recorders along with historical rotators
296 mDevRecorder = buildRecorder(PREFIX_DEV, mSettings.getDevConfig(), false);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700297 mXtRecorder = buildRecorder(PREFIX_XT, mSettings.getXtConfig(), false);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800298 mUidRecorder = buildRecorder(PREFIX_UID, mSettings.getUidConfig(), false);
299 mUidTagRecorder = buildRecorder(PREFIX_UID_TAG, mSettings.getUidTagConfig(), true);
Jeff Sharkey75279902011-05-24 18:39:45 -0700300
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700301 updatePersistThresholds();
302
Jeff Sharkey63abc372012-01-11 18:38:16 -0800303 synchronized (mStatsLock) {
304 // upgrade any legacy stats, migrating them to rotated files
305 maybeUpgradeLegacyStatsLocked();
306
307 // read historical network stats from disk, since policy service
308 // might need them right away.
309 mDevStatsCached = mDevRecorder.getOrLoadCompleteLocked();
Jeff Sharkey70c70532012-05-16 14:51:19 -0700310 mXtStatsCached = mXtRecorder.getOrLoadCompleteLocked();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800311
312 // bootstrap initial stats to prevent double-counting later
313 bootstrapStatsLocked();
314 }
Jeff Sharkey3359aca2011-11-08 18:08:48 -0800315
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700316 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700317 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700318 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
Jeff Sharkey75279902011-05-24 18:39:45 -0700319
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700320 // watch for tethering changes
321 final IntentFilter tetherFilter = new IntentFilter(ACTION_TETHER_STATE_CHANGED);
322 mContext.registerReceiver(mTetherReceiver, tetherFilter, CONNECTIVITY_INTERNAL, mHandler);
323
Jeff Sharkey75279902011-05-24 18:39:45 -0700324 // listen for periodic polling events
325 final IntentFilter pollFilter = new IntentFilter(ACTION_NETWORK_STATS_POLL);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700326 mContext.registerReceiver(mPollReceiver, pollFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
Jeff Sharkey75279902011-05-24 18:39:45 -0700327
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700328 // listen for uid removal to clean stats
329 final IntentFilter removedFilter = new IntentFilter(ACTION_UID_REMOVED);
330 mContext.registerReceiver(mRemovedReceiver, removedFilter, null, mHandler);
331
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700332 // listen for user changes to clean stats
333 final IntentFilter userFilter = new IntentFilter(ACTION_USER_REMOVED);
334 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
335
Jeff Sharkey75279902011-05-24 18:39:45 -0700336 // persist stats during clean shutdown
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700337 final IntentFilter shutdownFilter = new IntentFilter(ACTION_SHUTDOWN);
338 mContext.registerReceiver(mShutdownReceiver, shutdownFilter);
Jeff Sharkey75279902011-05-24 18:39:45 -0700339
340 try {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700341 mNetworkManager.registerObserver(mAlertObserver);
Jeff Sharkey75279902011-05-24 18:39:45 -0700342 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700343 // ignored; service lives in system_server
Jeff Sharkey75279902011-05-24 18:39:45 -0700344 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700345
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700346 // watch for networkType changes that aren't broadcast through
347 // CONNECTIVITY_ACTION_IMMEDIATE above.
Jeff Sharkeyd4dd7712012-03-16 11:11:54 -0700348 if (!COMBINE_SUBTYPE_ENABLED) {
349 mTeleManager.listen(mPhoneListener, LISTEN_DATA_CONNECTION_STATE);
350 }
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700351
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700352 registerPollAlarmLocked();
353 registerGlobalAlert();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800354 }
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700355
Jeff Sharkey63abc372012-01-11 18:38:16 -0800356 private NetworkStatsRecorder buildRecorder(
357 String prefix, NetworkStatsSettings.Config config, boolean includeTags) {
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700358 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
359 Context.DROPBOX_SERVICE);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700360 return new NetworkStatsRecorder(new FileRotator(
361 mBaseDir, prefix, config.rotateAgeMillis, config.deleteAgeMillis),
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700362 mNonMonotonicObserver, dropBox, prefix, config.bucketDuration, includeTags);
Jeff Sharkey75279902011-05-24 18:39:45 -0700363 }
364
Jeff Sharkey3f391352011-06-05 17:42:53 -0700365 private void shutdownLocked() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700366 mContext.unregisterReceiver(mConnReceiver);
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700367 mContext.unregisterReceiver(mTetherReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700368 mContext.unregisterReceiver(mPollReceiver);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700369 mContext.unregisterReceiver(mRemovedReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700370 mContext.unregisterReceiver(mShutdownReceiver);
371
Jeff Sharkeyd4dd7712012-03-16 11:11:54 -0700372 if (!COMBINE_SUBTYPE_ENABLED) {
373 mTeleManager.listen(mPhoneListener, LISTEN_NONE);
374 }
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700375
Jeff Sharkey63abc372012-01-11 18:38:16 -0800376 final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
377 : System.currentTimeMillis();
378
379 // persist any pending stats
380 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700381 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800382 mUidRecorder.forcePersistLocked(currentTime);
383 mUidTagRecorder.forcePersistLocked(currentTime);
384
385 mDevRecorder = null;
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700386 mXtRecorder = null;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800387 mUidRecorder = null;
388 mUidTagRecorder = null;
389
390 mDevStatsCached = null;
Jeff Sharkey70c70532012-05-16 14:51:19 -0700391 mXtStatsCached = null;
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800392
393 mSystemReady = false;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800394 }
395
396 private void maybeUpgradeLegacyStatsLocked() {
397 File file;
398 try {
399 file = new File(mSystemDir, "netstats.bin");
400 if (file.exists()) {
401 mDevRecorder.importLegacyNetworkLocked(file);
402 file.delete();
403 }
404
405 file = new File(mSystemDir, "netstats_xt.bin");
406 if (file.exists()) {
407 file.delete();
408 }
409
410 file = new File(mSystemDir, "netstats_uid.bin");
411 if (file.exists()) {
412 mUidRecorder.importLegacyUidLocked(file);
413 mUidTagRecorder.importLegacyUidLocked(file);
414 file.delete();
415 }
416 } catch (IOException e) {
417 Log.wtf(TAG, "problem during legacy upgrade", e);
Jeff Sharkeyc506ff62011-11-17 11:59:29 -0800418 }
Jeff Sharkey3f391352011-06-05 17:42:53 -0700419 }
420
Jeff Sharkey75279902011-05-24 18:39:45 -0700421 /**
422 * Clear any existing {@link #ACTION_NETWORK_STATS_POLL} alarms, and
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700423 * reschedule based on current {@link NetworkStatsSettings#getPollInterval()}.
Jeff Sharkey75279902011-05-24 18:39:45 -0700424 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700425 private void registerPollAlarmLocked() {
426 try {
427 if (mPollIntent != null) {
428 mAlarmManager.remove(mPollIntent);
429 }
430
431 mPollIntent = PendingIntent.getBroadcast(
432 mContext, 0, new Intent(ACTION_NETWORK_STATS_POLL), 0);
433
434 final long currentRealtime = SystemClock.elapsedRealtime();
435 mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, currentRealtime,
436 mSettings.getPollInterval(), mPollIntent);
437 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700438 // ignored; service lives in system_server
Jeff Sharkey75279902011-05-24 18:39:45 -0700439 }
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700440 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700441
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700442 /**
443 * Register for a global alert that is delivered through
444 * {@link INetworkManagementEventObserver} once a threshold amount of data
445 * has been transferred.
446 */
447 private void registerGlobalAlert() {
448 try {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700449 mNetworkManager.setGlobalAlert(mGlobalAlertBytes);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700450 } catch (IllegalStateException e) {
451 Slog.w(TAG, "problem registering for global alert: " + e);
452 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700453 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700454 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700455 }
456
457 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700458 public INetworkStatsSession openSession() {
459 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700460 assertBandwidthControlEnabled();
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700461
462 // return an IBinder which holds strong references to any loaded stats
463 // for its lifetime; when caller closes only weak references remain.
464
465 return new INetworkStatsSession.Stub() {
466 private NetworkStatsCollection mUidComplete;
467 private NetworkStatsCollection mUidTagComplete;
468
469 private NetworkStatsCollection getUidComplete() {
470 if (mUidComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700471 synchronized (mStatsLock) {
472 mUidComplete = mUidRecorder.getOrLoadCompleteLocked();
473 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700474 }
475 return mUidComplete;
476 }
477
478 private NetworkStatsCollection getUidTagComplete() {
479 if (mUidTagComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700480 synchronized (mStatsLock) {
481 mUidTagComplete = mUidTagRecorder.getOrLoadCompleteLocked();
482 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700483 }
484 return mUidTagComplete;
485 }
486
487 @Override
488 public NetworkStats getSummaryForNetwork(
489 NetworkTemplate template, long start, long end) {
Jeff Sharkey70c70532012-05-16 14:51:19 -0700490 return internalGetSummaryForNetwork(template, start, end);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700491 }
492
493 @Override
494 public NetworkStatsHistory getHistoryForNetwork(NetworkTemplate template, int fields) {
Jeff Sharkey70c70532012-05-16 14:51:19 -0700495 return internalGetHistoryForNetwork(template, fields);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700496 }
497
498 @Override
499 public NetworkStats getSummaryForAllUid(
500 NetworkTemplate template, long start, long end, boolean includeTags) {
501 final NetworkStats stats = getUidComplete().getSummary(template, start, end);
502 if (includeTags) {
503 final NetworkStats tagStats = getUidTagComplete()
504 .getSummary(template, start, end);
505 stats.combineAllValues(tagStats);
506 }
507 return stats;
508 }
509
510 @Override
511 public NetworkStatsHistory getHistoryForUid(
512 NetworkTemplate template, int uid, int set, int tag, int fields) {
513 if (tag == TAG_NONE) {
514 return getUidComplete().getHistory(template, uid, set, tag, fields);
515 } else {
516 return getUidTagComplete().getHistory(template, uid, set, tag, fields);
517 }
518 }
519
520 @Override
521 public void close() {
522 mUidComplete = null;
523 mUidTagComplete = null;
524 }
525 };
Jeff Sharkey905b5892011-09-30 15:19:49 -0700526 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700527
Jeff Sharkey70c70532012-05-16 14:51:19 -0700528 /**
529 * Return network summary, splicing between {@link #mDevStatsCached}
530 * and {@link #mXtStatsCached} when appropriate.
531 */
532 private NetworkStats internalGetSummaryForNetwork(
533 NetworkTemplate template, long start, long end) {
534 if (!mSettings.getReportXtOverDev()) {
535 // shortcut when XT reporting disabled
536 return mDevStatsCached.getSummary(template, start, end);
537 }
538
539 // splice stats between DEV and XT, switching over from DEV to XT at
540 // first atomic bucket.
541 final long firstAtomicBucket = mXtStatsCached.getFirstAtomicBucketMillis();
542 final NetworkStats dev = mDevStatsCached.getSummary(
543 template, Math.min(start, firstAtomicBucket), Math.min(end, firstAtomicBucket));
544 final NetworkStats xt = mXtStatsCached.getSummary(
545 template, Math.max(start, firstAtomicBucket), Math.max(end, firstAtomicBucket));
546
547 xt.combineAllValues(dev);
548 return xt;
549 }
550
551 /**
552 * Return network history, splicing between {@link #mDevStatsCached}
553 * and {@link #mXtStatsCached} when appropriate.
554 */
555 private NetworkStatsHistory internalGetHistoryForNetwork(NetworkTemplate template, int fields) {
556 if (!mSettings.getReportXtOverDev()) {
557 // shortcut when XT reporting disabled
558 return mDevStatsCached.getHistory(template, UID_ALL, SET_ALL, TAG_NONE, fields);
559 }
560
561 // splice stats between DEV and XT, switching over from DEV to XT at
562 // first atomic bucket.
563 final long firstAtomicBucket = mXtStatsCached.getFirstAtomicBucketMillis();
564 final NetworkStatsHistory dev = mDevStatsCached.getHistory(
565 template, UID_ALL, SET_ALL, TAG_NONE, fields, Long.MIN_VALUE, firstAtomicBucket);
566 final NetworkStatsHistory xt = mXtStatsCached.getHistory(
567 template, UID_ALL, SET_ALL, TAG_NONE, fields, firstAtomicBucket, Long.MAX_VALUE);
568
569 xt.recordEntireHistory(dev);
570 return xt;
571 }
572
Jeff Sharkey63abc372012-01-11 18:38:16 -0800573 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700574 public long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
575 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700576 assertBandwidthControlEnabled();
Jeff Sharkey70c70532012-05-16 14:51:19 -0700577 return internalGetSummaryForNetwork(template, start, end).getTotalBytes();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700578 }
579
Jeff Sharkey350083e2011-06-29 10:45:16 -0700580 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700581 public NetworkStats getDataLayerSnapshotForUid(int uid) throws RemoteException {
582 if (Binder.getCallingUid() != uid) {
583 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
584 }
Jeff Sharkey4190a042012-04-21 15:36:48 -0700585 assertBandwidthControlEnabled();
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700586
587 // TODO: switch to data layer stats once kernel exports
588 // for now, read network layer stats and flatten across all ifaces
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800589 final long token = Binder.clearCallingIdentity();
590 final NetworkStats networkLayer;
591 try {
592 networkLayer = mNetworkManager.getNetworkStatsUidDetail(uid);
593 } finally {
594 Binder.restoreCallingIdentity(token);
595 }
596
Jeff Sharkey21a54782012-04-09 10:27:55 -0700597 // splice in operation counts
598 networkLayer.spliceOperationsFrom(mUidOperations);
599
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700600 final NetworkStats dataLayer = new NetworkStats(
601 networkLayer.getElapsedRealtime(), networkLayer.size());
602
603 NetworkStats.Entry entry = null;
604 for (int i = 0; i < networkLayer.size(); i++) {
605 entry = networkLayer.getValues(i, entry);
606 entry.iface = IFACE_ALL;
607 dataLayer.combineValues(entry);
608 }
609
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700610 return dataLayer;
611 }
612
613 @Override
Jeff Sharkey234766a2012-04-10 19:48:07 -0700614 public String[] getMobileIfaces() {
615 return mMobileIfaces;
616 }
617
618 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700619 public void incrementOperationCount(int uid, int tag, int operationCount) {
620 if (Binder.getCallingUid() != uid) {
621 mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
622 }
623
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700624 if (operationCount < 0) {
625 throw new IllegalArgumentException("operation count can only be incremented");
626 }
627 if (tag == TAG_NONE) {
628 throw new IllegalArgumentException("operation count must have specific tag");
629 }
630
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700631 synchronized (mStatsLock) {
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700632 final int set = mActiveUidCounterSet.get(uid, SET_DEFAULT);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800633 mUidOperations.combineValues(
634 mActiveIface, uid, set, tag, 0L, 0L, 0L, 0L, operationCount);
635 mUidOperations.combineValues(
636 mActiveIface, uid, set, TAG_NONE, 0L, 0L, 0L, 0L, operationCount);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700637 }
638 }
639
640 @Override
641 public void setUidForeground(int uid, boolean uidForeground) {
642 mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
643
644 synchronized (mStatsLock) {
645 final int set = uidForeground ? SET_FOREGROUND : SET_DEFAULT;
646 final int oldSet = mActiveUidCounterSet.get(uid, SET_DEFAULT);
647 if (oldSet != set) {
648 mActiveUidCounterSet.put(uid, set);
649 setKernelCounterSet(uid, set);
650 }
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700651 }
652 }
653
654 @Override
Jeff Sharkey350083e2011-06-29 10:45:16 -0700655 public void forceUpdate() {
656 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700657 assertBandwidthControlEnabled();
Jeff Sharkeye630f7b2012-01-31 17:12:53 -0800658
659 final long token = Binder.clearCallingIdentity();
660 try {
661 performPoll(FLAG_PERSIST_ALL);
662 } finally {
663 Binder.restoreCallingIdentity(token);
664 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700665 }
666
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700667 @Override
668 public void advisePersistThreshold(long thresholdBytes) {
669 mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
670 assertBandwidthControlEnabled();
671
672 // clamp threshold into safe range
673 mPersistThreshold = MathUtils.constrain(thresholdBytes, 128 * KB_IN_BYTES, 2 * MB_IN_BYTES);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700674 if (LOGV) {
675 Slog.v(TAG, "advisePersistThreshold() given " + thresholdBytes + ", clamped to "
676 + mPersistThreshold);
677 }
678
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700679 // update and persist if beyond new thresholds
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700680 final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
681 : System.currentTimeMillis();
Jeff Sharkey58015972012-05-07 11:08:49 -0700682 synchronized (mStatsLock) {
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700683 if (!mSystemReady) return;
684
685 updatePersistThresholds();
686
Jeff Sharkey58015972012-05-07 11:08:49 -0700687 mDevRecorder.maybePersistLocked(currentTime);
688 mXtRecorder.maybePersistLocked(currentTime);
689 mUidRecorder.maybePersistLocked(currentTime);
690 mUidTagRecorder.maybePersistLocked(currentTime);
691 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700692
693 // re-arm global alert
694 registerGlobalAlert();
695 }
696
697 /**
698 * Update {@link NetworkStatsRecorder} and {@link #mGlobalAlertBytes} to
699 * reflect current {@link #mPersistThreshold} value. Always defers to
Jeff Sharkey625239a2012-09-26 22:03:49 -0700700 * {@link Global} values when defined.
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700701 */
702 private void updatePersistThresholds() {
703 mDevRecorder.setPersistThreshold(mSettings.getDevPersistBytes(mPersistThreshold));
704 mXtRecorder.setPersistThreshold(mSettings.getXtPersistBytes(mPersistThreshold));
705 mUidRecorder.setPersistThreshold(mSettings.getUidPersistBytes(mPersistThreshold));
706 mUidTagRecorder.setPersistThreshold(mSettings.getUidTagPersistBytes(mPersistThreshold));
707 mGlobalAlertBytes = mSettings.getGlobalAlertBytes(mPersistThreshold);
708 }
709
Jeff Sharkey75279902011-05-24 18:39:45 -0700710 /**
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700711 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey75279902011-05-24 18:39:45 -0700712 * interfaces. Used to associate {@link TelephonyManager#getSubscriberId()}
713 * with mobile interfaces.
714 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700715 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey75279902011-05-24 18:39:45 -0700716 @Override
717 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700718 // on background handler thread, and verified CONNECTIVITY_INTERNAL
719 // permission above.
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700720 updateIfaces();
Jeff Sharkey75279902011-05-24 18:39:45 -0700721 }
722 };
723
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700724 /**
725 * Receiver that watches for {@link Tethering} to claim interface pairs.
726 */
727 private BroadcastReceiver mTetherReceiver = new BroadcastReceiver() {
728 @Override
729 public void onReceive(Context context, Intent intent) {
730 // on background handler thread, and verified CONNECTIVITY_INTERNAL
731 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700732 performPoll(FLAG_PERSIST_NETWORK);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700733 }
734 };
735
Jeff Sharkey75279902011-05-24 18:39:45 -0700736 private BroadcastReceiver mPollReceiver = new BroadcastReceiver() {
737 @Override
738 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700739 // on background handler thread, and verified UPDATE_DEVICE_STATS
740 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700741 performPoll(FLAG_PERSIST_ALL);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700742
743 // verify that we're watching global alert
744 registerGlobalAlert();
Jeff Sharkey75279902011-05-24 18:39:45 -0700745 }
746 };
747
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700748 private BroadcastReceiver mRemovedReceiver = new BroadcastReceiver() {
749 @Override
750 public void onReceive(Context context, Intent intent) {
751 // on background handler thread, and UID_REMOVED is protected
752 // broadcast.
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700753
754 final int uid = intent.getIntExtra(EXTRA_UID, -1);
755 if (uid == -1) return;
756
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700757 synchronized (mStatsLock) {
Jeff Sharkey62489262011-07-17 12:53:28 -0700758 mWakeLock.acquire();
759 try {
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700760 removeUidsLocked(uid);
761 } finally {
762 mWakeLock.release();
763 }
764 }
765 }
766 };
767
768 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
769 @Override
770 public void onReceive(Context context, Intent intent) {
771 // On background handler thread, and USER_REMOVED is protected
772 // broadcast.
773
774 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
775 if (userId == -1) return;
776
777 synchronized (mStatsLock) {
778 mWakeLock.acquire();
779 try {
780 removeUserLocked(userId);
Jeff Sharkey62489262011-07-17 12:53:28 -0700781 } finally {
782 mWakeLock.release();
783 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700784 }
785 }
786 };
787
Jeff Sharkey75279902011-05-24 18:39:45 -0700788 private BroadcastReceiver mShutdownReceiver = new BroadcastReceiver() {
789 @Override
790 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700791 // SHUTDOWN is protected broadcast.
Jeff Sharkey75279902011-05-24 18:39:45 -0700792 synchronized (mStatsLock) {
Jeff Sharkey3f391352011-06-05 17:42:53 -0700793 shutdownLocked();
Jeff Sharkey75279902011-05-24 18:39:45 -0700794 }
795 }
796 };
797
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700798 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700799 * Observer that watches for {@link INetworkManagementService} alerts.
800 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700801 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700802 @Override
803 public void limitReached(String limitName, String iface) {
804 // only someone like NMS should be calling us
805 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
806
807 if (LIMIT_GLOBAL_ALERT.equals(limitName)) {
808 // kick off background poll to collect network stats; UID stats
809 // are handled during normal polling interval.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700810 final int flags = FLAG_PERSIST_NETWORK;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700811 mHandler.obtainMessage(MSG_PERFORM_POLL, flags, 0).sendToTarget();
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700812
813 // re-arm global alert for next update
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -0800814 mHandler.obtainMessage(MSG_REGISTER_GLOBAL_ALERT).sendToTarget();
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700815 }
816 }
817 };
818
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700819 private int mLastPhoneState = TelephonyManager.DATA_UNKNOWN;
820 private int mLastPhoneNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
821
822 /**
823 * Receiver that watches for {@link TelephonyManager} changes, such as
824 * transitioning between network types.
825 */
826 private PhoneStateListener mPhoneListener = new PhoneStateListener() {
827 @Override
828 public void onDataConnectionStateChanged(int state, int networkType) {
829 final boolean stateChanged = state != mLastPhoneState;
830 final boolean networkTypeChanged = networkType != mLastPhoneNetworkType;
831
832 if (networkTypeChanged && !stateChanged) {
833 // networkType changed without a state change, which means we
834 // need to roll our own update. delay long enough for
835 // ConnectivityManager to process.
836 // TODO: add direct event to ConnectivityService instead of
837 // relying on this delay.
838 if (LOGV) Slog.v(TAG, "triggering delayed updateIfaces()");
839 mHandler.sendMessageDelayed(
840 mHandler.obtainMessage(MSG_UPDATE_IFACES), SECOND_IN_MILLIS);
841 }
842
843 mLastPhoneState = state;
844 mLastPhoneNetworkType = networkType;
845 }
846 };
847
848 private void updateIfaces() {
849 synchronized (mStatsLock) {
850 mWakeLock.acquire();
851 try {
852 updateIfacesLocked();
853 } finally {
854 mWakeLock.release();
855 }
856 }
857 }
858
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700859 /**
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700860 * Inspect all current {@link NetworkState} to derive mapping from {@code
861 * iface} to {@link NetworkStatsHistory}. When multiple {@link NetworkInfo}
862 * are active on a single {@code iface}, they are combined under a single
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700863 * {@link NetworkIdentitySet}.
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700864 */
865 private void updateIfacesLocked() {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800866 if (!mSystemReady) return;
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700867 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700868
869 // take one last stats snapshot before updating iface mapping. this
870 // isn't perfect, since the kernel may already be counting traffic from
871 // the updated network.
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700872
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700873 // poll, but only persist network stats to keep codepath fast. UID stats
874 // will be persisted during next alarm poll event.
875 performPollLocked(FLAG_PERSIST_NETWORK);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700876
877 final NetworkState[] states;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800878 final LinkProperties activeLink;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700879 try {
880 states = mConnManager.getAllNetworkState();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800881 activeLink = mConnManager.getActiveLinkProperties();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700882 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700883 // ignored; service lives in system_server
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700884 return;
885 }
886
Jeff Sharkey63abc372012-01-11 18:38:16 -0800887 mActiveIface = activeLink != null ? activeLink.getInterfaceName() : null;
888
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700889 // rebuild active interfaces based on connected networks
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700890 mActiveIfaces.clear();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700891
892 for (NetworkState state : states) {
893 if (state.networkInfo.isConnected()) {
894 // collect networks under their parent interfaces
895 final String iface = state.linkProperties.getInterfaceName();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700896
897 NetworkIdentitySet ident = mActiveIfaces.get(iface);
898 if (ident == null) {
899 ident = new NetworkIdentitySet();
900 mActiveIfaces.put(iface, ident);
901 }
902
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700903 ident.add(NetworkIdentity.buildNetworkIdentity(mContext, state));
Jeff Sharkey234766a2012-04-10 19:48:07 -0700904
905 // remember any ifaces associated with mobile networks
Jeff Sharkey6a328af2012-11-30 17:49:39 -0800906 if (isNetworkTypeMobile(state.networkInfo.getType()) && iface != null) {
Jeff Sharkey234766a2012-04-10 19:48:07 -0700907 if (!contains(mMobileIfaces, iface)) {
908 mMobileIfaces = appendElement(String.class, mMobileIfaces, iface);
909 }
910 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700911 }
912 }
913 }
914
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700915 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700916 * Bootstrap initial stats snapshot, usually during {@link #systemReady()}
917 * so we have baseline values without double-counting.
918 */
Jeff Sharkey63abc372012-01-11 18:38:16 -0800919 private void bootstrapStatsLocked() {
920 final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
921 : System.currentTimeMillis();
922
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700923 try {
Jeff Sharkey63abc372012-01-11 18:38:16 -0800924 // snapshot and record current counters; read UID stats first to
925 // avoid overcounting dev stats.
926 final NetworkStats uidSnapshot = getNetworkStatsUidDetail();
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700927 final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
928 final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800929
930 mDevRecorder.recordSnapshotLocked(devSnapshot, mActiveIfaces, currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700931 mXtRecorder.recordSnapshotLocked(xtSnapshot, mActiveIfaces, currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800932 mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
933 mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
934
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700935 } catch (IllegalStateException e) {
936 Slog.w(TAG, "problem reading network stats: " + e);
937 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700938 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700939 }
940 }
941
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700942 private void performPoll(int flags) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700943 synchronized (mStatsLock) {
944 mWakeLock.acquire();
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800945
946 // try refreshing time source when stale
947 if (mTime.getCacheAge() > mSettings.getTimeCacheMaxAge()) {
948 mTime.forceRefresh();
949 }
950
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700951 try {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700952 performPollLocked(flags);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700953 } finally {
954 mWakeLock.release();
955 }
956 }
957 }
958
959 /**
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700960 * Periodic poll operation, reading current statistics and recording into
961 * {@link NetworkStatsHistory}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700962 */
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700963 private void performPollLocked(int flags) {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800964 if (!mSystemReady) return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700965 if (LOGV) Slog.v(TAG, "performPollLocked(flags=0x" + Integer.toHexString(flags) + ")");
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800966
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700967 final long startRealtime = SystemClock.elapsedRealtime();
Jeff Sharkey75279902011-05-24 18:39:45 -0700968
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700969 final boolean persistNetwork = (flags & FLAG_PERSIST_NETWORK) != 0;
970 final boolean persistUid = (flags & FLAG_PERSIST_UID) != 0;
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700971 final boolean persistForce = (flags & FLAG_PERSIST_FORCE) != 0;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700972
Jeff Sharkey75279902011-05-24 18:39:45 -0700973 // TODO: consider marking "untrusted" times in historical stats
974 final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
975 : System.currentTimeMillis();
976
Jeff Sharkey75279902011-05-24 18:39:45 -0700977 try {
Jeff Sharkey63abc372012-01-11 18:38:16 -0800978 // snapshot and record current counters; read UID stats first to
979 // avoid overcounting dev stats.
980 final NetworkStats uidSnapshot = getNetworkStatsUidDetail();
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700981 final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
982 final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700983
Jeff Sharkey63abc372012-01-11 18:38:16 -0800984 mDevRecorder.recordSnapshotLocked(devSnapshot, mActiveIfaces, currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700985 mXtRecorder.recordSnapshotLocked(xtSnapshot, mActiveIfaces, currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800986 mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
987 mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700988
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700989 } catch (IllegalStateException e) {
990 Log.wtf(TAG, "problem reading network stats", e);
Jeff Sharkey905b5892011-09-30 15:19:49 -0700991 return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700992 } catch (RemoteException e) {
993 // ignored; service lives in system_server
Jeff Sharkey905b5892011-09-30 15:19:49 -0700994 return;
995 }
996
Jeff Sharkey63abc372012-01-11 18:38:16 -0800997 // persist any pending data depending on requested flags
998 if (persistForce) {
999 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001000 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001001 mUidRecorder.forcePersistLocked(currentTime);
1002 mUidTagRecorder.forcePersistLocked(currentTime);
1003 } else {
1004 if (persistNetwork) {
1005 mDevRecorder.maybePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001006 mXtRecorder.maybePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001007 }
1008 if (persistUid) {
1009 mUidRecorder.maybePersistLocked(currentTime);
1010 mUidTagRecorder.maybePersistLocked(currentTime);
1011 }
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001012 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001013
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001014 if (LOGV) {
1015 final long duration = SystemClock.elapsedRealtime() - startRealtime;
1016 Slog.v(TAG, "performPollLocked() took " + duration + "ms");
1017 }
1018
Jeff Sharkey63abc372012-01-11 18:38:16 -08001019 if (mSettings.getSampleEnabled()) {
Jeff Sharkey905b5892011-09-30 15:19:49 -07001020 // sample stats after each full poll
Jeff Sharkey63abc372012-01-11 18:38:16 -08001021 performSampleLocked();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001022 }
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001023
Jeff Sharkey497e4432011-06-14 17:27:29 -07001024 // finally, dispatch updated event to any listeners
1025 final Intent updatedIntent = new Intent(ACTION_NETWORK_STATS_UPDATED);
1026 updatedIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001027 mContext.sendBroadcastAsUser(updatedIntent, UserHandle.ALL,
1028 READ_NETWORK_USAGE_HISTORY);
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001029 }
1030
1031 /**
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001032 * Sample recent statistics summary into {@link EventLog}.
1033 */
Jeff Sharkey63abc372012-01-11 18:38:16 -08001034 private void performSampleLocked() {
1035 // TODO: migrate trustedtime fixes to separate binary log events
Jeff Sharkey905b5892011-09-30 15:19:49 -07001036 final long trustedTime = mTime.hasCache() ? mTime.currentTimeMillis() : -1;
1037
Jeff Sharkey63abc372012-01-11 18:38:16 -08001038 NetworkTemplate template;
1039 NetworkStats.Entry devTotal;
1040 NetworkStats.Entry xtTotal;
1041 NetworkStats.Entry uidTotal;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001042
1043 // collect mobile sample
Jeff Sharkey234766a2012-04-10 19:48:07 -07001044 template = buildTemplateMobileWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001045 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001046 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001047 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001048
Jeff Sharkey905b5892011-09-30 15:19:49 -07001049 EventLogTags.writeNetstatsMobileSample(
1050 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1051 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1052 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey63abc372012-01-11 18:38:16 -08001053 trustedTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001054
1055 // collect wifi sample
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001056 template = buildTemplateWifiWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001057 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001058 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001059 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
1060
Jeff Sharkey905b5892011-09-30 15:19:49 -07001061 EventLogTags.writeNetstatsWifiSample(
1062 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1063 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1064 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey63abc372012-01-11 18:38:16 -08001065 trustedTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001066 }
1067
1068 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001069 * Clean up {@link #mUidRecorder} after UID is removed.
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001070 */
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001071 private void removeUidsLocked(int... uids) {
1072 if (LOGV) Slog.v(TAG, "removeUidsLocked() for UIDs " + Arrays.toString(uids));
1073
1074 // Perform one last poll before removing
Jeff Sharkey163e6442011-10-31 16:37:52 -07001075 performPollLocked(FLAG_PERSIST_ALL);
1076
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001077 mUidRecorder.removeUidsLocked(uids);
1078 mUidTagRecorder.removeUidsLocked(uids);
Jeff Sharkey163e6442011-10-31 16:37:52 -07001079
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001080 // Clear kernel stats associated with UID
1081 for (int uid : uids) {
1082 resetKernelUidStats(uid);
1083 }
1084 }
1085
1086 /**
1087 * Clean up {@link #mUidRecorder} after user is removed.
1088 */
1089 private void removeUserLocked(int userId) {
1090 if (LOGV) Slog.v(TAG, "removeUserLocked() for userId=" + userId);
1091
1092 // Build list of UIDs that we should clean up
1093 int[] uids = new int[0];
1094 final List<ApplicationInfo> apps = mContext.getPackageManager().getInstalledApplications(
1095 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1096 for (ApplicationInfo app : apps) {
1097 final int uid = UserHandle.getUid(userId, app.uid);
1098 uids = ArrayUtils.appendInt(uids, uid);
1099 }
1100
1101 removeUidsLocked(uids);
Jeff Sharkey75279902011-05-24 18:39:45 -07001102 }
1103
1104 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001105 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001106 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1107
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001108 final HashSet<String> argSet = new HashSet<String>();
1109 for (String arg : args) {
1110 argSet.add(arg);
Jeff Sharkey75279902011-05-24 18:39:45 -07001111 }
1112
Jeff Sharkey706498d2012-02-06 17:35:07 -08001113 // usage: dumpsys netstats --full --uid --tag --poll --checkin
Jeff Sharkey63abc372012-01-11 18:38:16 -08001114 final boolean poll = argSet.contains("--poll") || argSet.contains("poll");
Jeff Sharkey706498d2012-02-06 17:35:07 -08001115 final boolean checkin = argSet.contains("--checkin");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001116 final boolean fullHistory = argSet.contains("--full") || argSet.contains("full");
1117 final boolean includeUid = argSet.contains("--uid") || argSet.contains("detail");
1118 final boolean includeTag = argSet.contains("--tag") || argSet.contains("detail");
1119
1120 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkey350083e2011-06-29 10:45:16 -07001121
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001122 synchronized (mStatsLock) {
Jeff Sharkey63abc372012-01-11 18:38:16 -08001123 if (poll) {
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001124 performPollLocked(FLAG_PERSIST_ALL | FLAG_PERSIST_FORCE);
Jeff Sharkey3f391352011-06-05 17:42:53 -07001125 pw.println("Forced poll");
1126 return;
1127 }
1128
Jeff Sharkey706498d2012-02-06 17:35:07 -08001129 if (checkin) {
1130 // list current stats files to verify rotation
1131 pw.println("Current files:");
1132 pw.increaseIndent();
1133 for (String file : mBaseDir.list()) {
1134 pw.println(file);
1135 }
1136 pw.decreaseIndent();
1137 return;
1138 }
1139
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001140 pw.println("Active interfaces:");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001141 pw.increaseIndent();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001142 for (String iface : mActiveIfaces.keySet()) {
1143 final NetworkIdentitySet ident = mActiveIfaces.get(iface);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001144 pw.print("iface="); pw.print(iface);
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001145 pw.print(" ident="); pw.println(ident.toString());
1146 }
Jeff Sharkey63abc372012-01-11 18:38:16 -08001147 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001148
Jeff Sharkey63abc372012-01-11 18:38:16 -08001149 pw.println("Dev stats:");
1150 pw.increaseIndent();
1151 mDevRecorder.dumpLocked(pw, fullHistory);
1152 pw.decreaseIndent();
1153
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001154 pw.println("Xt stats:");
1155 pw.increaseIndent();
1156 mXtRecorder.dumpLocked(pw, fullHistory);
1157 pw.decreaseIndent();
1158
Jeff Sharkey63abc372012-01-11 18:38:16 -08001159 if (includeUid) {
1160 pw.println("UID stats:");
1161 pw.increaseIndent();
1162 mUidRecorder.dumpLocked(pw, fullHistory);
1163 pw.decreaseIndent();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001164 }
1165
Jeff Sharkey63abc372012-01-11 18:38:16 -08001166 if (includeTag) {
1167 pw.println("UID tag stats:");
1168 pw.increaseIndent();
1169 mUidTagRecorder.dumpLocked(pw, fullHistory);
1170 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001171 }
1172 }
1173 }
1174
1175 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001176 * Return snapshot of current UID statistics, including any
1177 * {@link TrafficStats#UID_TETHERING} and {@link #mUidOperations} values.
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001178 */
Jeff Sharkey63abc372012-01-11 18:38:16 -08001179 private NetworkStats getNetworkStatsUidDetail() throws RemoteException {
1180 final NetworkStats uidSnapshot = mNetworkManager.getNetworkStatsUidDetail(UID_ALL);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001181
Jeff Sharkey63abc372012-01-11 18:38:16 -08001182 // fold tethering stats and operations into uid snapshot
1183 final NetworkStats tetherSnapshot = getNetworkStatsTethering();
1184 uidSnapshot.combineAllValues(tetherSnapshot);
1185 uidSnapshot.combineAllValues(mUidOperations);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001186
Jeff Sharkey63abc372012-01-11 18:38:16 -08001187 return uidSnapshot;
Jeff Sharkey75279902011-05-24 18:39:45 -07001188 }
1189
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001190 /**
1191 * Return snapshot of current tethering statistics. Will return empty
1192 * {@link NetworkStats} if any problems are encountered.
1193 */
1194 private NetworkStats getNetworkStatsTethering() throws RemoteException {
1195 try {
1196 final String[] tetheredIfacePairs = mConnManager.getTetheredIfacePairs();
1197 return mNetworkManager.getNetworkStatsTethering(tetheredIfacePairs);
1198 } catch (IllegalStateException e) {
1199 Log.wtf(TAG, "problem reading network stats", e);
1200 return new NetworkStats(0L, 10);
1201 }
1202 }
1203
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001204 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001205 @Override
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001206 public boolean handleMessage(Message msg) {
1207 switch (msg.what) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001208 case MSG_PERFORM_POLL: {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001209 final int flags = msg.arg1;
1210 performPoll(flags);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001211 return true;
1212 }
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001213 case MSG_UPDATE_IFACES: {
1214 updateIfaces();
1215 return true;
1216 }
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001217 case MSG_REGISTER_GLOBAL_ALERT: {
1218 registerGlobalAlert();
1219 return true;
1220 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001221 default: {
1222 return false;
1223 }
1224 }
1225 }
1226 };
1227
Jeff Sharkey4190a042012-04-21 15:36:48 -07001228 private void assertBandwidthControlEnabled() {
1229 if (!isBandwidthControlEnabled()) {
1230 throw new IllegalStateException("Bandwidth module disabled");
1231 }
1232 }
1233
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001234 private boolean isBandwidthControlEnabled() {
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001235 final long token = Binder.clearCallingIdentity();
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001236 try {
1237 return mNetworkManager.isBandwidthControlEnabled();
1238 } catch (RemoteException e) {
1239 // ignored; service lives in system_server
1240 return false;
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001241 } finally {
1242 Binder.restoreCallingIdentity(token);
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001243 }
1244 }
1245
Jeff Sharkey63abc372012-01-11 18:38:16 -08001246 private class DropBoxNonMonotonicObserver implements NonMonotonicObserver<String> {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001247 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001248 public void foundNonMonotonic(NetworkStats left, int leftIndex, NetworkStats right,
1249 int rightIndex, String cookie) {
1250 Log.w(TAG, "found non-monotonic values; saving to dropbox");
1251
1252 // record error for debugging
1253 final StringBuilder builder = new StringBuilder();
1254 builder.append("found non-monotonic " + cookie + " values at left[" + leftIndex
1255 + "] - right[" + rightIndex + "]\n");
1256 builder.append("left=").append(left).append('\n');
1257 builder.append("right=").append(right).append('\n');
1258
1259 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
1260 Context.DROPBOX_SERVICE);
1261 dropBox.addText(TAG_NETSTATS_ERROR, builder.toString());
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001262 }
1263 }
1264
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001265 /**
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001266 * Default external settings that read from
Jeff Sharkey625239a2012-09-26 22:03:49 -07001267 * {@link android.provider.Settings.Global}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001268 */
1269 private static class DefaultNetworkStatsSettings implements NetworkStatsSettings {
1270 private final ContentResolver mResolver;
1271
1272 public DefaultNetworkStatsSettings(Context context) {
1273 mResolver = checkNotNull(context.getContentResolver());
1274 // TODO: adjust these timings for production builds
1275 }
1276
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001277 private long getGlobalLong(String name, long def) {
1278 return Settings.Global.getLong(mResolver, name, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001279 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001280 private boolean getGlobalBoolean(String name, boolean def) {
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001281 final int defInt = def ? 1 : 0;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001282 return Settings.Global.getInt(mResolver, name, defInt) != 0;
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001283 }
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001284
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001285 @Override
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001286 public long getPollInterval() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001287 return getGlobalLong(NETSTATS_POLL_INTERVAL, 30 * MINUTE_IN_MILLIS);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001288 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001289 @Override
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001290 public long getTimeCacheMaxAge() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001291 return getGlobalLong(NETSTATS_TIME_CACHE_MAX_AGE, DAY_IN_MILLIS);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001292 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001293 @Override
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001294 public long getGlobalAlertBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001295 return getGlobalLong(NETSTATS_GLOBAL_ALERT_BYTES, def);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001296 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001297 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001298 public boolean getSampleEnabled() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001299 return getGlobalBoolean(NETSTATS_SAMPLE_ENABLED, true);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001300 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001301 @Override
Jeff Sharkey70c70532012-05-16 14:51:19 -07001302 public boolean getReportXtOverDev() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001303 return getGlobalBoolean(NETSTATS_REPORT_XT_OVER_DEV, true);
Jeff Sharkey70c70532012-05-16 14:51:19 -07001304 }
1305 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001306 public Config getDevConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001307 return new Config(getGlobalLong(NETSTATS_DEV_BUCKET_DURATION, HOUR_IN_MILLIS),
1308 getGlobalLong(NETSTATS_DEV_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1309 getGlobalLong(NETSTATS_DEV_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001310 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001311 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001312 public Config getXtConfig() {
1313 return getDevConfig();
1314 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001315 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001316 public Config getUidConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001317 return new Config(getGlobalLong(NETSTATS_UID_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1318 getGlobalLong(NETSTATS_UID_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1319 getGlobalLong(NETSTATS_UID_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001320 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001321 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001322 public Config getUidTagConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001323 return new Config(getGlobalLong(NETSTATS_UID_TAG_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1324 getGlobalLong(NETSTATS_UID_TAG_ROTATE_AGE, 5 * DAY_IN_MILLIS),
1325 getGlobalLong(NETSTATS_UID_TAG_DELETE_AGE, 15 * DAY_IN_MILLIS));
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001326 }
1327 @Override
1328 public long getDevPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001329 return getGlobalLong(NETSTATS_DEV_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001330 }
1331 @Override
1332 public long getXtPersistBytes(long def) {
1333 return getDevPersistBytes(def);
1334 }
1335 @Override
1336 public long getUidPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001337 return getGlobalLong(NETSTATS_UID_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001338 }
1339 @Override
1340 public long getUidTagPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001341 return getGlobalLong(NETSTATS_UID_TAG_PERSIST_BYTES, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001342 }
1343 }
Jeff Sharkey75279902011-05-24 18:39:45 -07001344}