blob: e3ff72b9a9d7a65c5d1176b72bf06fe8c4d8c26d [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 Sharkey21c9c452011-06-07 12:26:43 -070021import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070022import static android.content.Intent.ACTION_SHUTDOWN;
23import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -070024import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070025import static android.content.Intent.EXTRA_UID;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -070026import static android.net.ConnectivityManager.ACTION_TETHER_STATE_CHANGED;
Jeff Sharkey234766a2012-04-10 19:48:07 -070027import static android.net.ConnectivityManager.isNetworkTypeMobile;
Lorenzo Colittiada23ed2018-01-19 01:05:20 +090028import static android.net.NetworkStats.DEFAULT_NETWORK_ALL;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -070029import static android.net.NetworkStats.IFACE_ALL;
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +090030import static android.net.NetworkStats.INTERFACES_ALL;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -060031import static android.net.NetworkStats.METERED_ALL;
32import static android.net.NetworkStats.ROAMING_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;
Lorenzo Colitti5356a352017-08-17 19:23:08 +090036import static android.net.NetworkStats.STATS_PER_IFACE;
37import static android.net.NetworkStats.STATS_PER_UID;
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +090038import static android.net.NetworkStats.TAG_ALL;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070039import static android.net.NetworkStats.TAG_NONE;
Jeff Sharkey75279902011-05-24 18:39:45 -070040import static android.net.NetworkStats.UID_ALL;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -060041import static android.net.NetworkStatsHistory.FIELD_ALL;
Jeff Sharkey234766a2012-04-10 19:48:07 -070042import static android.net.NetworkTemplate.buildTemplateMobileWildcard;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070043import static android.net.NetworkTemplate.buildTemplateWifiWildcard;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -070044import static android.net.TrafficStats.KB_IN_BYTES;
Jeff Sharkey241dde22012-02-03 14:50:07 -080045import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -060046import static android.provider.Settings.Global.NETSTATS_AUGMENT_ENABLED;
Jeff Sharkey023c05a2012-09-14 13:09:57 -070047import static android.provider.Settings.Global.NETSTATS_DEV_BUCKET_DURATION;
48import static android.provider.Settings.Global.NETSTATS_DEV_DELETE_AGE;
49import static android.provider.Settings.Global.NETSTATS_DEV_PERSIST_BYTES;
50import static android.provider.Settings.Global.NETSTATS_DEV_ROTATE_AGE;
51import static android.provider.Settings.Global.NETSTATS_GLOBAL_ALERT_BYTES;
52import static android.provider.Settings.Global.NETSTATS_POLL_INTERVAL;
Jeff Sharkey023c05a2012-09-14 13:09:57 -070053import static android.provider.Settings.Global.NETSTATS_SAMPLE_ENABLED;
Jeff Sharkey023c05a2012-09-14 13:09:57 -070054import static android.provider.Settings.Global.NETSTATS_UID_BUCKET_DURATION;
55import static android.provider.Settings.Global.NETSTATS_UID_DELETE_AGE;
56import static android.provider.Settings.Global.NETSTATS_UID_PERSIST_BYTES;
57import static android.provider.Settings.Global.NETSTATS_UID_ROTATE_AGE;
58import static android.provider.Settings.Global.NETSTATS_UID_TAG_BUCKET_DURATION;
59import static android.provider.Settings.Global.NETSTATS_UID_TAG_DELETE_AGE;
60import static android.provider.Settings.Global.NETSTATS_UID_TAG_PERSIST_BYTES;
61import static android.provider.Settings.Global.NETSTATS_UID_TAG_ROTATE_AGE;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -070062import static android.text.format.DateUtils.DAY_IN_MILLIS;
63import static android.text.format.DateUtils.HOUR_IN_MILLIS;
64import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070065import static android.text.format.DateUtils.SECOND_IN_MILLIS;
Jack Yuf9d559c2017-05-26 16:08:22 -070066
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
Jeff Sharkey9911a282018-02-14 22:29:11 -070072import android.annotation.NonNull;
Jeff Sharkey75279902011-05-24 18:39:45 -070073import android.app.AlarmManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070074import android.app.PendingIntent;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -060075import android.app.usage.NetworkStatsManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070076import android.content.BroadcastReceiver;
Jeff Sharkey39ebc212011-06-11 17:25:42 -070077import android.content.ContentResolver;
Jeff Sharkey75279902011-05-24 18:39:45 -070078import android.content.Context;
79import android.content.Intent;
80import android.content.IntentFilter;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -070081import android.content.pm.ApplicationInfo;
82import android.content.pm.PackageManager;
Antonio Cansadocd42acd2016-02-17 13:03:38 -080083import android.net.DataUsageRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070084import android.net.IConnectivityManager;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070085import android.net.INetworkManagementEventObserver;
Jeff Sharkey75279902011-05-24 18:39:45 -070086import android.net.INetworkStatsService;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -070087import android.net.INetworkStatsSession;
Jeff Sharkey63abc372012-01-11 18:38:16 -080088import android.net.LinkProperties;
Lorenzo Colittic78da292018-01-19 00:50:48 +090089import android.net.Network;
Jack Yub6587ea2016-06-22 11:35:10 -070090import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070091import android.net.NetworkIdentity;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070092import android.net.NetworkInfo;
93import android.net.NetworkState;
Jeff Sharkey75279902011-05-24 18:39:45 -070094import android.net.NetworkStats;
Jeff Sharkey5a7bcf32012-01-10 17:24:44 -080095import android.net.NetworkStats.NonMonotonicObserver;
Jeff Sharkey75279902011-05-24 18:39:45 -070096import android.net.NetworkStatsHistory;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070097import android.net.NetworkTemplate;
Jeff Sharkey63abc372012-01-11 18:38:16 -080098import android.net.TrafficStats;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070099import android.os.BestClock;
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700100import android.os.Binder;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700101import android.os.DropBoxManager;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700102import android.os.Environment;
Jeff Sharkey75279902011-05-24 18:39:45 -0700103import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700104import android.os.HandlerThread;
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800105import android.os.IBinder;
Jeff Sharkey75279902011-05-24 18:39:45 -0700106import android.os.INetworkManagementService;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700107import android.os.Message;
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800108import android.os.Messenger;
Jeff Sharkey62489262011-07-17 12:53:28 -0700109import android.os.PowerManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700110import android.os.RemoteException;
111import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700112import android.os.UserHandle;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700113import android.provider.Settings;
Jeff Sharkey625239a2012-09-26 22:03:49 -0700114import android.provider.Settings.Global;
Makoto Onukida65a522017-01-13 10:23:30 -0800115import android.service.NetworkInterfaceProto;
116import android.service.NetworkStatsServiceDumpProto;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600117import android.telephony.SubscriptionManager;
118import android.telephony.SubscriptionPlan;
Jeff Sharkey75279902011-05-24 18:39:45 -0700119import android.telephony.TelephonyManager;
Jeff Sharkey55a442e2014-11-18 18:22:21 -0800120import android.text.format.DateUtils;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import android.util.ArrayMap;
122import android.util.ArraySet;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -0700123import android.util.EventLog;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700124import android.util.Log;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700125import android.util.MathUtils;
Jeff Sharkey75279902011-05-24 18:39:45 -0700126import android.util.Slog;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700127import android.util.SparseIntArray;
Makoto Onukida65a522017-01-13 10:23:30 -0800128import android.util.proto.ProtoOutputStream;
Jeff Sharkey75279902011-05-24 18:39:45 -0700129
Jeff Sharkey4635f102017-09-01 11:27:13 -0600130import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800131import com.android.internal.annotations.VisibleForTesting;
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +0900132import com.android.internal.net.NetworkStatsFactory;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800133import com.android.internal.net.VpnInfo;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700134import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600135import com.android.internal.util.DumpUtils;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800136import com.android.internal.util.FileRotator;
137import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -0700138import com.android.server.EventLogTags;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700139import com.android.server.LocalServices;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700140import com.android.server.connectivity.Tethering;
Jeff Sharkey75279902011-05-24 18:39:45 -0700141
Jeff Sharkey3f391352011-06-05 17:42:53 -0700142import java.io.File;
Jeff Sharkey75279902011-05-24 18:39:45 -0700143import java.io.FileDescriptor;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700144import java.io.IOException;
Jeff Sharkey75279902011-05-24 18:39:45 -0700145import java.io.PrintWriter;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700146import java.time.Clock;
147import java.time.ZoneOffset;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700148import java.util.Arrays;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700149import java.util.HashSet;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700150import java.util.List;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700151
Jeff Sharkey75279902011-05-24 18:39:45 -0700152/**
153 * Collect and persist detailed network statistics, and provide this data to
154 * other system services.
155 */
156public class NetworkStatsService extends INetworkStatsService.Stub {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600157 static final String TAG = "NetworkStats";
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700158 static final boolean LOGD = Log.isLoggable(TAG, Log.DEBUG);
159 static final boolean LOGV = Log.isLoggable(TAG, Log.VERBOSE);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700160
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700161 private static final int MSG_PERFORM_POLL = 1;
162 private static final int MSG_UPDATE_IFACES = 2;
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -0800163 private static final int MSG_REGISTER_GLOBAL_ALERT = 3;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700164
165 /** Flags to control detail level of poll event. */
Jeff Sharkey905b5892011-09-30 15:19:49 -0700166 private static final int FLAG_PERSIST_NETWORK = 0x1;
167 private static final int FLAG_PERSIST_UID = 0x2;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700168 private static final int FLAG_PERSIST_ALL = FLAG_PERSIST_NETWORK | FLAG_PERSIST_UID;
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700169 private static final int FLAG_PERSIST_FORCE = 0x100;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700170
Jeff Sharkey163e6442011-10-31 16:37:52 -0700171 private static final String TAG_NETSTATS_ERROR = "netstats_error";
172
Jeff Sharkey75279902011-05-24 18:39:45 -0700173 private final Context mContext;
174 private final INetworkManagementService mNetworkManager;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700175 private final AlarmManager mAlarmManager;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700176 private final Clock mClock;
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700177 private final TelephonyManager mTeleManager;
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700178 private final NetworkStatsSettings mSettings;
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800179 private final NetworkStatsObservers mStatsObservers;
Jeff Sharkey75279902011-05-24 18:39:45 -0700180
Jeff Sharkey63abc372012-01-11 18:38:16 -0800181 private final File mSystemDir;
182 private final File mBaseDir;
183
Jeff Sharkey62489262011-07-17 12:53:28 -0700184 private final PowerManager.WakeLock mWakeLock;
185
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700186 private IConnectivityManager mConnManager;
187
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800188 @VisibleForTesting
Jeff Sharkey3f391352011-06-05 17:42:53 -0700189 public static final String ACTION_NETWORK_STATS_POLL =
Jeff Sharkey75279902011-05-24 18:39:45 -0700190 "com.android.server.action.NETWORK_STATS_POLL";
Jeff Sharkey497e4432011-06-14 17:27:29 -0700191 public static final String ACTION_NETWORK_STATS_UPDATED =
192 "com.android.server.action.NETWORK_STATS_UPDATED";
Jeff Sharkey75279902011-05-24 18:39:45 -0700193
194 private PendingIntent mPollIntent;
195
Jeff Sharkey63abc372012-01-11 18:38:16 -0800196 private static final String PREFIX_DEV = "dev";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700197 private static final String PREFIX_XT = "xt";
Jeff Sharkey63abc372012-01-11 18:38:16 -0800198 private static final String PREFIX_UID = "uid";
199 private static final String PREFIX_UID_TAG = "uid_tag";
200
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700201 /**
Jack Yub6587ea2016-06-22 11:35:10 -0700202 * Virtual network interface for video telephony. This is for VT data usage counting purpose.
203 */
204 public static final String VT_INTERFACE = "vt_data0";
205
206 /**
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700207 * Settings that can be changed externally.
208 */
209 public interface NetworkStatsSettings {
210 public long getPollInterval();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800211 public boolean getSampleEnabled();
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600212 public boolean getAugmentEnabled();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800213
214 public static class Config {
215 public final long bucketDuration;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800216 public final long rotateAgeMillis;
217 public final long deleteAgeMillis;
218
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700219 public Config(long bucketDuration, long rotateAgeMillis, long deleteAgeMillis) {
Jeff Sharkey63abc372012-01-11 18:38:16 -0800220 this.bucketDuration = bucketDuration;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800221 this.rotateAgeMillis = rotateAgeMillis;
222 this.deleteAgeMillis = deleteAgeMillis;
223 }
224 }
225
226 public Config getDevConfig();
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700227 public Config getXtConfig();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800228 public Config getUidConfig();
229 public Config getUidTagConfig();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700230
231 public long getGlobalAlertBytes(long def);
232 public long getDevPersistBytes(long def);
233 public long getXtPersistBytes(long def);
234 public long getUidPersistBytes(long def);
235 public long getUidTagPersistBytes(long def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700236 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700237
238 private final Object mStatsLock = new Object();
239
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700240 /** Set of currently active ifaces. */
Lorenzo Colittic78da292018-01-19 00:50:48 +0900241 @GuardedBy("mStatsLock")
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700242 private final ArrayMap<String, NetworkIdentitySet> mActiveIfaces = new ArrayMap<>();
Lorenzo Colittic78da292018-01-19 00:50:48 +0900243
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700244 /** Set of currently active ifaces for UID stats. */
Lorenzo Colittic78da292018-01-19 00:50:48 +0900245 @GuardedBy("mStatsLock")
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700246 private final ArrayMap<String, NetworkIdentitySet> mActiveUidIfaces = new ArrayMap<>();
Lorenzo Colittic78da292018-01-19 00:50:48 +0900247
Jeff Sharkey63abc372012-01-11 18:38:16 -0800248 /** Current default active iface. */
249 private String mActiveIface;
Lorenzo Colittic78da292018-01-19 00:50:48 +0900250
Jeff Sharkey234766a2012-04-10 19:48:07 -0700251 /** Set of any ifaces associated with mobile networks since boot. */
Lorenzo Colittic78da292018-01-19 00:50:48 +0900252 @GuardedBy("mStatsLock")
Jeff Sharkey234766a2012-04-10 19:48:07 -0700253 private String[] mMobileIfaces = new String[0];
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700254
Lorenzo Colittic78da292018-01-19 00:50:48 +0900255 /** Set of all ifaces currently used by traffic that does not explicitly specify a Network. */
256 @GuardedBy("mStatsLock")
257 private Network[] mDefaultNetworks = new Network[0];
258
Jeff Sharkey63abc372012-01-11 18:38:16 -0800259 private final DropBoxNonMonotonicObserver mNonMonotonicObserver =
260 new DropBoxNonMonotonicObserver();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700261
Jeff Sharkey4635f102017-09-01 11:27:13 -0600262 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800263 private NetworkStatsRecorder mDevRecorder;
Jeff Sharkey4635f102017-09-01 11:27:13 -0600264 @GuardedBy("mStatsLock")
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700265 private NetworkStatsRecorder mXtRecorder;
Jeff Sharkey4635f102017-09-01 11:27:13 -0600266 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800267 private NetworkStatsRecorder mUidRecorder;
Jeff Sharkey4635f102017-09-01 11:27:13 -0600268 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800269 private NetworkStatsRecorder mUidTagRecorder;
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700270
Jeff Sharkey70c70532012-05-16 14:51:19 -0700271 /** Cached {@link #mXtRecorder} stats. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600272 @GuardedBy("mStatsLock")
Jeff Sharkey70c70532012-05-16 14:51:19 -0700273 private NetworkStatsCollection mXtStatsCached;
Jeff Sharkey75279902011-05-24 18:39:45 -0700274
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700275 /** Current counter sets for each UID. */
276 private SparseIntArray mActiveUidCounterSet = new SparseIntArray();
277
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700278 /** Data layer operation counters for splicing into other structures. */
Jeff Sharkey63abc372012-01-11 18:38:16 -0800279 private NetworkStats mUidOperations = new NetworkStats(0L, 10);
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700280
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800281 /** Must be set in factory by calling #setHandler. */
282 private Handler mHandler;
283 private Handler.Callback mHandlerCallback;
Jeff Sharkey75279902011-05-24 18:39:45 -0700284
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800285 private boolean mSystemReady;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700286 private long mPersistThreshold = 2 * MB_IN_BYTES;
287 private long mGlobalAlertBytes;
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800288
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900289 private static final long POLL_RATE_LIMIT_MS = 15_000;
290
291 private long mLastStatsSessionPoll;
292
293 /** Map from UID to number of opened sessions */
294 @GuardedBy("mOpenSessionCallsPerUid")
295 private final SparseIntArray mOpenSessionCallsPerUid = new SparseIntArray();
296
297 private final static int DUMP_STATS_SESSION_COUNT = 20;
298
Jeff Sharkey9911a282018-02-14 22:29:11 -0700299 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey3f391352011-06-05 17:42:53 -0700300 return new File(Environment.getDataDirectory(), "system");
Jeff Sharkey75279902011-05-24 18:39:45 -0700301 }
302
Jeff Sharkey9911a282018-02-14 22:29:11 -0700303 private static @NonNull File getDefaultBaseDir() {
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800304 File baseDir = new File(getDefaultSystemDir(), "netstats");
305 baseDir.mkdirs();
306 return baseDir;
307 }
308
Jeff Sharkey9911a282018-02-14 22:29:11 -0700309 private static @NonNull Clock getDefaultClock() {
310 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
311 Clock.systemUTC());
312 }
313
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800314 public static NetworkStatsService create(Context context,
315 INetworkManagementService networkManager) {
316 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
317 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
318 PowerManager.WakeLock wakeLock =
319 powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
320
321 NetworkStatsService service = new NetworkStatsService(context, networkManager, alarmManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700322 wakeLock, getDefaultClock(), TelephonyManager.getDefault(),
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800323 new DefaultNetworkStatsSettings(context), new NetworkStatsObservers(),
324 getDefaultSystemDir(), getDefaultBaseDir());
325
326 HandlerThread handlerThread = new HandlerThread(TAG);
327 Handler.Callback callback = new HandlerCallback(service);
328 handlerThread.start();
329 Handler handler = new Handler(handlerThread.getLooper(), callback);
330 service.setHandler(handler, callback);
331 return service;
332 }
333
334 @VisibleForTesting
335 NetworkStatsService(Context context, INetworkManagementService networkManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700336 AlarmManager alarmManager, PowerManager.WakeLock wakeLock, Clock clock,
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800337 TelephonyManager teleManager, NetworkStatsSettings settings,
338 NetworkStatsObservers statsObservers, File systemDir, File baseDir) {
Jeff Sharkey75279902011-05-24 18:39:45 -0700339 mContext = checkNotNull(context, "missing Context");
340 mNetworkManager = checkNotNull(networkManager, "missing INetworkManagementService");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800341 mAlarmManager = checkNotNull(alarmManager, "missing AlarmManager");
Jeff Sharkey9911a282018-02-14 22:29:11 -0700342 mClock = checkNotNull(clock, "missing Clock");
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700343 mSettings = checkNotNull(settings, "missing NetworkStatsSettings");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800344 mTeleManager = checkNotNull(teleManager, "missing TelephonyManager");
345 mWakeLock = checkNotNull(wakeLock, "missing WakeLock");
346 mStatsObservers = checkNotNull(statsObservers, "missing NetworkStatsObservers");
347 mSystemDir = checkNotNull(systemDir, "missing systemDir");
348 mBaseDir = checkNotNull(baseDir, "missing baseDir");
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700349
350 LocalServices.addService(NetworkStatsManagerInternal.class,
351 new NetworkStatsManagerInternalImpl());
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800352 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700353
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800354 @VisibleForTesting
355 void setHandler(Handler handler, Handler.Callback callback) {
356 mHandler = handler;
357 mHandlerCallback = callback;
Jeff Sharkey75279902011-05-24 18:39:45 -0700358 }
359
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700360 public void bindConnectivityManager(IConnectivityManager connManager) {
361 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
362 }
363
Jeff Sharkey75279902011-05-24 18:39:45 -0700364 public void systemReady() {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800365 mSystemReady = true;
366
Jeff Sharkey418d12d2011-12-13 15:38:03 -0800367 if (!isBandwidthControlEnabled()) {
368 Slog.w(TAG, "bandwidth controls disabled, unable to track stats");
369 return;
370 }
371
Jeff Sharkey63abc372012-01-11 18:38:16 -0800372 synchronized (mStatsLock) {
Jeff Sharkey4635f102017-09-01 11:27:13 -0600373 // create data recorders along with historical rotators
374 mDevRecorder = buildRecorder(PREFIX_DEV, mSettings.getDevConfig(), false);
375 mXtRecorder = buildRecorder(PREFIX_XT, mSettings.getXtConfig(), false);
376 mUidRecorder = buildRecorder(PREFIX_UID, mSettings.getUidConfig(), false);
377 mUidTagRecorder = buildRecorder(PREFIX_UID_TAG, mSettings.getUidTagConfig(), true);
378
379 updatePersistThresholdsLocked();
380
Jeff Sharkey63abc372012-01-11 18:38:16 -0800381 // upgrade any legacy stats, migrating them to rotated files
382 maybeUpgradeLegacyStatsLocked();
383
384 // read historical network stats from disk, since policy service
385 // might need them right away.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700386 mXtStatsCached = mXtRecorder.getOrLoadCompleteLocked();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800387
388 // bootstrap initial stats to prevent double-counting later
389 bootstrapStatsLocked();
390 }
Jeff Sharkey3359aca2011-11-08 18:08:48 -0800391
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700392 // watch for tethering changes
393 final IntentFilter tetherFilter = new IntentFilter(ACTION_TETHER_STATE_CHANGED);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700394 mContext.registerReceiver(mTetherReceiver, tetherFilter, null, mHandler);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700395
Jeff Sharkey75279902011-05-24 18:39:45 -0700396 // listen for periodic polling events
397 final IntentFilter pollFilter = new IntentFilter(ACTION_NETWORK_STATS_POLL);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700398 mContext.registerReceiver(mPollReceiver, pollFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
Jeff Sharkey75279902011-05-24 18:39:45 -0700399
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700400 // listen for uid removal to clean stats
401 final IntentFilter removedFilter = new IntentFilter(ACTION_UID_REMOVED);
402 mContext.registerReceiver(mRemovedReceiver, removedFilter, null, mHandler);
403
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700404 // listen for user changes to clean stats
405 final IntentFilter userFilter = new IntentFilter(ACTION_USER_REMOVED);
406 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
407
Jeff Sharkey75279902011-05-24 18:39:45 -0700408 // persist stats during clean shutdown
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700409 final IntentFilter shutdownFilter = new IntentFilter(ACTION_SHUTDOWN);
410 mContext.registerReceiver(mShutdownReceiver, shutdownFilter);
Jeff Sharkey75279902011-05-24 18:39:45 -0700411
412 try {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700413 mNetworkManager.registerObserver(mAlertObserver);
Jeff Sharkey75279902011-05-24 18:39:45 -0700414 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700415 // ignored; service lives in system_server
Jeff Sharkey75279902011-05-24 18:39:45 -0700416 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700417
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700418 registerPollAlarmLocked();
419 registerGlobalAlert();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800420 }
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700421
Jeff Sharkey63abc372012-01-11 18:38:16 -0800422 private NetworkStatsRecorder buildRecorder(
423 String prefix, NetworkStatsSettings.Config config, boolean includeTags) {
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700424 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
425 Context.DROPBOX_SERVICE);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700426 return new NetworkStatsRecorder(new FileRotator(
427 mBaseDir, prefix, config.rotateAgeMillis, config.deleteAgeMillis),
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700428 mNonMonotonicObserver, dropBox, prefix, config.bucketDuration, includeTags);
Jeff Sharkey75279902011-05-24 18:39:45 -0700429 }
430
Andreas Gampea36dc622018-02-05 17:19:22 -0800431 @GuardedBy("mStatsLock")
Jeff Sharkey3f391352011-06-05 17:42:53 -0700432 private void shutdownLocked() {
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700433 mContext.unregisterReceiver(mTetherReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700434 mContext.unregisterReceiver(mPollReceiver);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700435 mContext.unregisterReceiver(mRemovedReceiver);
Ryuki Nakamuraa47b0c92017-03-01 10:40:36 +0900436 mContext.unregisterReceiver(mUserReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700437 mContext.unregisterReceiver(mShutdownReceiver);
438
Jeff Sharkey9911a282018-02-14 22:29:11 -0700439 final long currentTime = mClock.millis();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800440
441 // persist any pending stats
442 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700443 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800444 mUidRecorder.forcePersistLocked(currentTime);
445 mUidTagRecorder.forcePersistLocked(currentTime);
446
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800447 mSystemReady = false;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800448 }
449
Andreas Gampea36dc622018-02-05 17:19:22 -0800450 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800451 private void maybeUpgradeLegacyStatsLocked() {
452 File file;
453 try {
454 file = new File(mSystemDir, "netstats.bin");
455 if (file.exists()) {
456 mDevRecorder.importLegacyNetworkLocked(file);
457 file.delete();
458 }
459
460 file = new File(mSystemDir, "netstats_xt.bin");
461 if (file.exists()) {
462 file.delete();
463 }
464
465 file = new File(mSystemDir, "netstats_uid.bin");
466 if (file.exists()) {
467 mUidRecorder.importLegacyUidLocked(file);
468 mUidTagRecorder.importLegacyUidLocked(file);
469 file.delete();
470 }
471 } catch (IOException e) {
472 Log.wtf(TAG, "problem during legacy upgrade", e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700473 } catch (OutOfMemoryError e) {
474 Log.wtf(TAG, "problem during legacy upgrade", e);
Jeff Sharkeyc506ff62011-11-17 11:59:29 -0800475 }
Jeff Sharkey3f391352011-06-05 17:42:53 -0700476 }
477
Jeff Sharkey75279902011-05-24 18:39:45 -0700478 /**
479 * Clear any existing {@link #ACTION_NETWORK_STATS_POLL} alarms, and
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700480 * reschedule based on current {@link NetworkStatsSettings#getPollInterval()}.
Jeff Sharkey75279902011-05-24 18:39:45 -0700481 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700482 private void registerPollAlarmLocked() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700483 if (mPollIntent != null) {
484 mAlarmManager.cancel(mPollIntent);
Jeff Sharkey75279902011-05-24 18:39:45 -0700485 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700486
487 mPollIntent = PendingIntent.getBroadcast(
488 mContext, 0, new Intent(ACTION_NETWORK_STATS_POLL), 0);
489
490 final long currentRealtime = SystemClock.elapsedRealtime();
491 mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, currentRealtime,
492 mSettings.getPollInterval(), mPollIntent);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700493 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700494
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700495 /**
496 * Register for a global alert that is delivered through
497 * {@link INetworkManagementEventObserver} once a threshold amount of data
498 * has been transferred.
499 */
500 private void registerGlobalAlert() {
501 try {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700502 mNetworkManager.setGlobalAlert(mGlobalAlertBytes);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700503 } catch (IllegalStateException e) {
504 Slog.w(TAG, "problem registering for global alert: " + e);
505 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700506 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700507 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700508 }
509
510 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700511 public INetworkStatsSession openSession() {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600512 // NOTE: if callers want to get non-augmented data, they should go
513 // through the public API
514 return openSessionInternal(NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN, null);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000515 }
516
517 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600518 public INetworkStatsSession openSessionForUsageStats(int flags, String callingPackage) {
519 return openSessionInternal(flags, callingPackage);
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100520 }
521
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900522 private boolean isRateLimitedForPoll(int callingUid) {
523 if (callingUid == android.os.Process.SYSTEM_UID) {
524 return false;
525 }
526
527 final long lastCallTime;
528 final long now = SystemClock.elapsedRealtime();
529 synchronized (mOpenSessionCallsPerUid) {
530 int calls = mOpenSessionCallsPerUid.get(callingUid, 0);
531 mOpenSessionCallsPerUid.put(callingUid, calls + 1);
532 lastCallTime = mLastStatsSessionPoll;
533 mLastStatsSessionPoll = now;
534 }
535
536 return now - lastCallTime < POLL_RATE_LIMIT_MS;
537 }
538
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600539 private INetworkStatsSession openSessionInternal(final int flags, final String callingPackage) {
Jeff Sharkey4190a042012-04-21 15:36:48 -0700540 assertBandwidthControlEnabled();
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700541
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900542 final int callingUid = Binder.getCallingUid();
543 final int usedFlags = isRateLimitedForPoll(callingUid)
544 ? flags & (~NetworkStatsManager.FLAG_POLL_ON_OPEN)
545 : flags;
546 if ((usedFlags & NetworkStatsManager.FLAG_POLL_ON_OPEN) != 0) {
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100547 final long ident = Binder.clearCallingIdentity();
548 try {
549 performPoll(FLAG_PERSIST_ALL);
550 } finally {
551 Binder.restoreCallingIdentity(ident);
552 }
553 }
554
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700555 // return an IBinder which holds strong references to any loaded stats
556 // for its lifetime; when caller closes only weak references remain.
557
558 return new INetworkStatsSession.Stub() {
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900559 private final int mCallingUid = callingUid;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600560 private final String mCallingPackage = callingPackage;
561 private final @NetworkStatsAccess.Level int mAccessLevel = checkAccessLevel(
562 callingPackage);
563
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700564 private NetworkStatsCollection mUidComplete;
565 private NetworkStatsCollection mUidTagComplete;
566
567 private NetworkStatsCollection getUidComplete() {
Ashish Sharmac13b9452013-11-01 14:57:30 -0700568 synchronized (mStatsLock) {
569 if (mUidComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700570 mUidComplete = mUidRecorder.getOrLoadCompleteLocked();
571 }
Ashish Sharmac13b9452013-11-01 14:57:30 -0700572 return mUidComplete;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700573 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700574 }
575
576 private NetworkStatsCollection getUidTagComplete() {
Ashish Sharmac13b9452013-11-01 14:57:30 -0700577 synchronized (mStatsLock) {
578 if (mUidTagComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700579 mUidTagComplete = mUidTagRecorder.getOrLoadCompleteLocked();
580 }
Ashish Sharmac13b9452013-11-01 14:57:30 -0700581 return mUidTagComplete;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700582 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700583 }
584
585 @Override
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000586 public int[] getRelevantUids() {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600587 return getUidComplete().getRelevantUids(mAccessLevel);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000588 }
589
590 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600591 public NetworkStats getDeviceSummaryForNetwork(
592 NetworkTemplate template, long start, long end) {
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900593 return internalGetSummaryForNetwork(template, usedFlags, start, end, mAccessLevel,
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600594 mCallingUid);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000595 }
596
597 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700598 public NetworkStats getSummaryForNetwork(
599 NetworkTemplate template, long start, long end) {
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900600 return internalGetSummaryForNetwork(template, usedFlags, start, end, mAccessLevel,
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600601 mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700602 }
603
604 @Override
605 public NetworkStatsHistory getHistoryForNetwork(NetworkTemplate template, int fields) {
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900606 return internalGetHistoryForNetwork(template, usedFlags, fields, mAccessLevel,
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600607 mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700608 }
609
610 @Override
611 public NetworkStats getSummaryForAllUid(
612 NetworkTemplate template, long start, long end, boolean includeTags) {
Jeff Davidson39583b52016-12-12 11:55:37 -0800613 try {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600614 final NetworkStats stats = getUidComplete()
615 .getSummary(template, start, end, mAccessLevel, mCallingUid);
Jeff Davidson39583b52016-12-12 11:55:37 -0800616 if (includeTags) {
617 final NetworkStats tagStats = getUidTagComplete()
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600618 .getSummary(template, start, end, mAccessLevel, mCallingUid);
Jeff Davidson39583b52016-12-12 11:55:37 -0800619 stats.combineAllValues(tagStats);
620 }
621 return stats;
622 } catch (NullPointerException e) {
623 // TODO: Track down and fix the cause of this crash and remove this catch block.
624 Slog.wtf(TAG, "NullPointerException in getSummaryForAllUid", e);
625 throw e;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700626 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700627 }
628
629 @Override
630 public NetworkStatsHistory getHistoryForUid(
631 NetworkTemplate template, int uid, int set, int tag, int fields) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600632 // NOTE: We don't augment UID-level statistics
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700633 if (tag == TAG_NONE) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600634 return getUidComplete().getHistory(template, null, uid, set, tag, fields,
635 Long.MIN_VALUE, Long.MAX_VALUE, mAccessLevel, mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700636 } else {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600637 return getUidTagComplete().getHistory(template, null, uid, set, tag, fields,
638 Long.MIN_VALUE, Long.MAX_VALUE, mAccessLevel, mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700639 }
640 }
641
642 @Override
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100643 public NetworkStatsHistory getHistoryIntervalForUid(
644 NetworkTemplate template, int uid, int set, int tag, int fields,
645 long start, long end) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600646 // NOTE: We don't augment UID-level statistics
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100647 if (tag == TAG_NONE) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600648 return getUidComplete().getHistory(template, null, uid, set, tag, fields,
649 start, end, mAccessLevel, mCallingUid);
Antonio Cansado6965c182016-03-30 11:37:18 -0700650 } else if (uid == Binder.getCallingUid()) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600651 return getUidTagComplete().getHistory(template, null, uid, set, tag, fields,
652 start, end, mAccessLevel, mCallingUid);
Antonio Cansado6965c182016-03-30 11:37:18 -0700653 } else {
654 throw new SecurityException("Calling package " + mCallingPackage
655 + " cannot access tag information from a different uid");
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100656 }
657 }
658
659 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700660 public void close() {
661 mUidComplete = null;
662 mUidTagComplete = null;
663 }
664 };
Jeff Sharkey905b5892011-09-30 15:19:49 -0700665 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700666
Jeff Davidson1efb1332015-12-09 18:04:50 -0800667 private @NetworkStatsAccess.Level int checkAccessLevel(String callingPackage) {
668 return NetworkStatsAccess.checkAccessLevel(
669 mContext, Binder.getCallingUid(), callingPackage);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000670 }
671
Jeff Sharkey70c70532012-05-16 14:51:19 -0700672 /**
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600673 * Find the most relevant {@link SubscriptionPlan} for the given
674 * {@link NetworkTemplate} and flags. This is typically used to augment
675 * local measurement results to match a known anchor from the carrier.
676 */
677 private SubscriptionPlan resolveSubscriptionPlan(NetworkTemplate template, int flags) {
678 SubscriptionPlan plan = null;
679 if ((flags & NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN) != 0
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700680 && (template.getMatchRule() == NetworkTemplate.MATCH_MOBILE)
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600681 && mSettings.getAugmentEnabled()) {
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700682 if (LOGD) Slog.d(TAG, "Resolving plan for " + template);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600683 final long token = Binder.clearCallingIdentity();
684 try {
685 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
686 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
687 for (int subId : sm.getActiveSubscriptionIdList()) {
688 if (template.matchesSubscriberId(tm.getSubscriberId(subId))) {
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700689 if (LOGD) Slog.d(TAG, "Found active matching subId " + subId);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600690 final List<SubscriptionPlan> plans = sm.getSubscriptionPlans(subId);
691 if (!plans.isEmpty()) {
692 plan = plans.get(0);
693 }
694 }
695 }
696 } finally {
697 Binder.restoreCallingIdentity(token);
698 }
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700699 if (LOGD) Slog.d(TAG, "Resolved to plan " + plan);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600700 }
701 return plan;
702 }
703
704 /**
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700705 * Return network summary, splicing between DEV and XT stats when
706 * appropriate.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700707 */
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600708 private NetworkStats internalGetSummaryForNetwork(NetworkTemplate template, int flags,
709 long start, long end, @NetworkStatsAccess.Level int accessLevel, int callingUid) {
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700710 // We've been using pure XT stats long enough that we no longer need to
711 // splice DEV and XT together.
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600712 final NetworkStatsHistory history = internalGetHistoryForNetwork(template, flags, FIELD_ALL,
713 accessLevel, callingUid);
714
715 final long now = System.currentTimeMillis();
716 final NetworkStatsHistory.Entry entry = history.getValues(start, end, now, null);
717
718 final NetworkStats stats = new NetworkStats(end - start, 1);
Lorenzo Colittiada23ed2018-01-19 01:05:20 +0900719 stats.addValues(new NetworkStats.Entry(IFACE_ALL, UID_ALL, SET_ALL, TAG_NONE,
720 METERED_ALL, ROAMING_ALL, DEFAULT_NETWORK_ALL, entry.rxBytes, entry.rxPackets,
721 entry.txBytes, entry.txPackets, entry.operations));
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600722 return stats;
Jeff Sharkey70c70532012-05-16 14:51:19 -0700723 }
724
725 /**
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700726 * Return network history, splicing between DEV and XT stats when
727 * appropriate.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700728 */
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600729 private NetworkStatsHistory internalGetHistoryForNetwork(NetworkTemplate template,
730 int flags, int fields, @NetworkStatsAccess.Level int accessLevel, int callingUid) {
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700731 // We've been using pure XT stats long enough that we no longer need to
732 // splice DEV and XT together.
Jeff Sharkey4635f102017-09-01 11:27:13 -0600733 final SubscriptionPlan augmentPlan = resolveSubscriptionPlan(template, flags);
734 synchronized (mStatsLock) {
735 return mXtStatsCached.getHistory(template, augmentPlan,
736 UID_ALL, SET_ALL, TAG_NONE, fields, Long.MIN_VALUE, Long.MAX_VALUE,
737 accessLevel, callingUid);
738 }
Jeff Sharkey70c70532012-05-16 14:51:19 -0700739 }
740
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700741 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
742 assertSystemReady();
Jeff Sharkey4190a042012-04-21 15:36:48 -0700743 assertBandwidthControlEnabled();
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600744
745 // NOTE: if callers want to get non-augmented data, they should go
746 // through the public API
747 return internalGetSummaryForNetwork(template,
748 NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN, start, end,
749 NetworkStatsAccess.Level.DEVICE, Binder.getCallingUid()).getTotalBytes();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700750 }
751
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700752 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
753 assertSystemReady();
754 assertBandwidthControlEnabled();
755
756 final NetworkStatsCollection uidComplete;
757 synchronized (mStatsLock) {
758 uidComplete = mUidRecorder.getOrLoadCompleteLocked();
759 }
760 return uidComplete.getSummary(template, start, end, NetworkStatsAccess.Level.DEVICE,
761 android.os.Process.SYSTEM_UID);
762 }
763
Jeff Sharkey350083e2011-06-29 10:45:16 -0700764 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700765 public NetworkStats getDataLayerSnapshotForUid(int uid) throws RemoteException {
766 if (Binder.getCallingUid() != uid) {
767 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
768 }
Jeff Sharkey4190a042012-04-21 15:36:48 -0700769 assertBandwidthControlEnabled();
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700770
771 // TODO: switch to data layer stats once kernel exports
772 // for now, read network layer stats and flatten across all ifaces
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800773 final long token = Binder.clearCallingIdentity();
774 final NetworkStats networkLayer;
775 try {
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +0900776 networkLayer = mNetworkManager.getNetworkStatsUidDetail(uid,
777 NetworkStats.INTERFACES_ALL);
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800778 } finally {
779 Binder.restoreCallingIdentity(token);
780 }
781
Jeff Sharkey21a54782012-04-09 10:27:55 -0700782 // splice in operation counts
783 networkLayer.spliceOperationsFrom(mUidOperations);
784
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700785 final NetworkStats dataLayer = new NetworkStats(
786 networkLayer.getElapsedRealtime(), networkLayer.size());
787
788 NetworkStats.Entry entry = null;
789 for (int i = 0; i < networkLayer.size(); i++) {
790 entry = networkLayer.getValues(i, entry);
791 entry.iface = IFACE_ALL;
792 dataLayer.combineValues(entry);
793 }
794
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700795 return dataLayer;
796 }
797
798 @Override
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +0900799 public NetworkStats getDetailedUidStats(String[] requiredIfaces) {
800 try {
801 final String[] ifacesToQuery =
Remi NGUYEN VAN75525b32018-02-27 16:47:22 +0900802 NetworkStatsFactory.augmentWithStackedInterfaces(requiredIfaces);
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +0900803 return getNetworkStatsUidDetail(ifacesToQuery);
804 } catch (RemoteException e) {
805 Log.wtf(TAG, "Error compiling UID stats", e);
806 return new NetworkStats(0L, 0);
807 }
808 }
809
810 @Override
Jeff Sharkey234766a2012-04-10 19:48:07 -0700811 public String[] getMobileIfaces() {
812 return mMobileIfaces;
813 }
814
815 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700816 public void incrementOperationCount(int uid, int tag, int operationCount) {
817 if (Binder.getCallingUid() != uid) {
Jeff Sharkey9f09e6a72017-06-26 11:24:47 -0600818 mContext.enforceCallingOrSelfPermission(
819 android.Manifest.permission.UPDATE_DEVICE_STATS, TAG);
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700820 }
821
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700822 if (operationCount < 0) {
823 throw new IllegalArgumentException("operation count can only be incremented");
824 }
825 if (tag == TAG_NONE) {
826 throw new IllegalArgumentException("operation count must have specific tag");
827 }
828
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700829 synchronized (mStatsLock) {
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700830 final int set = mActiveUidCounterSet.get(uid, SET_DEFAULT);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800831 mUidOperations.combineValues(
832 mActiveIface, uid, set, tag, 0L, 0L, 0L, 0L, operationCount);
833 mUidOperations.combineValues(
834 mActiveIface, uid, set, TAG_NONE, 0L, 0L, 0L, 0L, operationCount);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700835 }
836 }
837
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700838 @VisibleForTesting
839 void setUidForeground(int uid, boolean uidForeground) {
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700840 synchronized (mStatsLock) {
841 final int set = uidForeground ? SET_FOREGROUND : SET_DEFAULT;
842 final int oldSet = mActiveUidCounterSet.get(uid, SET_DEFAULT);
843 if (oldSet != set) {
844 mActiveUidCounterSet.put(uid, set);
845 setKernelCounterSet(uid, set);
846 }
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700847 }
848 }
849
850 @Override
Lorenzo Colittic78da292018-01-19 00:50:48 +0900851 public void forceUpdateIfaces(Network[] defaultNetworks) {
Jeff Sharkey69736342014-12-08 14:50:12 -0800852 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
853 assertBandwidthControlEnabled();
854
855 final long token = Binder.clearCallingIdentity();
856 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +0900857 updateIfaces(defaultNetworks);
Jeff Sharkey69736342014-12-08 14:50:12 -0800858 } finally {
859 Binder.restoreCallingIdentity(token);
860 }
861 }
862
863 @Override
Jeff Sharkey350083e2011-06-29 10:45:16 -0700864 public void forceUpdate() {
865 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700866 assertBandwidthControlEnabled();
Jeff Sharkeye630f7b2012-01-31 17:12:53 -0800867
868 final long token = Binder.clearCallingIdentity();
869 try {
870 performPoll(FLAG_PERSIST_ALL);
871 } finally {
872 Binder.restoreCallingIdentity(token);
873 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700874 }
875
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700876 private void advisePersistThreshold(long thresholdBytes) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700877 assertBandwidthControlEnabled();
878
879 // clamp threshold into safe range
880 mPersistThreshold = MathUtils.constrain(thresholdBytes, 128 * KB_IN_BYTES, 2 * MB_IN_BYTES);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700881 if (LOGV) {
882 Slog.v(TAG, "advisePersistThreshold() given " + thresholdBytes + ", clamped to "
883 + mPersistThreshold);
884 }
885
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700886 // update and persist if beyond new thresholds
Jeff Sharkey9911a282018-02-14 22:29:11 -0700887 final long currentTime = mClock.millis();
Jeff Sharkey58015972012-05-07 11:08:49 -0700888 synchronized (mStatsLock) {
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700889 if (!mSystemReady) return;
890
Jeff Sharkey4635f102017-09-01 11:27:13 -0600891 updatePersistThresholdsLocked();
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700892
Jeff Sharkey58015972012-05-07 11:08:49 -0700893 mDevRecorder.maybePersistLocked(currentTime);
894 mXtRecorder.maybePersistLocked(currentTime);
895 mUidRecorder.maybePersistLocked(currentTime);
896 mUidTagRecorder.maybePersistLocked(currentTime);
897 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700898
899 // re-arm global alert
900 registerGlobalAlert();
901 }
902
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800903 @Override
Antonio Cansado6965c182016-03-30 11:37:18 -0700904 public DataUsageRequest registerUsageCallback(String callingPackage,
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800905 DataUsageRequest request, Messenger messenger, IBinder binder) {
906 checkNotNull(callingPackage, "calling package is null");
907 checkNotNull(request, "DataUsageRequest is null");
Antonio Cansado6965c182016-03-30 11:37:18 -0700908 checkNotNull(request.template, "NetworkTemplate is null");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800909 checkNotNull(messenger, "messenger is null");
910 checkNotNull(binder, "binder is null");
911
912 int callingUid = Binder.getCallingUid();
913 @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(callingPackage);
914 DataUsageRequest normalizedRequest;
915 final long token = Binder.clearCallingIdentity();
916 try {
917 normalizedRequest = mStatsObservers.register(request, messenger, binder,
918 callingUid, accessLevel);
919 } finally {
920 Binder.restoreCallingIdentity(token);
921 }
922
923 // Create baseline stats
924 mHandler.sendMessage(mHandler.obtainMessage(MSG_PERFORM_POLL, FLAG_PERSIST_ALL));
925
926 return normalizedRequest;
927 }
928
929 @Override
Antonio Cansado6965c182016-03-30 11:37:18 -0700930 public void unregisterUsageRequest(DataUsageRequest request) {
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800931 checkNotNull(request, "DataUsageRequest is null");
932
933 int callingUid = Binder.getCallingUid();
934 final long token = Binder.clearCallingIdentity();
935 try {
936 mStatsObservers.unregister(request, callingUid);
937 } finally {
938 Binder.restoreCallingIdentity(token);
939 }
940 }
941
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800942 @Override
943 public long getUidStats(int uid, int type) {
Chenbo Fengaedd6a32017-11-20 18:23:46 -0800944 return nativeGetUidStat(uid, type, checkBpfStatsEnable());
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800945 }
946
947 @Override
948 public long getIfaceStats(String iface, int type) {
Chenbo Fengaedd6a32017-11-20 18:23:46 -0800949 return nativeGetIfaceStat(iface, type, checkBpfStatsEnable());
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800950 }
951
952 @Override
953 public long getTotalStats(int type) {
Chenbo Fengaedd6a32017-11-20 18:23:46 -0800954 return nativeGetTotalStat(type, checkBpfStatsEnable());
955 }
956
957 private boolean checkBpfStatsEnable() {
958 return new File("/sys/fs/bpf/traffic_uid_stats_map").exists();
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800959 }
960
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700961 /**
962 * Update {@link NetworkStatsRecorder} and {@link #mGlobalAlertBytes} to
963 * reflect current {@link #mPersistThreshold} value. Always defers to
Jeff Sharkey625239a2012-09-26 22:03:49 -0700964 * {@link Global} values when defined.
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700965 */
Andreas Gampea36dc622018-02-05 17:19:22 -0800966 @GuardedBy("mStatsLock")
Jeff Sharkey4635f102017-09-01 11:27:13 -0600967 private void updatePersistThresholdsLocked() {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700968 mDevRecorder.setPersistThreshold(mSettings.getDevPersistBytes(mPersistThreshold));
969 mXtRecorder.setPersistThreshold(mSettings.getXtPersistBytes(mPersistThreshold));
970 mUidRecorder.setPersistThreshold(mSettings.getUidPersistBytes(mPersistThreshold));
971 mUidTagRecorder.setPersistThreshold(mSettings.getUidTagPersistBytes(mPersistThreshold));
972 mGlobalAlertBytes = mSettings.getGlobalAlertBytes(mPersistThreshold);
973 }
974
Jeff Sharkey75279902011-05-24 18:39:45 -0700975 /**
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700976 * Receiver that watches for {@link Tethering} to claim interface pairs.
977 */
978 private BroadcastReceiver mTetherReceiver = new BroadcastReceiver() {
979 @Override
980 public void onReceive(Context context, Intent intent) {
981 // on background handler thread, and verified CONNECTIVITY_INTERNAL
982 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700983 performPoll(FLAG_PERSIST_NETWORK);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700984 }
985 };
986
Jeff Sharkey75279902011-05-24 18:39:45 -0700987 private BroadcastReceiver mPollReceiver = new BroadcastReceiver() {
988 @Override
989 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700990 // on background handler thread, and verified UPDATE_DEVICE_STATS
991 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700992 performPoll(FLAG_PERSIST_ALL);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700993
994 // verify that we're watching global alert
995 registerGlobalAlert();
Jeff Sharkey75279902011-05-24 18:39:45 -0700996 }
997 };
998
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700999 private BroadcastReceiver mRemovedReceiver = new BroadcastReceiver() {
1000 @Override
1001 public void onReceive(Context context, Intent intent) {
1002 // on background handler thread, and UID_REMOVED is protected
1003 // broadcast.
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001004
1005 final int uid = intent.getIntExtra(EXTRA_UID, -1);
1006 if (uid == -1) return;
1007
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001008 synchronized (mStatsLock) {
Jeff Sharkey62489262011-07-17 12:53:28 -07001009 mWakeLock.acquire();
1010 try {
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001011 removeUidsLocked(uid);
1012 } finally {
1013 mWakeLock.release();
1014 }
1015 }
1016 }
1017 };
1018
1019 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
1020 @Override
1021 public void onReceive(Context context, Intent intent) {
1022 // On background handler thread, and USER_REMOVED is protected
1023 // broadcast.
1024
1025 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1026 if (userId == -1) return;
1027
1028 synchronized (mStatsLock) {
1029 mWakeLock.acquire();
1030 try {
1031 removeUserLocked(userId);
Jeff Sharkey62489262011-07-17 12:53:28 -07001032 } finally {
1033 mWakeLock.release();
1034 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001035 }
1036 }
1037 };
1038
Jeff Sharkey75279902011-05-24 18:39:45 -07001039 private BroadcastReceiver mShutdownReceiver = new BroadcastReceiver() {
1040 @Override
1041 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001042 // SHUTDOWN is protected broadcast.
Jeff Sharkey75279902011-05-24 18:39:45 -07001043 synchronized (mStatsLock) {
Jeff Sharkey3f391352011-06-05 17:42:53 -07001044 shutdownLocked();
Jeff Sharkey75279902011-05-24 18:39:45 -07001045 }
1046 }
1047 };
1048
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001049 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001050 * Observer that watches for {@link INetworkManagementService} alerts.
1051 */
Jeff Sharkey216c1812012-08-05 14:29:23 -07001052 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001053 @Override
1054 public void limitReached(String limitName, String iface) {
1055 // only someone like NMS should be calling us
1056 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1057
1058 if (LIMIT_GLOBAL_ALERT.equals(limitName)) {
1059 // kick off background poll to collect network stats; UID stats
1060 // are handled during normal polling interval.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001061 final int flags = FLAG_PERSIST_NETWORK;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001062 mHandler.obtainMessage(MSG_PERFORM_POLL, flags, 0).sendToTarget();
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001063
1064 // re-arm global alert for next update
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001065 mHandler.obtainMessage(MSG_REGISTER_GLOBAL_ALERT).sendToTarget();
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001066 }
1067 }
1068 };
1069
Lorenzo Colittic78da292018-01-19 00:50:48 +09001070 private void updateIfaces(Network[] defaultNetworks) {
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001071 synchronized (mStatsLock) {
1072 mWakeLock.acquire();
1073 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09001074 updateIfacesLocked(defaultNetworks);
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001075 } finally {
1076 mWakeLock.release();
1077 }
1078 }
1079 }
1080
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001081 /**
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001082 * Inspect all current {@link NetworkState} to derive mapping from {@code
1083 * iface} to {@link NetworkStatsHistory}. When multiple {@link NetworkInfo}
1084 * are active on a single {@code iface}, they are combined under a single
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001085 * {@link NetworkIdentitySet}.
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001086 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001087 @GuardedBy("mStatsLock")
Lorenzo Colittic78da292018-01-19 00:50:48 +09001088 private void updateIfacesLocked(Network[] defaultNetworks) {
Jeff Sharkey6341fce2012-03-06 19:59:57 -08001089 if (!mSystemReady) return;
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001090 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001091
1092 // take one last stats snapshot before updating iface mapping. this
1093 // isn't perfect, since the kernel may already be counting traffic from
1094 // the updated network.
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001095
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001096 // poll, but only persist network stats to keep codepath fast. UID stats
1097 // will be persisted during next alarm poll event.
1098 performPollLocked(FLAG_PERSIST_NETWORK);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001099
1100 final NetworkState[] states;
Jeff Sharkey63abc372012-01-11 18:38:16 -08001101 final LinkProperties activeLink;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001102 try {
1103 states = mConnManager.getAllNetworkState();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001104 activeLink = mConnManager.getActiveLinkProperties();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001105 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001106 // ignored; service lives in system_server
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001107 return;
1108 }
1109
Jeff Sharkey63abc372012-01-11 18:38:16 -08001110 mActiveIface = activeLink != null ? activeLink.getInterfaceName() : null;
1111
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001112 // Rebuild active interfaces based on connected networks
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001113 mActiveIfaces.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001114 mActiveUidIfaces.clear();
Lorenzo Colittic78da292018-01-19 00:50:48 +09001115 if (defaultNetworks != null) {
1116 // Caller is ConnectivityService. Update the list of default networks.
1117 mDefaultNetworks = defaultNetworks;
1118 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001119
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001120 final ArraySet<String> mobileIfaces = new ArraySet<>();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001121 for (NetworkState state : states) {
1122 if (state.networkInfo.isConnected()) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001123 final boolean isMobile = isNetworkTypeMobile(state.networkInfo.getType());
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001124 final boolean isDefault = ArrayUtils.contains(mDefaultNetworks, state.network);
1125 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1126 isDefault);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001127
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001128 // Traffic occurring on the base interface is always counted for
1129 // both total usage and UID details.
1130 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001131 if (baseIface != null) {
1132 findOrCreateNetworkIdentitySet(mActiveIfaces, baseIface).add(ident);
1133 findOrCreateNetworkIdentitySet(mActiveUidIfaces, baseIface).add(ident);
Jack Yub6587ea2016-06-22 11:35:10 -07001134
1135 // Build a separate virtual interface for VT (Video Telephony) data usage.
1136 // Only do this when IMS is not metered, but VT is metered.
1137 // If IMS is metered, then the IMS network usage has already included VT usage.
1138 // VT is considered always metered in framework's layer. If VT is not metered
1139 // per carrier's policy, modem will report 0 usage for VT calls.
1140 if (state.networkCapabilities.hasCapability(
1141 NetworkCapabilities.NET_CAPABILITY_IMS) && !ident.getMetered()) {
1142
1143 // Copy the identify from IMS one but mark it as metered.
1144 NetworkIdentity vtIdent = new NetworkIdentity(ident.getType(),
1145 ident.getSubType(), ident.getSubscriberId(), ident.getNetworkId(),
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001146 ident.getRoaming(), true /* metered */,
1147 true /* onDefaultNetwork */);
Jack Yub6587ea2016-06-22 11:35:10 -07001148 findOrCreateNetworkIdentitySet(mActiveIfaces, VT_INTERFACE).add(vtIdent);
1149 findOrCreateNetworkIdentitySet(mActiveUidIfaces, VT_INTERFACE).add(vtIdent);
1150 }
1151
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001152 if (isMobile) {
1153 mobileIfaces.add(baseIface);
1154 }
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001155 }
1156
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001157 // Traffic occurring on stacked interfaces is usually clatd,
1158 // which is already accounted against its final egress interface
1159 // by the kernel. Thus, we only need to collect stacked
1160 // interface stats at the UID level.
1161 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1162 for (LinkProperties stackedLink : stackedLinks) {
1163 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001164 if (stackedIface != null) {
1165 findOrCreateNetworkIdentitySet(mActiveUidIfaces, stackedIface).add(ident);
1166 if (isMobile) {
1167 mobileIfaces.add(stackedIface);
1168 }
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001169
1170 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
Jeff Sharkey234766a2012-04-10 19:48:07 -07001171 }
1172 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001173 }
1174 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001175
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001176 mMobileIfaces = mobileIfaces.toArray(new String[mobileIfaces.size()]);
1177 }
1178
1179 private static <K> NetworkIdentitySet findOrCreateNetworkIdentitySet(
1180 ArrayMap<K, NetworkIdentitySet> map, K key) {
1181 NetworkIdentitySet ident = map.get(key);
1182 if (ident == null) {
1183 ident = new NetworkIdentitySet();
1184 map.put(key, ident);
1185 }
1186 return ident;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001187 }
1188
Andreas Gampea36dc622018-02-05 17:19:22 -08001189 @GuardedBy("mStatsLock")
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001190 private void recordSnapshotLocked(long currentTime) throws RemoteException {
1191 // snapshot and record current counters; read UID stats first to
Jack Yub6587ea2016-06-22 11:35:10 -07001192 // avoid over counting dev stats.
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001193 final NetworkStats uidSnapshot = getNetworkStatsUidDetail(INTERFACES_ALL);
Jack Yuf9d559c2017-05-26 16:08:22 -07001194 final NetworkStats xtSnapshot = getNetworkStatsXt();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001195 final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
1196
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001197 // Tethering snapshot for dev and xt stats. Counts per-interface data from tethering stats
1198 // providers that isn't already counted by dev and XT stats.
1199 final NetworkStats tetherSnapshot = getNetworkStatsTethering(STATS_PER_IFACE);
1200 xtSnapshot.combineAllValues(tetherSnapshot);
1201 devSnapshot.combineAllValues(tetherSnapshot);
Jeff Davidson4ff3bcf2016-06-15 13:31:52 -07001202
1203 // For xt/dev, we pass a null VPN array because usage is aggregated by UID, so VPN traffic
1204 // can't be reattributed to responsible apps.
1205 mDevRecorder.recordSnapshotLocked(
1206 devSnapshot, mActiveIfaces, null /* vpnArray */, currentTime);
1207 mXtRecorder.recordSnapshotLocked(
1208 xtSnapshot, mActiveIfaces, null /* vpnArray */, currentTime);
1209
1210 // For per-UID stats, pass the VPN info so VPN traffic is reattributed to responsible apps.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001211 VpnInfo[] vpnArray = mConnManager.getAllVpnInfo();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001212 mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
1213 mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001214
1215 // We need to make copies of member fields that are sent to the observer to avoid
1216 // a race condition between the service handler thread and the observer's
1217 mStatsObservers.updateStats(xtSnapshot, uidSnapshot, new ArrayMap<>(mActiveIfaces),
1218 new ArrayMap<>(mActiveUidIfaces), vpnArray, currentTime);
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001219 }
1220
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001221 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001222 * Bootstrap initial stats snapshot, usually during {@link #systemReady()}
1223 * so we have baseline values without double-counting.
1224 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001225 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -08001226 private void bootstrapStatsLocked() {
Jeff Sharkey9911a282018-02-14 22:29:11 -07001227 final long currentTime = mClock.millis();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001228
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001229 try {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001230 recordSnapshotLocked(currentTime);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001231 } catch (IllegalStateException e) {
1232 Slog.w(TAG, "problem reading network stats: " + e);
1233 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001234 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001235 }
1236 }
1237
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001238 private void performPoll(int flags) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001239 synchronized (mStatsLock) {
1240 mWakeLock.acquire();
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001241
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001242 try {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001243 performPollLocked(flags);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001244 } finally {
1245 mWakeLock.release();
1246 }
1247 }
1248 }
1249
1250 /**
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001251 * Periodic poll operation, reading current statistics and recording into
1252 * {@link NetworkStatsHistory}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001253 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001254 @GuardedBy("mStatsLock")
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001255 private void performPollLocked(int flags) {
Jeff Sharkey6341fce2012-03-06 19:59:57 -08001256 if (!mSystemReady) return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001257 if (LOGV) Slog.v(TAG, "performPollLocked(flags=0x" + Integer.toHexString(flags) + ")");
Jeff Sharkey6341fce2012-03-06 19:59:57 -08001258
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001259 final long startRealtime = SystemClock.elapsedRealtime();
Jeff Sharkey75279902011-05-24 18:39:45 -07001260
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001261 final boolean persistNetwork = (flags & FLAG_PERSIST_NETWORK) != 0;
1262 final boolean persistUid = (flags & FLAG_PERSIST_UID) != 0;
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001263 final boolean persistForce = (flags & FLAG_PERSIST_FORCE) != 0;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001264
Jeff Sharkey75279902011-05-24 18:39:45 -07001265 // TODO: consider marking "untrusted" times in historical stats
Jeff Sharkey9911a282018-02-14 22:29:11 -07001266 final long currentTime = mClock.millis();
Jeff Sharkey75279902011-05-24 18:39:45 -07001267
Jeff Sharkey75279902011-05-24 18:39:45 -07001268 try {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001269 recordSnapshotLocked(currentTime);
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001270 } catch (IllegalStateException e) {
1271 Log.wtf(TAG, "problem reading network stats", e);
Jeff Sharkey905b5892011-09-30 15:19:49 -07001272 return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001273 } catch (RemoteException e) {
1274 // ignored; service lives in system_server
Jeff Sharkey905b5892011-09-30 15:19:49 -07001275 return;
1276 }
1277
Jeff Sharkey63abc372012-01-11 18:38:16 -08001278 // persist any pending data depending on requested flags
1279 if (persistForce) {
1280 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001281 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001282 mUidRecorder.forcePersistLocked(currentTime);
1283 mUidTagRecorder.forcePersistLocked(currentTime);
1284 } else {
1285 if (persistNetwork) {
1286 mDevRecorder.maybePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001287 mXtRecorder.maybePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001288 }
1289 if (persistUid) {
1290 mUidRecorder.maybePersistLocked(currentTime);
1291 mUidTagRecorder.maybePersistLocked(currentTime);
1292 }
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001293 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001294
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001295 if (LOGV) {
1296 final long duration = SystemClock.elapsedRealtime() - startRealtime;
1297 Slog.v(TAG, "performPollLocked() took " + duration + "ms");
1298 }
1299
Jeff Sharkey63abc372012-01-11 18:38:16 -08001300 if (mSettings.getSampleEnabled()) {
Jeff Sharkey905b5892011-09-30 15:19:49 -07001301 // sample stats after each full poll
Jeff Sharkey63abc372012-01-11 18:38:16 -08001302 performSampleLocked();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001303 }
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001304
Jeff Sharkey497e4432011-06-14 17:27:29 -07001305 // finally, dispatch updated event to any listeners
1306 final Intent updatedIntent = new Intent(ACTION_NETWORK_STATS_UPDATED);
1307 updatedIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001308 mContext.sendBroadcastAsUser(updatedIntent, UserHandle.ALL,
1309 READ_NETWORK_USAGE_HISTORY);
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001310 }
1311
1312 /**
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001313 * Sample recent statistics summary into {@link EventLog}.
1314 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001315 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -08001316 private void performSampleLocked() {
1317 // TODO: migrate trustedtime fixes to separate binary log events
Jeff Sharkey9911a282018-02-14 22:29:11 -07001318 final long currentTime = mClock.millis();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001319
Jeff Sharkey63abc372012-01-11 18:38:16 -08001320 NetworkTemplate template;
1321 NetworkStats.Entry devTotal;
1322 NetworkStats.Entry xtTotal;
1323 NetworkStats.Entry uidTotal;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001324
1325 // collect mobile sample
Jeff Sharkey234766a2012-04-10 19:48:07 -07001326 template = buildTemplateMobileWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001327 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001328 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001329 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001330
Jeff Sharkey905b5892011-09-30 15:19:49 -07001331 EventLogTags.writeNetstatsMobileSample(
1332 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1333 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1334 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey9911a282018-02-14 22:29:11 -07001335 currentTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001336
1337 // collect wifi sample
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001338 template = buildTemplateWifiWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001339 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001340 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001341 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
1342
Jeff Sharkey905b5892011-09-30 15:19:49 -07001343 EventLogTags.writeNetstatsWifiSample(
1344 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1345 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1346 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey9911a282018-02-14 22:29:11 -07001347 currentTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001348 }
1349
1350 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001351 * Clean up {@link #mUidRecorder} after UID is removed.
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001352 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001353 @GuardedBy("mStatsLock")
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001354 private void removeUidsLocked(int... uids) {
1355 if (LOGV) Slog.v(TAG, "removeUidsLocked() for UIDs " + Arrays.toString(uids));
1356
1357 // Perform one last poll before removing
Jeff Sharkey163e6442011-10-31 16:37:52 -07001358 performPollLocked(FLAG_PERSIST_ALL);
1359
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001360 mUidRecorder.removeUidsLocked(uids);
1361 mUidTagRecorder.removeUidsLocked(uids);
Jeff Sharkey163e6442011-10-31 16:37:52 -07001362
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001363 // Clear kernel stats associated with UID
1364 for (int uid : uids) {
1365 resetKernelUidStats(uid);
1366 }
1367 }
1368
1369 /**
1370 * Clean up {@link #mUidRecorder} after user is removed.
1371 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001372 @GuardedBy("mStatsLock")
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001373 private void removeUserLocked(int userId) {
1374 if (LOGV) Slog.v(TAG, "removeUserLocked() for userId=" + userId);
1375
1376 // Build list of UIDs that we should clean up
1377 int[] uids = new int[0];
1378 final List<ApplicationInfo> apps = mContext.getPackageManager().getInstalledApplications(
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001379 PackageManager.MATCH_ANY_USER
1380 | PackageManager.MATCH_DISABLED_COMPONENTS);
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001381 for (ApplicationInfo app : apps) {
1382 final int uid = UserHandle.getUid(userId, app.uid);
1383 uids = ArrayUtils.appendInt(uids, uid);
1384 }
1385
1386 removeUidsLocked(uids);
Jeff Sharkey75279902011-05-24 18:39:45 -07001387 }
1388
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001389 private class NetworkStatsManagerInternalImpl extends NetworkStatsManagerInternal {
1390 @Override
1391 public long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
1392 return NetworkStatsService.this.getNetworkTotalBytes(template, start, end);
1393 }
1394
1395 @Override
1396 public NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
1397 return NetworkStatsService.this.getNetworkUidBytes(template, start, end);
1398 }
1399
1400 @Override
1401 public void setUidForeground(int uid, boolean uidForeground) {
1402 NetworkStatsService.this.setUidForeground(uid, uidForeground);
1403 }
1404
1405 @Override
1406 public void advisePersistThreshold(long thresholdBytes) {
1407 NetworkStatsService.this.advisePersistThreshold(thresholdBytes);
1408 }
1409
1410 @Override
1411 public void forceUpdate() {
1412 NetworkStatsService.this.forceUpdate();
1413 }
1414 }
1415
Jeff Sharkey75279902011-05-24 18:39:45 -07001416 @Override
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001417 protected void dump(FileDescriptor fd, PrintWriter rawWriter, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001418 if (!DumpUtils.checkDumpPermission(mContext, TAG, rawWriter)) return;
Jeff Sharkey75279902011-05-24 18:39:45 -07001419
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001420 long duration = DateUtils.DAY_IN_MILLIS;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001421 final HashSet<String> argSet = new HashSet<String>();
1422 for (String arg : args) {
1423 argSet.add(arg);
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001424
1425 if (arg.startsWith("--duration=")) {
1426 try {
1427 duration = Long.parseLong(arg.substring(11));
1428 } catch (NumberFormatException ignored) {
1429 }
1430 }
Jeff Sharkey75279902011-05-24 18:39:45 -07001431 }
1432
Jeff Sharkey706498d2012-02-06 17:35:07 -08001433 // usage: dumpsys netstats --full --uid --tag --poll --checkin
Jeff Sharkey63abc372012-01-11 18:38:16 -08001434 final boolean poll = argSet.contains("--poll") || argSet.contains("poll");
Jeff Sharkey706498d2012-02-06 17:35:07 -08001435 final boolean checkin = argSet.contains("--checkin");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001436 final boolean fullHistory = argSet.contains("--full") || argSet.contains("full");
1437 final boolean includeUid = argSet.contains("--uid") || argSet.contains("detail");
1438 final boolean includeTag = argSet.contains("--tag") || argSet.contains("detail");
1439
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001440 final IndentingPrintWriter pw = new IndentingPrintWriter(rawWriter, " ");
Jeff Sharkey350083e2011-06-29 10:45:16 -07001441
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001442 synchronized (mStatsLock) {
Makoto Onukida65a522017-01-13 10:23:30 -08001443 if (args.length > 0 && "--proto".equals(args[0])) {
1444 // In this case ignore all other arguments.
Jeff Sharkey4635f102017-09-01 11:27:13 -06001445 dumpProtoLocked(fd);
Makoto Onukida65a522017-01-13 10:23:30 -08001446 return;
1447 }
1448
Jeff Sharkey63abc372012-01-11 18:38:16 -08001449 if (poll) {
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001450 performPollLocked(FLAG_PERSIST_ALL | FLAG_PERSIST_FORCE);
Jeff Sharkey3f391352011-06-05 17:42:53 -07001451 pw.println("Forced poll");
1452 return;
1453 }
1454
Jeff Sharkey706498d2012-02-06 17:35:07 -08001455 if (checkin) {
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001456 final long end = System.currentTimeMillis();
1457 final long start = end - duration;
1458
1459 pw.print("v1,");
1460 pw.print(start / SECOND_IN_MILLIS); pw.print(',');
1461 pw.print(end / SECOND_IN_MILLIS); pw.println();
1462
1463 pw.println("xt");
1464 mXtRecorder.dumpCheckin(rawWriter, start, end);
1465
1466 if (includeUid) {
1467 pw.println("uid");
1468 mUidRecorder.dumpCheckin(rawWriter, start, end);
Jeff Sharkey706498d2012-02-06 17:35:07 -08001469 }
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001470 if (includeTag) {
1471 pw.println("tag");
1472 mUidTagRecorder.dumpCheckin(rawWriter, start, end);
1473 }
Jeff Sharkey706498d2012-02-06 17:35:07 -08001474 return;
1475 }
1476
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001477 pw.println("Active interfaces:");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001478 pw.increaseIndent();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001479 for (int i = 0; i < mActiveIfaces.size(); i++) {
1480 pw.printPair("iface", mActiveIfaces.keyAt(i));
1481 pw.printPair("ident", mActiveIfaces.valueAt(i));
1482 pw.println();
1483 }
1484 pw.decreaseIndent();
1485
1486 pw.println("Active UID interfaces:");
1487 pw.increaseIndent();
1488 for (int i = 0; i < mActiveUidIfaces.size(); i++) {
1489 pw.printPair("iface", mActiveUidIfaces.keyAt(i));
1490 pw.printPair("ident", mActiveUidIfaces.valueAt(i));
1491 pw.println();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001492 }
Jeff Sharkey63abc372012-01-11 18:38:16 -08001493 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001494
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +09001495 // Get the top openSession callers
1496 final SparseIntArray calls;
1497 synchronized (mOpenSessionCallsPerUid) {
1498 calls = mOpenSessionCallsPerUid.clone();
1499 }
1500
1501 final int N = calls.size();
1502 final long[] values = new long[N];
1503 for (int j = 0; j < N; j++) {
1504 values[j] = ((long) calls.valueAt(j) << 32) | calls.keyAt(j);
1505 }
1506 Arrays.sort(values);
1507
1508 pw.println("Top openSession callers (uid=count):");
1509 pw.increaseIndent();
1510 final int end = Math.max(0, N - DUMP_STATS_SESSION_COUNT);
1511 for (int j = N - 1; j >= end; j--) {
1512 final int uid = (int) (values[j] & 0xffffffff);
1513 final int count = (int) (values[j] >> 32);
1514 pw.print(uid); pw.print("="); pw.println(count);
1515 }
1516 pw.decreaseIndent();
1517 pw.println();
1518
Jeff Sharkey63abc372012-01-11 18:38:16 -08001519 pw.println("Dev stats:");
1520 pw.increaseIndent();
1521 mDevRecorder.dumpLocked(pw, fullHistory);
1522 pw.decreaseIndent();
1523
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001524 pw.println("Xt stats:");
1525 pw.increaseIndent();
1526 mXtRecorder.dumpLocked(pw, fullHistory);
1527 pw.decreaseIndent();
1528
Jeff Sharkey63abc372012-01-11 18:38:16 -08001529 if (includeUid) {
1530 pw.println("UID stats:");
1531 pw.increaseIndent();
1532 mUidRecorder.dumpLocked(pw, fullHistory);
1533 pw.decreaseIndent();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001534 }
1535
Jeff Sharkey63abc372012-01-11 18:38:16 -08001536 if (includeTag) {
1537 pw.println("UID tag stats:");
1538 pw.increaseIndent();
1539 mUidTagRecorder.dumpLocked(pw, fullHistory);
1540 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001541 }
1542 }
1543 }
1544
Andreas Gampea36dc622018-02-05 17:19:22 -08001545 @GuardedBy("mStatsLock")
Jeff Sharkey4635f102017-09-01 11:27:13 -06001546 private void dumpProtoLocked(FileDescriptor fd) {
Makoto Onukida65a522017-01-13 10:23:30 -08001547 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1548
1549 // TODO Right now it writes all history. Should it limit to the "since-boot" log?
1550
1551 dumpInterfaces(proto, NetworkStatsServiceDumpProto.ACTIVE_INTERFACES, mActiveIfaces);
1552 dumpInterfaces(proto, NetworkStatsServiceDumpProto.ACTIVE_UID_INTERFACES, mActiveUidIfaces);
1553 mDevRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.DEV_STATS);
1554 mXtRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.XT_STATS);
1555 mUidRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.UID_STATS);
1556 mUidTagRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.UID_TAG_STATS);
1557
1558 proto.flush();
1559 }
1560
1561 private static void dumpInterfaces(ProtoOutputStream proto, long tag,
1562 ArrayMap<String, NetworkIdentitySet> ifaces) {
1563 for (int i = 0; i < ifaces.size(); i++) {
1564 final long start = proto.start(tag);
1565
1566 proto.write(NetworkInterfaceProto.INTERFACE, ifaces.keyAt(i));
1567 ifaces.valueAt(i).writeToProto(proto, NetworkInterfaceProto.IDENTITIES);
1568
1569 proto.end(start);
1570 }
1571 }
1572
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001573 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001574 * Return snapshot of current UID statistics, including any
Jack Yuf9d559c2017-05-26 16:08:22 -07001575 * {@link TrafficStats#UID_TETHERING}, video calling data usage, and {@link #mUidOperations}
1576 * values.
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001577 *
1578 * @param ifaces A list of interfaces the stats should be restricted to, or
1579 * {@link NetworkStats#INTERFACES_ALL}.
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001580 */
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001581 private NetworkStats getNetworkStatsUidDetail(String[] ifaces)
1582 throws RemoteException {
1583
Remi NGUYEN VAN75525b32018-02-27 16:47:22 +09001584 // TODO: remove 464xlat adjustments from NetworkStatsFactory and apply all at once here.
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001585 final NetworkStats uidSnapshot = mNetworkManager.getNetworkStatsUidDetail(UID_ALL,
1586 ifaces);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001587
Jeff Sharkey63abc372012-01-11 18:38:16 -08001588 // fold tethering stats and operations into uid snapshot
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001589 final NetworkStats tetherSnapshot = getNetworkStatsTethering(STATS_PER_UID);
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001590 tetherSnapshot.filter(UID_ALL, ifaces, TAG_ALL);
Remi NGUYEN VAN75525b32018-02-27 16:47:22 +09001591 NetworkStatsFactory.apply464xlatAdjustments(uidSnapshot, tetherSnapshot);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001592 uidSnapshot.combineAllValues(tetherSnapshot);
Jack Yuf9d559c2017-05-26 16:08:22 -07001593
1594 final TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(
1595 Context.TELEPHONY_SERVICE);
1596
1597 // fold video calling data usage stats into uid snapshot
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001598 final NetworkStats vtStats = telephonyManager.getVtDataUsage(STATS_PER_UID);
Jack Yuf9d559c2017-05-26 16:08:22 -07001599 if (vtStats != null) {
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001600 vtStats.filter(UID_ALL, ifaces, TAG_ALL);
Remi NGUYEN VAN75525b32018-02-27 16:47:22 +09001601 NetworkStatsFactory.apply464xlatAdjustments(uidSnapshot, vtStats);
Jack Yuf9d559c2017-05-26 16:08:22 -07001602 uidSnapshot.combineAllValues(vtStats);
1603 }
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001604
Jeff Sharkey63abc372012-01-11 18:38:16 -08001605 uidSnapshot.combineAllValues(mUidOperations);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001606
Jeff Sharkey63abc372012-01-11 18:38:16 -08001607 return uidSnapshot;
Jeff Sharkey75279902011-05-24 18:39:45 -07001608 }
1609
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001610 /**
Jack Yuf9d559c2017-05-26 16:08:22 -07001611 * Return snapshot of current XT statistics with video calling data usage statistics.
Jack Yub6587ea2016-06-22 11:35:10 -07001612 */
Jack Yuf9d559c2017-05-26 16:08:22 -07001613 private NetworkStats getNetworkStatsXt() throws RemoteException {
Jack Yub6587ea2016-06-22 11:35:10 -07001614 final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
1615
Jack Yuf9d559c2017-05-26 16:08:22 -07001616 final TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(
Jack Yub6587ea2016-06-22 11:35:10 -07001617 Context.TELEPHONY_SERVICE);
1618
Jack Yuf9d559c2017-05-26 16:08:22 -07001619 // Merge video calling data usage into XT
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001620 final NetworkStats vtSnapshot = telephonyManager.getVtDataUsage(STATS_PER_IFACE);
Jack Yuf9d559c2017-05-26 16:08:22 -07001621 if (vtSnapshot != null) {
1622 xtSnapshot.combineAllValues(vtSnapshot);
1623 }
Jack Yub6587ea2016-06-22 11:35:10 -07001624
1625 return xtSnapshot;
1626 }
1627
1628 /**
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001629 * Return snapshot of current tethering statistics. Will return empty
1630 * {@link NetworkStats} if any problems are encountered.
1631 */
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001632 private NetworkStats getNetworkStatsTethering(int how) throws RemoteException {
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001633 try {
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001634 return mNetworkManager.getNetworkStatsTethering(how);
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001635 } catch (IllegalStateException e) {
1636 Log.wtf(TAG, "problem reading network stats", e);
1637 return new NetworkStats(0L, 10);
1638 }
1639 }
1640
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001641 @VisibleForTesting
1642 static class HandlerCallback implements Handler.Callback {
1643 private final NetworkStatsService mService;
1644
1645 HandlerCallback(NetworkStatsService service) {
1646 this.mService = service;
1647 }
1648
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001649 @Override
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001650 public boolean handleMessage(Message msg) {
1651 switch (msg.what) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001652 case MSG_PERFORM_POLL: {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001653 final int flags = msg.arg1;
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001654 mService.performPoll(flags);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001655 return true;
1656 }
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001657 case MSG_UPDATE_IFACES: {
Lorenzo Colittic78da292018-01-19 00:50:48 +09001658 mService.updateIfaces(null);
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001659 return true;
1660 }
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001661 case MSG_REGISTER_GLOBAL_ALERT: {
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001662 mService.registerGlobalAlert();
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001663 return true;
1664 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001665 default: {
1666 return false;
1667 }
1668 }
1669 }
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001670 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001671
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001672 private void assertSystemReady() {
1673 if (!mSystemReady) {
1674 throw new IllegalStateException("System not ready");
1675 }
1676 }
1677
Jeff Sharkey4190a042012-04-21 15:36:48 -07001678 private void assertBandwidthControlEnabled() {
1679 if (!isBandwidthControlEnabled()) {
1680 throw new IllegalStateException("Bandwidth module disabled");
1681 }
1682 }
1683
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001684 private boolean isBandwidthControlEnabled() {
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001685 final long token = Binder.clearCallingIdentity();
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001686 try {
1687 return mNetworkManager.isBandwidthControlEnabled();
1688 } catch (RemoteException e) {
1689 // ignored; service lives in system_server
1690 return false;
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001691 } finally {
1692 Binder.restoreCallingIdentity(token);
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001693 }
1694 }
1695
Jeff Sharkey63abc372012-01-11 18:38:16 -08001696 private class DropBoxNonMonotonicObserver implements NonMonotonicObserver<String> {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001697 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001698 public void foundNonMonotonic(NetworkStats left, int leftIndex, NetworkStats right,
1699 int rightIndex, String cookie) {
1700 Log.w(TAG, "found non-monotonic values; saving to dropbox");
1701
1702 // record error for debugging
1703 final StringBuilder builder = new StringBuilder();
1704 builder.append("found non-monotonic " + cookie + " values at left[" + leftIndex
1705 + "] - right[" + rightIndex + "]\n");
1706 builder.append("left=").append(left).append('\n');
1707 builder.append("right=").append(right).append('\n');
1708
1709 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
1710 Context.DROPBOX_SERVICE);
1711 dropBox.addText(TAG_NETSTATS_ERROR, builder.toString());
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001712 }
1713 }
1714
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001715 /**
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001716 * Default external settings that read from
Jeff Sharkey625239a2012-09-26 22:03:49 -07001717 * {@link android.provider.Settings.Global}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001718 */
1719 private static class DefaultNetworkStatsSettings implements NetworkStatsSettings {
1720 private final ContentResolver mResolver;
1721
1722 public DefaultNetworkStatsSettings(Context context) {
1723 mResolver = checkNotNull(context.getContentResolver());
1724 // TODO: adjust these timings for production builds
1725 }
1726
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001727 private long getGlobalLong(String name, long def) {
1728 return Settings.Global.getLong(mResolver, name, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001729 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001730 private boolean getGlobalBoolean(String name, boolean def) {
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001731 final int defInt = def ? 1 : 0;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001732 return Settings.Global.getInt(mResolver, name, defInt) != 0;
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001733 }
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001734
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001735 @Override
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001736 public long getPollInterval() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001737 return getGlobalLong(NETSTATS_POLL_INTERVAL, 30 * MINUTE_IN_MILLIS);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001738 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001739 @Override
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001740 public long getGlobalAlertBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001741 return getGlobalLong(NETSTATS_GLOBAL_ALERT_BYTES, def);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001742 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001743 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001744 public boolean getSampleEnabled() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001745 return getGlobalBoolean(NETSTATS_SAMPLE_ENABLED, true);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001746 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001747 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -06001748 public boolean getAugmentEnabled() {
1749 return getGlobalBoolean(NETSTATS_AUGMENT_ENABLED, true);
1750 }
1751 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001752 public Config getDevConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001753 return new Config(getGlobalLong(NETSTATS_DEV_BUCKET_DURATION, HOUR_IN_MILLIS),
1754 getGlobalLong(NETSTATS_DEV_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1755 getGlobalLong(NETSTATS_DEV_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001756 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001757 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001758 public Config getXtConfig() {
1759 return getDevConfig();
1760 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001761 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001762 public Config getUidConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001763 return new Config(getGlobalLong(NETSTATS_UID_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1764 getGlobalLong(NETSTATS_UID_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1765 getGlobalLong(NETSTATS_UID_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001766 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001767 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001768 public Config getUidTagConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001769 return new Config(getGlobalLong(NETSTATS_UID_TAG_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1770 getGlobalLong(NETSTATS_UID_TAG_ROTATE_AGE, 5 * DAY_IN_MILLIS),
1771 getGlobalLong(NETSTATS_UID_TAG_DELETE_AGE, 15 * DAY_IN_MILLIS));
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001772 }
1773 @Override
1774 public long getDevPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001775 return getGlobalLong(NETSTATS_DEV_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001776 }
1777 @Override
1778 public long getXtPersistBytes(long def) {
1779 return getDevPersistBytes(def);
1780 }
1781 @Override
1782 public long getUidPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001783 return getGlobalLong(NETSTATS_UID_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001784 }
1785 @Override
1786 public long getUidTagPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001787 return getGlobalLong(NETSTATS_UID_TAG_PERSIST_BYTES, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001788 }
1789 }
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -08001790
1791 private static int TYPE_RX_BYTES;
1792 private static int TYPE_RX_PACKETS;
1793 private static int TYPE_TX_BYTES;
1794 private static int TYPE_TX_PACKETS;
1795 private static int TYPE_TCP_RX_PACKETS;
1796 private static int TYPE_TCP_TX_PACKETS;
1797
Chenbo Fengaedd6a32017-11-20 18:23:46 -08001798 private static native long nativeGetTotalStat(int type, boolean useBpfStats);
1799 private static native long nativeGetIfaceStat(String iface, int type, boolean useBpfStats);
1800 private static native long nativeGetUidStat(int uid, int type, boolean useBpfStats);
Jeff Sharkey75279902011-05-24 18:39:45 -07001801}