blob: 05eeb36195eeab0e96d6388d0882c927d5290f61 [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;
Jeff Sharkey75279902011-05-24 18:39:45 -070099import android.os.INetworkManagementService;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700100import android.os.Message;
Jeff Sharkey62489262011-07-17 12:53:28 -0700101import android.os.PowerManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700102import android.os.RemoteException;
103import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700104import android.os.UserHandle;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700105import android.provider.Settings;
Jeff Sharkey625239a2012-09-26 22:03:49 -0700106import android.provider.Settings.Global;
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700107import android.telephony.PhoneStateListener;
Jeff Sharkey75279902011-05-24 18:39:45 -0700108import android.telephony.TelephonyManager;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -0700109import android.util.EventLog;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700110import android.util.Log;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700111import android.util.MathUtils;
Jeff Sharkey75279902011-05-24 18:39:45 -0700112import android.util.NtpTrustedTime;
113import android.util.Slog;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700114import android.util.SparseIntArray;
Jeff Sharkey75279902011-05-24 18:39:45 -0700115import android.util.TrustedTime;
116
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800117import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700118import com.android.internal.util.ArrayUtils;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800119import com.android.internal.util.FileRotator;
120import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -0700121import com.android.server.EventLogTags;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700122import com.android.server.IoThread;
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;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700157 private final AlarmManager mAlarmManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700158 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 Handler mHandler;
244
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800245 private boolean mSystemReady;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700246 private long mPersistThreshold = 2 * MB_IN_BYTES;
247 private long mGlobalAlertBytes;
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800248
Jeff Sharkey75279902011-05-24 18:39:45 -0700249 public NetworkStatsService(
250 Context context, INetworkManagementService networkManager, IAlarmManager alarmManager) {
Jeff Sharkey104344e2011-07-10 14:20:41 -0700251 this(context, networkManager, alarmManager, NtpTrustedTime.getInstance(context),
Jeff Sharkey63abc372012-01-11 18:38:16 -0800252 getDefaultSystemDir(), new DefaultNetworkStatsSettings(context));
Jeff Sharkey3f391352011-06-05 17:42:53 -0700253 }
254
Jeff Sharkey63abc372012-01-11 18:38:16 -0800255 private static File getDefaultSystemDir() {
Jeff Sharkey3f391352011-06-05 17:42:53 -0700256 return new File(Environment.getDataDirectory(), "system");
Jeff Sharkey75279902011-05-24 18:39:45 -0700257 }
258
259 public NetworkStatsService(Context context, INetworkManagementService networkManager,
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700260 IAlarmManager alarmManager, TrustedTime time, File systemDir,
261 NetworkStatsSettings settings) {
Jeff Sharkey75279902011-05-24 18:39:45 -0700262 mContext = checkNotNull(context, "missing Context");
263 mNetworkManager = checkNotNull(networkManager, "missing INetworkManagementService");
Jeff Sharkey75279902011-05-24 18:39:45 -0700264 mTime = checkNotNull(time, "missing TrustedTime");
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700265 mTeleManager = checkNotNull(TelephonyManager.getDefault(), "missing TelephonyManager");
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700266 mSettings = checkNotNull(settings, "missing NetworkStatsSettings");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700267 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Jeff Sharkey75279902011-05-24 18:39:45 -0700268
Jeff Sharkey62489262011-07-17 12:53:28 -0700269 final PowerManager powerManager = (PowerManager) context.getSystemService(
270 Context.POWER_SERVICE);
271 mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
272
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700273 mHandler = new Handler(IoThread.get().getLooper(), mHandlerCallback);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700274
Jeff Sharkey63abc372012-01-11 18:38:16 -0800275 mSystemDir = checkNotNull(systemDir);
276 mBaseDir = new File(systemDir, "netstats");
277 mBaseDir.mkdirs();
Jeff Sharkey75279902011-05-24 18:39:45 -0700278 }
279
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700280 public void bindConnectivityManager(IConnectivityManager connManager) {
281 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
282 }
283
Jeff Sharkey75279902011-05-24 18:39:45 -0700284 public void systemReady() {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800285 mSystemReady = true;
286
Jeff Sharkey418d12d2011-12-13 15:38:03 -0800287 if (!isBandwidthControlEnabled()) {
288 Slog.w(TAG, "bandwidth controls disabled, unable to track stats");
289 return;
290 }
291
Jeff Sharkey63abc372012-01-11 18:38:16 -0800292 // create data recorders along with historical rotators
293 mDevRecorder = buildRecorder(PREFIX_DEV, mSettings.getDevConfig(), false);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700294 mXtRecorder = buildRecorder(PREFIX_XT, mSettings.getXtConfig(), false);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800295 mUidRecorder = buildRecorder(PREFIX_UID, mSettings.getUidConfig(), false);
296 mUidTagRecorder = buildRecorder(PREFIX_UID_TAG, mSettings.getUidTagConfig(), true);
Jeff Sharkey75279902011-05-24 18:39:45 -0700297
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700298 updatePersistThresholds();
299
Jeff Sharkey63abc372012-01-11 18:38:16 -0800300 synchronized (mStatsLock) {
301 // upgrade any legacy stats, migrating them to rotated files
302 maybeUpgradeLegacyStatsLocked();
303
304 // read historical network stats from disk, since policy service
305 // might need them right away.
306 mDevStatsCached = mDevRecorder.getOrLoadCompleteLocked();
Jeff Sharkey70c70532012-05-16 14:51:19 -0700307 mXtStatsCached = mXtRecorder.getOrLoadCompleteLocked();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800308
309 // bootstrap initial stats to prevent double-counting later
310 bootstrapStatsLocked();
311 }
Jeff Sharkey3359aca2011-11-08 18:08:48 -0800312
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700313 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700314 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700315 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
Jeff Sharkey75279902011-05-24 18:39:45 -0700316
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700317 // watch for tethering changes
318 final IntentFilter tetherFilter = new IntentFilter(ACTION_TETHER_STATE_CHANGED);
319 mContext.registerReceiver(mTetherReceiver, tetherFilter, CONNECTIVITY_INTERNAL, mHandler);
320
Jeff Sharkey75279902011-05-24 18:39:45 -0700321 // listen for periodic polling events
322 final IntentFilter pollFilter = new IntentFilter(ACTION_NETWORK_STATS_POLL);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700323 mContext.registerReceiver(mPollReceiver, pollFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
Jeff Sharkey75279902011-05-24 18:39:45 -0700324
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700325 // listen for uid removal to clean stats
326 final IntentFilter removedFilter = new IntentFilter(ACTION_UID_REMOVED);
327 mContext.registerReceiver(mRemovedReceiver, removedFilter, null, mHandler);
328
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700329 // listen for user changes to clean stats
330 final IntentFilter userFilter = new IntentFilter(ACTION_USER_REMOVED);
331 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
332
Jeff Sharkey75279902011-05-24 18:39:45 -0700333 // persist stats during clean shutdown
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700334 final IntentFilter shutdownFilter = new IntentFilter(ACTION_SHUTDOWN);
335 mContext.registerReceiver(mShutdownReceiver, shutdownFilter);
Jeff Sharkey75279902011-05-24 18:39:45 -0700336
337 try {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700338 mNetworkManager.registerObserver(mAlertObserver);
Jeff Sharkey75279902011-05-24 18:39:45 -0700339 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700340 // ignored; service lives in system_server
Jeff Sharkey75279902011-05-24 18:39:45 -0700341 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700342
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700343 // watch for networkType changes that aren't broadcast through
344 // CONNECTIVITY_ACTION_IMMEDIATE above.
Jeff Sharkeyd4dd7712012-03-16 11:11:54 -0700345 if (!COMBINE_SUBTYPE_ENABLED) {
346 mTeleManager.listen(mPhoneListener, LISTEN_DATA_CONNECTION_STATE);
347 }
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700348
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700349 registerPollAlarmLocked();
350 registerGlobalAlert();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800351 }
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700352
Jeff Sharkey63abc372012-01-11 18:38:16 -0800353 private NetworkStatsRecorder buildRecorder(
354 String prefix, NetworkStatsSettings.Config config, boolean includeTags) {
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700355 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
356 Context.DROPBOX_SERVICE);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700357 return new NetworkStatsRecorder(new FileRotator(
358 mBaseDir, prefix, config.rotateAgeMillis, config.deleteAgeMillis),
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700359 mNonMonotonicObserver, dropBox, prefix, config.bucketDuration, includeTags);
Jeff Sharkey75279902011-05-24 18:39:45 -0700360 }
361
Jeff Sharkey3f391352011-06-05 17:42:53 -0700362 private void shutdownLocked() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700363 mContext.unregisterReceiver(mConnReceiver);
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700364 mContext.unregisterReceiver(mTetherReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700365 mContext.unregisterReceiver(mPollReceiver);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700366 mContext.unregisterReceiver(mRemovedReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700367 mContext.unregisterReceiver(mShutdownReceiver);
368
Jeff Sharkeyd4dd7712012-03-16 11:11:54 -0700369 if (!COMBINE_SUBTYPE_ENABLED) {
370 mTeleManager.listen(mPhoneListener, LISTEN_NONE);
371 }
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700372
Jeff Sharkey63abc372012-01-11 18:38:16 -0800373 final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
374 : System.currentTimeMillis();
375
376 // persist any pending stats
377 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700378 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800379 mUidRecorder.forcePersistLocked(currentTime);
380 mUidTagRecorder.forcePersistLocked(currentTime);
381
382 mDevRecorder = null;
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700383 mXtRecorder = null;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800384 mUidRecorder = null;
385 mUidTagRecorder = null;
386
387 mDevStatsCached = null;
Jeff Sharkey70c70532012-05-16 14:51:19 -0700388 mXtStatsCached = null;
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800389
390 mSystemReady = false;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800391 }
392
393 private void maybeUpgradeLegacyStatsLocked() {
394 File file;
395 try {
396 file = new File(mSystemDir, "netstats.bin");
397 if (file.exists()) {
398 mDevRecorder.importLegacyNetworkLocked(file);
399 file.delete();
400 }
401
402 file = new File(mSystemDir, "netstats_xt.bin");
403 if (file.exists()) {
404 file.delete();
405 }
406
407 file = new File(mSystemDir, "netstats_uid.bin");
408 if (file.exists()) {
409 mUidRecorder.importLegacyUidLocked(file);
410 mUidTagRecorder.importLegacyUidLocked(file);
411 file.delete();
412 }
413 } catch (IOException e) {
414 Log.wtf(TAG, "problem during legacy upgrade", e);
Jeff Sharkeyc506ff62011-11-17 11:59:29 -0800415 }
Jeff Sharkey3f391352011-06-05 17:42:53 -0700416 }
417
Jeff Sharkey75279902011-05-24 18:39:45 -0700418 /**
419 * Clear any existing {@link #ACTION_NETWORK_STATS_POLL} alarms, and
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700420 * reschedule based on current {@link NetworkStatsSettings#getPollInterval()}.
Jeff Sharkey75279902011-05-24 18:39:45 -0700421 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700422 private void registerPollAlarmLocked() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700423 if (mPollIntent != null) {
424 mAlarmManager.cancel(mPollIntent);
Jeff Sharkey75279902011-05-24 18:39:45 -0700425 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700426
427 mPollIntent = PendingIntent.getBroadcast(
428 mContext, 0, new Intent(ACTION_NETWORK_STATS_POLL), 0);
429
430 final long currentRealtime = SystemClock.elapsedRealtime();
431 mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, currentRealtime,
432 mSettings.getPollInterval(), mPollIntent);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700433 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700434
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700435 /**
436 * Register for a global alert that is delivered through
437 * {@link INetworkManagementEventObserver} once a threshold amount of data
438 * has been transferred.
439 */
440 private void registerGlobalAlert() {
441 try {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700442 mNetworkManager.setGlobalAlert(mGlobalAlertBytes);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700443 } catch (IllegalStateException e) {
444 Slog.w(TAG, "problem registering for global alert: " + e);
445 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700446 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700447 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700448 }
449
450 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700451 public INetworkStatsSession openSession() {
452 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700453 assertBandwidthControlEnabled();
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700454
455 // return an IBinder which holds strong references to any loaded stats
456 // for its lifetime; when caller closes only weak references remain.
457
458 return new INetworkStatsSession.Stub() {
459 private NetworkStatsCollection mUidComplete;
460 private NetworkStatsCollection mUidTagComplete;
461
462 private NetworkStatsCollection getUidComplete() {
463 if (mUidComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700464 synchronized (mStatsLock) {
465 mUidComplete = mUidRecorder.getOrLoadCompleteLocked();
466 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700467 }
468 return mUidComplete;
469 }
470
471 private NetworkStatsCollection getUidTagComplete() {
472 if (mUidTagComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700473 synchronized (mStatsLock) {
474 mUidTagComplete = mUidTagRecorder.getOrLoadCompleteLocked();
475 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700476 }
477 return mUidTagComplete;
478 }
479
480 @Override
481 public NetworkStats getSummaryForNetwork(
482 NetworkTemplate template, long start, long end) {
Jeff Sharkey70c70532012-05-16 14:51:19 -0700483 return internalGetSummaryForNetwork(template, start, end);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700484 }
485
486 @Override
487 public NetworkStatsHistory getHistoryForNetwork(NetworkTemplate template, int fields) {
Jeff Sharkey70c70532012-05-16 14:51:19 -0700488 return internalGetHistoryForNetwork(template, fields);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700489 }
490
491 @Override
492 public NetworkStats getSummaryForAllUid(
493 NetworkTemplate template, long start, long end, boolean includeTags) {
494 final NetworkStats stats = getUidComplete().getSummary(template, start, end);
495 if (includeTags) {
496 final NetworkStats tagStats = getUidTagComplete()
497 .getSummary(template, start, end);
498 stats.combineAllValues(tagStats);
499 }
500 return stats;
501 }
502
503 @Override
504 public NetworkStatsHistory getHistoryForUid(
505 NetworkTemplate template, int uid, int set, int tag, int fields) {
506 if (tag == TAG_NONE) {
507 return getUidComplete().getHistory(template, uid, set, tag, fields);
508 } else {
509 return getUidTagComplete().getHistory(template, uid, set, tag, fields);
510 }
511 }
512
513 @Override
514 public void close() {
515 mUidComplete = null;
516 mUidTagComplete = null;
517 }
518 };
Jeff Sharkey905b5892011-09-30 15:19:49 -0700519 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700520
Jeff Sharkey70c70532012-05-16 14:51:19 -0700521 /**
522 * Return network summary, splicing between {@link #mDevStatsCached}
523 * and {@link #mXtStatsCached} when appropriate.
524 */
525 private NetworkStats internalGetSummaryForNetwork(
526 NetworkTemplate template, long start, long end) {
527 if (!mSettings.getReportXtOverDev()) {
528 // shortcut when XT reporting disabled
529 return mDevStatsCached.getSummary(template, start, end);
530 }
531
532 // splice stats between DEV and XT, switching over from DEV to XT at
533 // first atomic bucket.
534 final long firstAtomicBucket = mXtStatsCached.getFirstAtomicBucketMillis();
535 final NetworkStats dev = mDevStatsCached.getSummary(
536 template, Math.min(start, firstAtomicBucket), Math.min(end, firstAtomicBucket));
537 final NetworkStats xt = mXtStatsCached.getSummary(
538 template, Math.max(start, firstAtomicBucket), Math.max(end, firstAtomicBucket));
539
540 xt.combineAllValues(dev);
541 return xt;
542 }
543
544 /**
545 * Return network history, splicing between {@link #mDevStatsCached}
546 * and {@link #mXtStatsCached} when appropriate.
547 */
548 private NetworkStatsHistory internalGetHistoryForNetwork(NetworkTemplate template, int fields) {
549 if (!mSettings.getReportXtOverDev()) {
550 // shortcut when XT reporting disabled
551 return mDevStatsCached.getHistory(template, UID_ALL, SET_ALL, TAG_NONE, fields);
552 }
553
554 // splice stats between DEV and XT, switching over from DEV to XT at
555 // first atomic bucket.
556 final long firstAtomicBucket = mXtStatsCached.getFirstAtomicBucketMillis();
557 final NetworkStatsHistory dev = mDevStatsCached.getHistory(
558 template, UID_ALL, SET_ALL, TAG_NONE, fields, Long.MIN_VALUE, firstAtomicBucket);
559 final NetworkStatsHistory xt = mXtStatsCached.getHistory(
560 template, UID_ALL, SET_ALL, TAG_NONE, fields, firstAtomicBucket, Long.MAX_VALUE);
561
562 xt.recordEntireHistory(dev);
563 return xt;
564 }
565
Jeff Sharkey63abc372012-01-11 18:38:16 -0800566 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700567 public long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
568 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700569 assertBandwidthControlEnabled();
Jeff Sharkey70c70532012-05-16 14:51:19 -0700570 return internalGetSummaryForNetwork(template, start, end).getTotalBytes();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700571 }
572
Jeff Sharkey350083e2011-06-29 10:45:16 -0700573 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700574 public NetworkStats getDataLayerSnapshotForUid(int uid) throws RemoteException {
575 if (Binder.getCallingUid() != uid) {
576 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
577 }
Jeff Sharkey4190a042012-04-21 15:36:48 -0700578 assertBandwidthControlEnabled();
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700579
580 // TODO: switch to data layer stats once kernel exports
581 // for now, read network layer stats and flatten across all ifaces
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800582 final long token = Binder.clearCallingIdentity();
583 final NetworkStats networkLayer;
584 try {
585 networkLayer = mNetworkManager.getNetworkStatsUidDetail(uid);
586 } finally {
587 Binder.restoreCallingIdentity(token);
588 }
589
Jeff Sharkey21a54782012-04-09 10:27:55 -0700590 // splice in operation counts
591 networkLayer.spliceOperationsFrom(mUidOperations);
592
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700593 final NetworkStats dataLayer = new NetworkStats(
594 networkLayer.getElapsedRealtime(), networkLayer.size());
595
596 NetworkStats.Entry entry = null;
597 for (int i = 0; i < networkLayer.size(); i++) {
598 entry = networkLayer.getValues(i, entry);
599 entry.iface = IFACE_ALL;
600 dataLayer.combineValues(entry);
601 }
602
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700603 return dataLayer;
604 }
605
606 @Override
Jeff Sharkey234766a2012-04-10 19:48:07 -0700607 public String[] getMobileIfaces() {
608 return mMobileIfaces;
609 }
610
611 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700612 public void incrementOperationCount(int uid, int tag, int operationCount) {
613 if (Binder.getCallingUid() != uid) {
614 mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
615 }
616
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700617 if (operationCount < 0) {
618 throw new IllegalArgumentException("operation count can only be incremented");
619 }
620 if (tag == TAG_NONE) {
621 throw new IllegalArgumentException("operation count must have specific tag");
622 }
623
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700624 synchronized (mStatsLock) {
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700625 final int set = mActiveUidCounterSet.get(uid, SET_DEFAULT);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800626 mUidOperations.combineValues(
627 mActiveIface, uid, set, tag, 0L, 0L, 0L, 0L, operationCount);
628 mUidOperations.combineValues(
629 mActiveIface, uid, set, TAG_NONE, 0L, 0L, 0L, 0L, operationCount);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700630 }
631 }
632
633 @Override
634 public void setUidForeground(int uid, boolean uidForeground) {
635 mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
636
637 synchronized (mStatsLock) {
638 final int set = uidForeground ? SET_FOREGROUND : SET_DEFAULT;
639 final int oldSet = mActiveUidCounterSet.get(uid, SET_DEFAULT);
640 if (oldSet != set) {
641 mActiveUidCounterSet.put(uid, set);
642 setKernelCounterSet(uid, set);
643 }
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700644 }
645 }
646
647 @Override
Jeff Sharkey350083e2011-06-29 10:45:16 -0700648 public void forceUpdate() {
649 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700650 assertBandwidthControlEnabled();
Jeff Sharkeye630f7b2012-01-31 17:12:53 -0800651
652 final long token = Binder.clearCallingIdentity();
653 try {
654 performPoll(FLAG_PERSIST_ALL);
655 } finally {
656 Binder.restoreCallingIdentity(token);
657 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700658 }
659
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700660 @Override
661 public void advisePersistThreshold(long thresholdBytes) {
662 mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
663 assertBandwidthControlEnabled();
664
665 // clamp threshold into safe range
666 mPersistThreshold = MathUtils.constrain(thresholdBytes, 128 * KB_IN_BYTES, 2 * MB_IN_BYTES);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700667 if (LOGV) {
668 Slog.v(TAG, "advisePersistThreshold() given " + thresholdBytes + ", clamped to "
669 + mPersistThreshold);
670 }
671
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700672 // update and persist if beyond new thresholds
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700673 final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
674 : System.currentTimeMillis();
Jeff Sharkey58015972012-05-07 11:08:49 -0700675 synchronized (mStatsLock) {
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700676 if (!mSystemReady) return;
677
678 updatePersistThresholds();
679
Jeff Sharkey58015972012-05-07 11:08:49 -0700680 mDevRecorder.maybePersistLocked(currentTime);
681 mXtRecorder.maybePersistLocked(currentTime);
682 mUidRecorder.maybePersistLocked(currentTime);
683 mUidTagRecorder.maybePersistLocked(currentTime);
684 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700685
686 // re-arm global alert
687 registerGlobalAlert();
688 }
689
690 /**
691 * Update {@link NetworkStatsRecorder} and {@link #mGlobalAlertBytes} to
692 * reflect current {@link #mPersistThreshold} value. Always defers to
Jeff Sharkey625239a2012-09-26 22:03:49 -0700693 * {@link Global} values when defined.
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700694 */
695 private void updatePersistThresholds() {
696 mDevRecorder.setPersistThreshold(mSettings.getDevPersistBytes(mPersistThreshold));
697 mXtRecorder.setPersistThreshold(mSettings.getXtPersistBytes(mPersistThreshold));
698 mUidRecorder.setPersistThreshold(mSettings.getUidPersistBytes(mPersistThreshold));
699 mUidTagRecorder.setPersistThreshold(mSettings.getUidTagPersistBytes(mPersistThreshold));
700 mGlobalAlertBytes = mSettings.getGlobalAlertBytes(mPersistThreshold);
701 }
702
Jeff Sharkey75279902011-05-24 18:39:45 -0700703 /**
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700704 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey75279902011-05-24 18:39:45 -0700705 * interfaces. Used to associate {@link TelephonyManager#getSubscriberId()}
706 * with mobile interfaces.
707 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700708 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey75279902011-05-24 18:39:45 -0700709 @Override
710 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700711 // on background handler thread, and verified CONNECTIVITY_INTERNAL
712 // permission above.
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700713 updateIfaces();
Jeff Sharkey75279902011-05-24 18:39:45 -0700714 }
715 };
716
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700717 /**
718 * Receiver that watches for {@link Tethering} to claim interface pairs.
719 */
720 private BroadcastReceiver mTetherReceiver = new BroadcastReceiver() {
721 @Override
722 public void onReceive(Context context, Intent intent) {
723 // on background handler thread, and verified CONNECTIVITY_INTERNAL
724 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700725 performPoll(FLAG_PERSIST_NETWORK);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700726 }
727 };
728
Jeff Sharkey75279902011-05-24 18:39:45 -0700729 private BroadcastReceiver mPollReceiver = new BroadcastReceiver() {
730 @Override
731 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700732 // on background handler thread, and verified UPDATE_DEVICE_STATS
733 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700734 performPoll(FLAG_PERSIST_ALL);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700735
736 // verify that we're watching global alert
737 registerGlobalAlert();
Jeff Sharkey75279902011-05-24 18:39:45 -0700738 }
739 };
740
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700741 private BroadcastReceiver mRemovedReceiver = new BroadcastReceiver() {
742 @Override
743 public void onReceive(Context context, Intent intent) {
744 // on background handler thread, and UID_REMOVED is protected
745 // broadcast.
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700746
747 final int uid = intent.getIntExtra(EXTRA_UID, -1);
748 if (uid == -1) return;
749
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700750 synchronized (mStatsLock) {
Jeff Sharkey62489262011-07-17 12:53:28 -0700751 mWakeLock.acquire();
752 try {
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700753 removeUidsLocked(uid);
754 } finally {
755 mWakeLock.release();
756 }
757 }
758 }
759 };
760
761 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
762 @Override
763 public void onReceive(Context context, Intent intent) {
764 // On background handler thread, and USER_REMOVED is protected
765 // broadcast.
766
767 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
768 if (userId == -1) return;
769
770 synchronized (mStatsLock) {
771 mWakeLock.acquire();
772 try {
773 removeUserLocked(userId);
Jeff Sharkey62489262011-07-17 12:53:28 -0700774 } finally {
775 mWakeLock.release();
776 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700777 }
778 }
779 };
780
Jeff Sharkey75279902011-05-24 18:39:45 -0700781 private BroadcastReceiver mShutdownReceiver = new BroadcastReceiver() {
782 @Override
783 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700784 // SHUTDOWN is protected broadcast.
Jeff Sharkey75279902011-05-24 18:39:45 -0700785 synchronized (mStatsLock) {
Jeff Sharkey3f391352011-06-05 17:42:53 -0700786 shutdownLocked();
Jeff Sharkey75279902011-05-24 18:39:45 -0700787 }
788 }
789 };
790
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700791 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700792 * Observer that watches for {@link INetworkManagementService} alerts.
793 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700794 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700795 @Override
796 public void limitReached(String limitName, String iface) {
797 // only someone like NMS should be calling us
798 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
799
800 if (LIMIT_GLOBAL_ALERT.equals(limitName)) {
801 // kick off background poll to collect network stats; UID stats
802 // are handled during normal polling interval.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700803 final int flags = FLAG_PERSIST_NETWORK;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700804 mHandler.obtainMessage(MSG_PERFORM_POLL, flags, 0).sendToTarget();
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700805
806 // re-arm global alert for next update
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -0800807 mHandler.obtainMessage(MSG_REGISTER_GLOBAL_ALERT).sendToTarget();
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700808 }
809 }
810 };
811
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700812 private int mLastPhoneState = TelephonyManager.DATA_UNKNOWN;
813 private int mLastPhoneNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
814
815 /**
816 * Receiver that watches for {@link TelephonyManager} changes, such as
817 * transitioning between network types.
818 */
819 private PhoneStateListener mPhoneListener = new PhoneStateListener() {
820 @Override
821 public void onDataConnectionStateChanged(int state, int networkType) {
822 final boolean stateChanged = state != mLastPhoneState;
823 final boolean networkTypeChanged = networkType != mLastPhoneNetworkType;
824
825 if (networkTypeChanged && !stateChanged) {
826 // networkType changed without a state change, which means we
827 // need to roll our own update. delay long enough for
828 // ConnectivityManager to process.
829 // TODO: add direct event to ConnectivityService instead of
830 // relying on this delay.
831 if (LOGV) Slog.v(TAG, "triggering delayed updateIfaces()");
832 mHandler.sendMessageDelayed(
833 mHandler.obtainMessage(MSG_UPDATE_IFACES), SECOND_IN_MILLIS);
834 }
835
836 mLastPhoneState = state;
837 mLastPhoneNetworkType = networkType;
838 }
839 };
840
841 private void updateIfaces() {
842 synchronized (mStatsLock) {
843 mWakeLock.acquire();
844 try {
845 updateIfacesLocked();
846 } finally {
847 mWakeLock.release();
848 }
849 }
850 }
851
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700852 /**
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700853 * Inspect all current {@link NetworkState} to derive mapping from {@code
854 * iface} to {@link NetworkStatsHistory}. When multiple {@link NetworkInfo}
855 * are active on a single {@code iface}, they are combined under a single
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700856 * {@link NetworkIdentitySet}.
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700857 */
858 private void updateIfacesLocked() {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800859 if (!mSystemReady) return;
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700860 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700861
862 // take one last stats snapshot before updating iface mapping. this
863 // isn't perfect, since the kernel may already be counting traffic from
864 // the updated network.
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700865
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700866 // poll, but only persist network stats to keep codepath fast. UID stats
867 // will be persisted during next alarm poll event.
868 performPollLocked(FLAG_PERSIST_NETWORK);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700869
870 final NetworkState[] states;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800871 final LinkProperties activeLink;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700872 try {
873 states = mConnManager.getAllNetworkState();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800874 activeLink = mConnManager.getActiveLinkProperties();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700875 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700876 // ignored; service lives in system_server
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700877 return;
878 }
879
Jeff Sharkey63abc372012-01-11 18:38:16 -0800880 mActiveIface = activeLink != null ? activeLink.getInterfaceName() : null;
881
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700882 // rebuild active interfaces based on connected networks
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700883 mActiveIfaces.clear();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700884
885 for (NetworkState state : states) {
886 if (state.networkInfo.isConnected()) {
887 // collect networks under their parent interfaces
888 final String iface = state.linkProperties.getInterfaceName();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700889
890 NetworkIdentitySet ident = mActiveIfaces.get(iface);
891 if (ident == null) {
892 ident = new NetworkIdentitySet();
893 mActiveIfaces.put(iface, ident);
894 }
895
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700896 ident.add(NetworkIdentity.buildNetworkIdentity(mContext, state));
Jeff Sharkey234766a2012-04-10 19:48:07 -0700897
898 // remember any ifaces associated with mobile networks
Jeff Sharkey6a328af2012-11-30 17:49:39 -0800899 if (isNetworkTypeMobile(state.networkInfo.getType()) && iface != null) {
Jeff Sharkey234766a2012-04-10 19:48:07 -0700900 if (!contains(mMobileIfaces, iface)) {
901 mMobileIfaces = appendElement(String.class, mMobileIfaces, iface);
902 }
903 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700904 }
905 }
906 }
907
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700908 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700909 * Bootstrap initial stats snapshot, usually during {@link #systemReady()}
910 * so we have baseline values without double-counting.
911 */
Jeff Sharkey63abc372012-01-11 18:38:16 -0800912 private void bootstrapStatsLocked() {
913 final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
914 : System.currentTimeMillis();
915
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700916 try {
Jeff Sharkey63abc372012-01-11 18:38:16 -0800917 // snapshot and record current counters; read UID stats first to
918 // avoid overcounting dev stats.
919 final NetworkStats uidSnapshot = getNetworkStatsUidDetail();
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700920 final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
921 final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800922
923 mDevRecorder.recordSnapshotLocked(devSnapshot, mActiveIfaces, currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700924 mXtRecorder.recordSnapshotLocked(xtSnapshot, mActiveIfaces, currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800925 mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
926 mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
927
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700928 } catch (IllegalStateException e) {
929 Slog.w(TAG, "problem reading network stats: " + e);
930 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700931 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700932 }
933 }
934
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700935 private void performPoll(int flags) {
Anders 3 Fridlund36bc5b62012-06-07 11:24:10 +0200936 // try refreshing time source when stale
937 if (mTime.getCacheAge() > mSettings.getTimeCacheMaxAge()) {
938 mTime.forceRefresh();
939 }
940
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700941 synchronized (mStatsLock) {
942 mWakeLock.acquire();
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800943
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700944 try {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700945 performPollLocked(flags);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700946 } finally {
947 mWakeLock.release();
948 }
949 }
950 }
951
952 /**
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700953 * Periodic poll operation, reading current statistics and recording into
954 * {@link NetworkStatsHistory}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700955 */
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700956 private void performPollLocked(int flags) {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800957 if (!mSystemReady) return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700958 if (LOGV) Slog.v(TAG, "performPollLocked(flags=0x" + Integer.toHexString(flags) + ")");
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800959
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700960 final long startRealtime = SystemClock.elapsedRealtime();
Jeff Sharkey75279902011-05-24 18:39:45 -0700961
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700962 final boolean persistNetwork = (flags & FLAG_PERSIST_NETWORK) != 0;
963 final boolean persistUid = (flags & FLAG_PERSIST_UID) != 0;
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700964 final boolean persistForce = (flags & FLAG_PERSIST_FORCE) != 0;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700965
Jeff Sharkey75279902011-05-24 18:39:45 -0700966 // TODO: consider marking "untrusted" times in historical stats
967 final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
968 : System.currentTimeMillis();
969
Jeff Sharkey75279902011-05-24 18:39:45 -0700970 try {
Jeff Sharkey63abc372012-01-11 18:38:16 -0800971 // snapshot and record current counters; read UID stats first to
972 // avoid overcounting dev stats.
973 final NetworkStats uidSnapshot = getNetworkStatsUidDetail();
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700974 final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
975 final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700976
Jeff Sharkey63abc372012-01-11 18:38:16 -0800977 mDevRecorder.recordSnapshotLocked(devSnapshot, mActiveIfaces, currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700978 mXtRecorder.recordSnapshotLocked(xtSnapshot, mActiveIfaces, currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800979 mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
980 mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700981
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700982 } catch (IllegalStateException e) {
983 Log.wtf(TAG, "problem reading network stats", e);
Jeff Sharkey905b5892011-09-30 15:19:49 -0700984 return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700985 } catch (RemoteException e) {
986 // ignored; service lives in system_server
Jeff Sharkey905b5892011-09-30 15:19:49 -0700987 return;
988 }
989
Jeff Sharkey63abc372012-01-11 18:38:16 -0800990 // persist any pending data depending on requested flags
991 if (persistForce) {
992 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700993 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800994 mUidRecorder.forcePersistLocked(currentTime);
995 mUidTagRecorder.forcePersistLocked(currentTime);
996 } else {
997 if (persistNetwork) {
998 mDevRecorder.maybePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700999 mXtRecorder.maybePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001000 }
1001 if (persistUid) {
1002 mUidRecorder.maybePersistLocked(currentTime);
1003 mUidTagRecorder.maybePersistLocked(currentTime);
1004 }
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001005 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001006
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001007 if (LOGV) {
1008 final long duration = SystemClock.elapsedRealtime() - startRealtime;
1009 Slog.v(TAG, "performPollLocked() took " + duration + "ms");
1010 }
1011
Jeff Sharkey63abc372012-01-11 18:38:16 -08001012 if (mSettings.getSampleEnabled()) {
Jeff Sharkey905b5892011-09-30 15:19:49 -07001013 // sample stats after each full poll
Jeff Sharkey63abc372012-01-11 18:38:16 -08001014 performSampleLocked();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001015 }
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001016
Jeff Sharkey497e4432011-06-14 17:27:29 -07001017 // finally, dispatch updated event to any listeners
1018 final Intent updatedIntent = new Intent(ACTION_NETWORK_STATS_UPDATED);
1019 updatedIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001020 mContext.sendBroadcastAsUser(updatedIntent, UserHandle.ALL,
1021 READ_NETWORK_USAGE_HISTORY);
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001022 }
1023
1024 /**
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001025 * Sample recent statistics summary into {@link EventLog}.
1026 */
Jeff Sharkey63abc372012-01-11 18:38:16 -08001027 private void performSampleLocked() {
1028 // TODO: migrate trustedtime fixes to separate binary log events
Jeff Sharkey905b5892011-09-30 15:19:49 -07001029 final long trustedTime = mTime.hasCache() ? mTime.currentTimeMillis() : -1;
1030
Jeff Sharkey63abc372012-01-11 18:38:16 -08001031 NetworkTemplate template;
1032 NetworkStats.Entry devTotal;
1033 NetworkStats.Entry xtTotal;
1034 NetworkStats.Entry uidTotal;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001035
1036 // collect mobile sample
Jeff Sharkey234766a2012-04-10 19:48:07 -07001037 template = buildTemplateMobileWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001038 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001039 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001040 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001041
Jeff Sharkey905b5892011-09-30 15:19:49 -07001042 EventLogTags.writeNetstatsMobileSample(
1043 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1044 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1045 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey63abc372012-01-11 18:38:16 -08001046 trustedTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001047
1048 // collect wifi sample
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001049 template = buildTemplateWifiWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001050 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001051 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001052 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
1053
Jeff Sharkey905b5892011-09-30 15:19:49 -07001054 EventLogTags.writeNetstatsWifiSample(
1055 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1056 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1057 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey63abc372012-01-11 18:38:16 -08001058 trustedTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001059 }
1060
1061 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001062 * Clean up {@link #mUidRecorder} after UID is removed.
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001063 */
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001064 private void removeUidsLocked(int... uids) {
1065 if (LOGV) Slog.v(TAG, "removeUidsLocked() for UIDs " + Arrays.toString(uids));
1066
1067 // Perform one last poll before removing
Jeff Sharkey163e6442011-10-31 16:37:52 -07001068 performPollLocked(FLAG_PERSIST_ALL);
1069
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001070 mUidRecorder.removeUidsLocked(uids);
1071 mUidTagRecorder.removeUidsLocked(uids);
Jeff Sharkey163e6442011-10-31 16:37:52 -07001072
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001073 // Clear kernel stats associated with UID
1074 for (int uid : uids) {
1075 resetKernelUidStats(uid);
1076 }
1077 }
1078
1079 /**
1080 * Clean up {@link #mUidRecorder} after user is removed.
1081 */
1082 private void removeUserLocked(int userId) {
1083 if (LOGV) Slog.v(TAG, "removeUserLocked() for userId=" + userId);
1084
1085 // Build list of UIDs that we should clean up
1086 int[] uids = new int[0];
1087 final List<ApplicationInfo> apps = mContext.getPackageManager().getInstalledApplications(
1088 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1089 for (ApplicationInfo app : apps) {
1090 final int uid = UserHandle.getUid(userId, app.uid);
1091 uids = ArrayUtils.appendInt(uids, uid);
1092 }
1093
1094 removeUidsLocked(uids);
Jeff Sharkey75279902011-05-24 18:39:45 -07001095 }
1096
1097 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001098 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001099 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1100
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001101 final HashSet<String> argSet = new HashSet<String>();
1102 for (String arg : args) {
1103 argSet.add(arg);
Jeff Sharkey75279902011-05-24 18:39:45 -07001104 }
1105
Jeff Sharkey706498d2012-02-06 17:35:07 -08001106 // usage: dumpsys netstats --full --uid --tag --poll --checkin
Jeff Sharkey63abc372012-01-11 18:38:16 -08001107 final boolean poll = argSet.contains("--poll") || argSet.contains("poll");
Jeff Sharkey706498d2012-02-06 17:35:07 -08001108 final boolean checkin = argSet.contains("--checkin");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001109 final boolean fullHistory = argSet.contains("--full") || argSet.contains("full");
1110 final boolean includeUid = argSet.contains("--uid") || argSet.contains("detail");
1111 final boolean includeTag = argSet.contains("--tag") || argSet.contains("detail");
1112
1113 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkey350083e2011-06-29 10:45:16 -07001114
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001115 synchronized (mStatsLock) {
Jeff Sharkey63abc372012-01-11 18:38:16 -08001116 if (poll) {
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001117 performPollLocked(FLAG_PERSIST_ALL | FLAG_PERSIST_FORCE);
Jeff Sharkey3f391352011-06-05 17:42:53 -07001118 pw.println("Forced poll");
1119 return;
1120 }
1121
Jeff Sharkey706498d2012-02-06 17:35:07 -08001122 if (checkin) {
1123 // list current stats files to verify rotation
1124 pw.println("Current files:");
1125 pw.increaseIndent();
1126 for (String file : mBaseDir.list()) {
1127 pw.println(file);
1128 }
1129 pw.decreaseIndent();
1130 return;
1131 }
1132
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001133 pw.println("Active interfaces:");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001134 pw.increaseIndent();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001135 for (String iface : mActiveIfaces.keySet()) {
1136 final NetworkIdentitySet ident = mActiveIfaces.get(iface);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001137 pw.print("iface="); pw.print(iface);
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001138 pw.print(" ident="); pw.println(ident.toString());
1139 }
Jeff Sharkey63abc372012-01-11 18:38:16 -08001140 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001141
Jeff Sharkey63abc372012-01-11 18:38:16 -08001142 pw.println("Dev stats:");
1143 pw.increaseIndent();
1144 mDevRecorder.dumpLocked(pw, fullHistory);
1145 pw.decreaseIndent();
1146
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001147 pw.println("Xt stats:");
1148 pw.increaseIndent();
1149 mXtRecorder.dumpLocked(pw, fullHistory);
1150 pw.decreaseIndent();
1151
Jeff Sharkey63abc372012-01-11 18:38:16 -08001152 if (includeUid) {
1153 pw.println("UID stats:");
1154 pw.increaseIndent();
1155 mUidRecorder.dumpLocked(pw, fullHistory);
1156 pw.decreaseIndent();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001157 }
1158
Jeff Sharkey63abc372012-01-11 18:38:16 -08001159 if (includeTag) {
1160 pw.println("UID tag stats:");
1161 pw.increaseIndent();
1162 mUidTagRecorder.dumpLocked(pw, fullHistory);
1163 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001164 }
1165 }
1166 }
1167
1168 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001169 * Return snapshot of current UID statistics, including any
1170 * {@link TrafficStats#UID_TETHERING} and {@link #mUidOperations} values.
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001171 */
Jeff Sharkey63abc372012-01-11 18:38:16 -08001172 private NetworkStats getNetworkStatsUidDetail() throws RemoteException {
1173 final NetworkStats uidSnapshot = mNetworkManager.getNetworkStatsUidDetail(UID_ALL);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001174
Jeff Sharkey63abc372012-01-11 18:38:16 -08001175 // fold tethering stats and operations into uid snapshot
1176 final NetworkStats tetherSnapshot = getNetworkStatsTethering();
1177 uidSnapshot.combineAllValues(tetherSnapshot);
1178 uidSnapshot.combineAllValues(mUidOperations);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001179
Jeff Sharkey63abc372012-01-11 18:38:16 -08001180 return uidSnapshot;
Jeff Sharkey75279902011-05-24 18:39:45 -07001181 }
1182
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001183 /**
1184 * Return snapshot of current tethering statistics. Will return empty
1185 * {@link NetworkStats} if any problems are encountered.
1186 */
1187 private NetworkStats getNetworkStatsTethering() throws RemoteException {
1188 try {
1189 final String[] tetheredIfacePairs = mConnManager.getTetheredIfacePairs();
1190 return mNetworkManager.getNetworkStatsTethering(tetheredIfacePairs);
1191 } catch (IllegalStateException e) {
1192 Log.wtf(TAG, "problem reading network stats", e);
1193 return new NetworkStats(0L, 10);
1194 }
1195 }
1196
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001197 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001198 @Override
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001199 public boolean handleMessage(Message msg) {
1200 switch (msg.what) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001201 case MSG_PERFORM_POLL: {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001202 final int flags = msg.arg1;
1203 performPoll(flags);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001204 return true;
1205 }
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001206 case MSG_UPDATE_IFACES: {
1207 updateIfaces();
1208 return true;
1209 }
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001210 case MSG_REGISTER_GLOBAL_ALERT: {
1211 registerGlobalAlert();
1212 return true;
1213 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001214 default: {
1215 return false;
1216 }
1217 }
1218 }
1219 };
1220
Jeff Sharkey4190a042012-04-21 15:36:48 -07001221 private void assertBandwidthControlEnabled() {
1222 if (!isBandwidthControlEnabled()) {
1223 throw new IllegalStateException("Bandwidth module disabled");
1224 }
1225 }
1226
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001227 private boolean isBandwidthControlEnabled() {
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001228 final long token = Binder.clearCallingIdentity();
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001229 try {
1230 return mNetworkManager.isBandwidthControlEnabled();
1231 } catch (RemoteException e) {
1232 // ignored; service lives in system_server
1233 return false;
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001234 } finally {
1235 Binder.restoreCallingIdentity(token);
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001236 }
1237 }
1238
Jeff Sharkey63abc372012-01-11 18:38:16 -08001239 private class DropBoxNonMonotonicObserver implements NonMonotonicObserver<String> {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001240 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001241 public void foundNonMonotonic(NetworkStats left, int leftIndex, NetworkStats right,
1242 int rightIndex, String cookie) {
1243 Log.w(TAG, "found non-monotonic values; saving to dropbox");
1244
1245 // record error for debugging
1246 final StringBuilder builder = new StringBuilder();
1247 builder.append("found non-monotonic " + cookie + " values at left[" + leftIndex
1248 + "] - right[" + rightIndex + "]\n");
1249 builder.append("left=").append(left).append('\n');
1250 builder.append("right=").append(right).append('\n');
1251
1252 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
1253 Context.DROPBOX_SERVICE);
1254 dropBox.addText(TAG_NETSTATS_ERROR, builder.toString());
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001255 }
1256 }
1257
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001258 /**
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001259 * Default external settings that read from
Jeff Sharkey625239a2012-09-26 22:03:49 -07001260 * {@link android.provider.Settings.Global}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001261 */
1262 private static class DefaultNetworkStatsSettings implements NetworkStatsSettings {
1263 private final ContentResolver mResolver;
1264
1265 public DefaultNetworkStatsSettings(Context context) {
1266 mResolver = checkNotNull(context.getContentResolver());
1267 // TODO: adjust these timings for production builds
1268 }
1269
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001270 private long getGlobalLong(String name, long def) {
1271 return Settings.Global.getLong(mResolver, name, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001272 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001273 private boolean getGlobalBoolean(String name, boolean def) {
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001274 final int defInt = def ? 1 : 0;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001275 return Settings.Global.getInt(mResolver, name, defInt) != 0;
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001276 }
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001277
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001278 @Override
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001279 public long getPollInterval() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001280 return getGlobalLong(NETSTATS_POLL_INTERVAL, 30 * MINUTE_IN_MILLIS);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001281 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001282 @Override
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001283 public long getTimeCacheMaxAge() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001284 return getGlobalLong(NETSTATS_TIME_CACHE_MAX_AGE, DAY_IN_MILLIS);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001285 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001286 @Override
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001287 public long getGlobalAlertBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001288 return getGlobalLong(NETSTATS_GLOBAL_ALERT_BYTES, def);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001289 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001290 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001291 public boolean getSampleEnabled() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001292 return getGlobalBoolean(NETSTATS_SAMPLE_ENABLED, true);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001293 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001294 @Override
Jeff Sharkey70c70532012-05-16 14:51:19 -07001295 public boolean getReportXtOverDev() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001296 return getGlobalBoolean(NETSTATS_REPORT_XT_OVER_DEV, true);
Jeff Sharkey70c70532012-05-16 14:51:19 -07001297 }
1298 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001299 public Config getDevConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001300 return new Config(getGlobalLong(NETSTATS_DEV_BUCKET_DURATION, HOUR_IN_MILLIS),
1301 getGlobalLong(NETSTATS_DEV_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1302 getGlobalLong(NETSTATS_DEV_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001303 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001304 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001305 public Config getXtConfig() {
1306 return getDevConfig();
1307 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001308 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001309 public Config getUidConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001310 return new Config(getGlobalLong(NETSTATS_UID_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1311 getGlobalLong(NETSTATS_UID_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1312 getGlobalLong(NETSTATS_UID_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001313 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001314 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001315 public Config getUidTagConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001316 return new Config(getGlobalLong(NETSTATS_UID_TAG_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1317 getGlobalLong(NETSTATS_UID_TAG_ROTATE_AGE, 5 * DAY_IN_MILLIS),
1318 getGlobalLong(NETSTATS_UID_TAG_DELETE_AGE, 15 * DAY_IN_MILLIS));
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001319 }
1320 @Override
1321 public long getDevPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001322 return getGlobalLong(NETSTATS_DEV_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001323 }
1324 @Override
1325 public long getXtPersistBytes(long def) {
1326 return getDevPersistBytes(def);
1327 }
1328 @Override
1329 public long getUidPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001330 return getGlobalLong(NETSTATS_UID_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001331 }
1332 @Override
1333 public long getUidTagPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001334 return getGlobalLong(NETSTATS_UID_TAG_PERSIST_BYTES, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001335 }
1336 }
Jeff Sharkey75279902011-05-24 18:39:45 -07001337}