blob: 4e848f8f364c8f7b12a8111be526da2386ac0de7 [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
Jeff Sharkey9911a282018-02-14 22:29:11 -0700289 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey3f391352011-06-05 17:42:53 -0700290 return new File(Environment.getDataDirectory(), "system");
Jeff Sharkey75279902011-05-24 18:39:45 -0700291 }
292
Jeff Sharkey9911a282018-02-14 22:29:11 -0700293 private static @NonNull File getDefaultBaseDir() {
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800294 File baseDir = new File(getDefaultSystemDir(), "netstats");
295 baseDir.mkdirs();
296 return baseDir;
297 }
298
Jeff Sharkey9911a282018-02-14 22:29:11 -0700299 private static @NonNull Clock getDefaultClock() {
300 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
301 Clock.systemUTC());
302 }
303
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800304 public static NetworkStatsService create(Context context,
305 INetworkManagementService networkManager) {
306 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
307 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
308 PowerManager.WakeLock wakeLock =
309 powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
310
311 NetworkStatsService service = new NetworkStatsService(context, networkManager, alarmManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700312 wakeLock, getDefaultClock(), TelephonyManager.getDefault(),
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800313 new DefaultNetworkStatsSettings(context), new NetworkStatsObservers(),
314 getDefaultSystemDir(), getDefaultBaseDir());
315
316 HandlerThread handlerThread = new HandlerThread(TAG);
317 Handler.Callback callback = new HandlerCallback(service);
318 handlerThread.start();
319 Handler handler = new Handler(handlerThread.getLooper(), callback);
320 service.setHandler(handler, callback);
321 return service;
322 }
323
324 @VisibleForTesting
325 NetworkStatsService(Context context, INetworkManagementService networkManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700326 AlarmManager alarmManager, PowerManager.WakeLock wakeLock, Clock clock,
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800327 TelephonyManager teleManager, NetworkStatsSettings settings,
328 NetworkStatsObservers statsObservers, File systemDir, File baseDir) {
Jeff Sharkey75279902011-05-24 18:39:45 -0700329 mContext = checkNotNull(context, "missing Context");
330 mNetworkManager = checkNotNull(networkManager, "missing INetworkManagementService");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800331 mAlarmManager = checkNotNull(alarmManager, "missing AlarmManager");
Jeff Sharkey9911a282018-02-14 22:29:11 -0700332 mClock = checkNotNull(clock, "missing Clock");
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700333 mSettings = checkNotNull(settings, "missing NetworkStatsSettings");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800334 mTeleManager = checkNotNull(teleManager, "missing TelephonyManager");
335 mWakeLock = checkNotNull(wakeLock, "missing WakeLock");
336 mStatsObservers = checkNotNull(statsObservers, "missing NetworkStatsObservers");
337 mSystemDir = checkNotNull(systemDir, "missing systemDir");
338 mBaseDir = checkNotNull(baseDir, "missing baseDir");
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700339
340 LocalServices.addService(NetworkStatsManagerInternal.class,
341 new NetworkStatsManagerInternalImpl());
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800342 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700343
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800344 @VisibleForTesting
345 void setHandler(Handler handler, Handler.Callback callback) {
346 mHandler = handler;
347 mHandlerCallback = callback;
Jeff Sharkey75279902011-05-24 18:39:45 -0700348 }
349
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700350 public void bindConnectivityManager(IConnectivityManager connManager) {
351 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
352 }
353
Jeff Sharkey75279902011-05-24 18:39:45 -0700354 public void systemReady() {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800355 mSystemReady = true;
356
Jeff Sharkey418d12d2011-12-13 15:38:03 -0800357 if (!isBandwidthControlEnabled()) {
358 Slog.w(TAG, "bandwidth controls disabled, unable to track stats");
359 return;
360 }
361
Jeff Sharkey63abc372012-01-11 18:38:16 -0800362 synchronized (mStatsLock) {
Jeff Sharkey4635f102017-09-01 11:27:13 -0600363 // create data recorders along with historical rotators
364 mDevRecorder = buildRecorder(PREFIX_DEV, mSettings.getDevConfig(), false);
365 mXtRecorder = buildRecorder(PREFIX_XT, mSettings.getXtConfig(), false);
366 mUidRecorder = buildRecorder(PREFIX_UID, mSettings.getUidConfig(), false);
367 mUidTagRecorder = buildRecorder(PREFIX_UID_TAG, mSettings.getUidTagConfig(), true);
368
369 updatePersistThresholdsLocked();
370
Jeff Sharkey63abc372012-01-11 18:38:16 -0800371 // upgrade any legacy stats, migrating them to rotated files
372 maybeUpgradeLegacyStatsLocked();
373
374 // read historical network stats from disk, since policy service
375 // might need them right away.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700376 mXtStatsCached = mXtRecorder.getOrLoadCompleteLocked();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800377
378 // bootstrap initial stats to prevent double-counting later
379 bootstrapStatsLocked();
380 }
Jeff Sharkey3359aca2011-11-08 18:08:48 -0800381
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700382 // watch for tethering changes
383 final IntentFilter tetherFilter = new IntentFilter(ACTION_TETHER_STATE_CHANGED);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700384 mContext.registerReceiver(mTetherReceiver, tetherFilter, null, mHandler);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700385
Jeff Sharkey75279902011-05-24 18:39:45 -0700386 // listen for periodic polling events
387 final IntentFilter pollFilter = new IntentFilter(ACTION_NETWORK_STATS_POLL);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700388 mContext.registerReceiver(mPollReceiver, pollFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
Jeff Sharkey75279902011-05-24 18:39:45 -0700389
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700390 // listen for uid removal to clean stats
391 final IntentFilter removedFilter = new IntentFilter(ACTION_UID_REMOVED);
392 mContext.registerReceiver(mRemovedReceiver, removedFilter, null, mHandler);
393
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700394 // listen for user changes to clean stats
395 final IntentFilter userFilter = new IntentFilter(ACTION_USER_REMOVED);
396 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
397
Jeff Sharkey75279902011-05-24 18:39:45 -0700398 // persist stats during clean shutdown
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700399 final IntentFilter shutdownFilter = new IntentFilter(ACTION_SHUTDOWN);
400 mContext.registerReceiver(mShutdownReceiver, shutdownFilter);
Jeff Sharkey75279902011-05-24 18:39:45 -0700401
402 try {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700403 mNetworkManager.registerObserver(mAlertObserver);
Jeff Sharkey75279902011-05-24 18:39:45 -0700404 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700405 // ignored; service lives in system_server
Jeff Sharkey75279902011-05-24 18:39:45 -0700406 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700407
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700408 registerPollAlarmLocked();
409 registerGlobalAlert();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800410 }
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700411
Jeff Sharkey63abc372012-01-11 18:38:16 -0800412 private NetworkStatsRecorder buildRecorder(
413 String prefix, NetworkStatsSettings.Config config, boolean includeTags) {
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700414 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
415 Context.DROPBOX_SERVICE);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700416 return new NetworkStatsRecorder(new FileRotator(
417 mBaseDir, prefix, config.rotateAgeMillis, config.deleteAgeMillis),
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700418 mNonMonotonicObserver, dropBox, prefix, config.bucketDuration, includeTags);
Jeff Sharkey75279902011-05-24 18:39:45 -0700419 }
420
Andreas Gampea36dc622018-02-05 17:19:22 -0800421 @GuardedBy("mStatsLock")
Jeff Sharkey3f391352011-06-05 17:42:53 -0700422 private void shutdownLocked() {
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700423 mContext.unregisterReceiver(mTetherReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700424 mContext.unregisterReceiver(mPollReceiver);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700425 mContext.unregisterReceiver(mRemovedReceiver);
Ryuki Nakamuraa47b0c92017-03-01 10:40:36 +0900426 mContext.unregisterReceiver(mUserReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700427 mContext.unregisterReceiver(mShutdownReceiver);
428
Jeff Sharkey9911a282018-02-14 22:29:11 -0700429 final long currentTime = mClock.millis();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800430
431 // persist any pending stats
432 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700433 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800434 mUidRecorder.forcePersistLocked(currentTime);
435 mUidTagRecorder.forcePersistLocked(currentTime);
436
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800437 mSystemReady = false;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800438 }
439
Andreas Gampea36dc622018-02-05 17:19:22 -0800440 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800441 private void maybeUpgradeLegacyStatsLocked() {
442 File file;
443 try {
444 file = new File(mSystemDir, "netstats.bin");
445 if (file.exists()) {
446 mDevRecorder.importLegacyNetworkLocked(file);
447 file.delete();
448 }
449
450 file = new File(mSystemDir, "netstats_xt.bin");
451 if (file.exists()) {
452 file.delete();
453 }
454
455 file = new File(mSystemDir, "netstats_uid.bin");
456 if (file.exists()) {
457 mUidRecorder.importLegacyUidLocked(file);
458 mUidTagRecorder.importLegacyUidLocked(file);
459 file.delete();
460 }
461 } catch (IOException e) {
462 Log.wtf(TAG, "problem during legacy upgrade", e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700463 } catch (OutOfMemoryError e) {
464 Log.wtf(TAG, "problem during legacy upgrade", e);
Jeff Sharkeyc506ff62011-11-17 11:59:29 -0800465 }
Jeff Sharkey3f391352011-06-05 17:42:53 -0700466 }
467
Jeff Sharkey75279902011-05-24 18:39:45 -0700468 /**
469 * Clear any existing {@link #ACTION_NETWORK_STATS_POLL} alarms, and
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700470 * reschedule based on current {@link NetworkStatsSettings#getPollInterval()}.
Jeff Sharkey75279902011-05-24 18:39:45 -0700471 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700472 private void registerPollAlarmLocked() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473 if (mPollIntent != null) {
474 mAlarmManager.cancel(mPollIntent);
Jeff Sharkey75279902011-05-24 18:39:45 -0700475 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700476
477 mPollIntent = PendingIntent.getBroadcast(
478 mContext, 0, new Intent(ACTION_NETWORK_STATS_POLL), 0);
479
480 final long currentRealtime = SystemClock.elapsedRealtime();
481 mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, currentRealtime,
482 mSettings.getPollInterval(), mPollIntent);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700483 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700484
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700485 /**
486 * Register for a global alert that is delivered through
487 * {@link INetworkManagementEventObserver} once a threshold amount of data
488 * has been transferred.
489 */
490 private void registerGlobalAlert() {
491 try {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700492 mNetworkManager.setGlobalAlert(mGlobalAlertBytes);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700493 } catch (IllegalStateException e) {
494 Slog.w(TAG, "problem registering for global alert: " + e);
495 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700496 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700497 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700498 }
499
500 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700501 public INetworkStatsSession openSession() {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600502 // NOTE: if callers want to get non-augmented data, they should go
503 // through the public API
504 return openSessionInternal(NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN, null);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000505 }
506
507 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600508 public INetworkStatsSession openSessionForUsageStats(int flags, String callingPackage) {
509 return openSessionInternal(flags, callingPackage);
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100510 }
511
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600512 private INetworkStatsSession openSessionInternal(final int flags, final String callingPackage) {
Jeff Sharkey4190a042012-04-21 15:36:48 -0700513 assertBandwidthControlEnabled();
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700514
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600515 if ((flags & NetworkStatsManager.FLAG_POLL_ON_OPEN) != 0) {
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100516 final long ident = Binder.clearCallingIdentity();
517 try {
518 performPoll(FLAG_PERSIST_ALL);
519 } finally {
520 Binder.restoreCallingIdentity(ident);
521 }
522 }
523
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700524 // return an IBinder which holds strong references to any loaded stats
525 // for its lifetime; when caller closes only weak references remain.
526
527 return new INetworkStatsSession.Stub() {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600528 private final int mCallingUid = Binder.getCallingUid();
529 private final String mCallingPackage = callingPackage;
530 private final @NetworkStatsAccess.Level int mAccessLevel = checkAccessLevel(
531 callingPackage);
532
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700533 private NetworkStatsCollection mUidComplete;
534 private NetworkStatsCollection mUidTagComplete;
535
536 private NetworkStatsCollection getUidComplete() {
Ashish Sharmac13b9452013-11-01 14:57:30 -0700537 synchronized (mStatsLock) {
538 if (mUidComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700539 mUidComplete = mUidRecorder.getOrLoadCompleteLocked();
540 }
Ashish Sharmac13b9452013-11-01 14:57:30 -0700541 return mUidComplete;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700542 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700543 }
544
545 private NetworkStatsCollection getUidTagComplete() {
Ashish Sharmac13b9452013-11-01 14:57:30 -0700546 synchronized (mStatsLock) {
547 if (mUidTagComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700548 mUidTagComplete = mUidTagRecorder.getOrLoadCompleteLocked();
549 }
Ashish Sharmac13b9452013-11-01 14:57:30 -0700550 return mUidTagComplete;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700551 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700552 }
553
554 @Override
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000555 public int[] getRelevantUids() {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600556 return getUidComplete().getRelevantUids(mAccessLevel);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000557 }
558
559 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600560 public NetworkStats getDeviceSummaryForNetwork(
561 NetworkTemplate template, long start, long end) {
562 return internalGetSummaryForNetwork(template, flags, start, end, mAccessLevel,
563 mCallingUid);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000564 }
565
566 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700567 public NetworkStats getSummaryForNetwork(
568 NetworkTemplate template, long start, long end) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600569 return internalGetSummaryForNetwork(template, flags, start, end, mAccessLevel,
570 mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700571 }
572
573 @Override
574 public NetworkStatsHistory getHistoryForNetwork(NetworkTemplate template, int fields) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600575 return internalGetHistoryForNetwork(template, flags, fields, mAccessLevel,
576 mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700577 }
578
579 @Override
580 public NetworkStats getSummaryForAllUid(
581 NetworkTemplate template, long start, long end, boolean includeTags) {
Jeff Davidson39583b52016-12-12 11:55:37 -0800582 try {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600583 final NetworkStats stats = getUidComplete()
584 .getSummary(template, start, end, mAccessLevel, mCallingUid);
Jeff Davidson39583b52016-12-12 11:55:37 -0800585 if (includeTags) {
586 final NetworkStats tagStats = getUidTagComplete()
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600587 .getSummary(template, start, end, mAccessLevel, mCallingUid);
Jeff Davidson39583b52016-12-12 11:55:37 -0800588 stats.combineAllValues(tagStats);
589 }
590 return stats;
591 } catch (NullPointerException e) {
592 // TODO: Track down and fix the cause of this crash and remove this catch block.
593 Slog.wtf(TAG, "NullPointerException in getSummaryForAllUid", e);
594 throw e;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700595 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700596 }
597
598 @Override
599 public NetworkStatsHistory getHistoryForUid(
600 NetworkTemplate template, int uid, int set, int tag, int fields) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600601 // NOTE: We don't augment UID-level statistics
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700602 if (tag == TAG_NONE) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600603 return getUidComplete().getHistory(template, null, uid, set, tag, fields,
604 Long.MIN_VALUE, Long.MAX_VALUE, mAccessLevel, mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700605 } else {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600606 return getUidTagComplete().getHistory(template, null, uid, set, tag, fields,
607 Long.MIN_VALUE, Long.MAX_VALUE, mAccessLevel, mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700608 }
609 }
610
611 @Override
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100612 public NetworkStatsHistory getHistoryIntervalForUid(
613 NetworkTemplate template, int uid, int set, int tag, int fields,
614 long start, long end) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600615 // NOTE: We don't augment UID-level statistics
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100616 if (tag == TAG_NONE) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600617 return getUidComplete().getHistory(template, null, uid, set, tag, fields,
618 start, end, mAccessLevel, mCallingUid);
Antonio Cansado6965c182016-03-30 11:37:18 -0700619 } else if (uid == Binder.getCallingUid()) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600620 return getUidTagComplete().getHistory(template, null, uid, set, tag, fields,
621 start, end, mAccessLevel, mCallingUid);
Antonio Cansado6965c182016-03-30 11:37:18 -0700622 } else {
623 throw new SecurityException("Calling package " + mCallingPackage
624 + " cannot access tag information from a different uid");
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100625 }
626 }
627
628 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700629 public void close() {
630 mUidComplete = null;
631 mUidTagComplete = null;
632 }
633 };
Jeff Sharkey905b5892011-09-30 15:19:49 -0700634 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700635
Jeff Davidson1efb1332015-12-09 18:04:50 -0800636 private @NetworkStatsAccess.Level int checkAccessLevel(String callingPackage) {
637 return NetworkStatsAccess.checkAccessLevel(
638 mContext, Binder.getCallingUid(), callingPackage);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000639 }
640
Jeff Sharkey70c70532012-05-16 14:51:19 -0700641 /**
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600642 * Find the most relevant {@link SubscriptionPlan} for the given
643 * {@link NetworkTemplate} and flags. This is typically used to augment
644 * local measurement results to match a known anchor from the carrier.
645 */
646 private SubscriptionPlan resolveSubscriptionPlan(NetworkTemplate template, int flags) {
647 SubscriptionPlan plan = null;
648 if ((flags & NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN) != 0
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700649 && (template.getMatchRule() == NetworkTemplate.MATCH_MOBILE)
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600650 && mSettings.getAugmentEnabled()) {
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700651 if (LOGD) Slog.d(TAG, "Resolving plan for " + template);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600652 final long token = Binder.clearCallingIdentity();
653 try {
654 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
655 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
656 for (int subId : sm.getActiveSubscriptionIdList()) {
657 if (template.matchesSubscriberId(tm.getSubscriberId(subId))) {
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700658 if (LOGD) Slog.d(TAG, "Found active matching subId " + subId);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600659 final List<SubscriptionPlan> plans = sm.getSubscriptionPlans(subId);
660 if (!plans.isEmpty()) {
661 plan = plans.get(0);
662 }
663 }
664 }
665 } finally {
666 Binder.restoreCallingIdentity(token);
667 }
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700668 if (LOGD) Slog.d(TAG, "Resolved to plan " + plan);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600669 }
670 return plan;
671 }
672
673 /**
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700674 * Return network summary, splicing between DEV and XT stats when
675 * appropriate.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700676 */
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600677 private NetworkStats internalGetSummaryForNetwork(NetworkTemplate template, int flags,
678 long start, long end, @NetworkStatsAccess.Level int accessLevel, int callingUid) {
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700679 // We've been using pure XT stats long enough that we no longer need to
680 // splice DEV and XT together.
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600681 final NetworkStatsHistory history = internalGetHistoryForNetwork(template, flags, FIELD_ALL,
682 accessLevel, callingUid);
683
684 final long now = System.currentTimeMillis();
685 final NetworkStatsHistory.Entry entry = history.getValues(start, end, now, null);
686
687 final NetworkStats stats = new NetworkStats(end - start, 1);
Lorenzo Colittiada23ed2018-01-19 01:05:20 +0900688 stats.addValues(new NetworkStats.Entry(IFACE_ALL, UID_ALL, SET_ALL, TAG_NONE,
689 METERED_ALL, ROAMING_ALL, DEFAULT_NETWORK_ALL, entry.rxBytes, entry.rxPackets,
690 entry.txBytes, entry.txPackets, entry.operations));
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600691 return stats;
Jeff Sharkey70c70532012-05-16 14:51:19 -0700692 }
693
694 /**
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700695 * Return network history, splicing between DEV and XT stats when
696 * appropriate.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700697 */
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600698 private NetworkStatsHistory internalGetHistoryForNetwork(NetworkTemplate template,
699 int flags, int fields, @NetworkStatsAccess.Level int accessLevel, int callingUid) {
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700700 // We've been using pure XT stats long enough that we no longer need to
701 // splice DEV and XT together.
Jeff Sharkey4635f102017-09-01 11:27:13 -0600702 final SubscriptionPlan augmentPlan = resolveSubscriptionPlan(template, flags);
703 synchronized (mStatsLock) {
704 return mXtStatsCached.getHistory(template, augmentPlan,
705 UID_ALL, SET_ALL, TAG_NONE, fields, Long.MIN_VALUE, Long.MAX_VALUE,
706 accessLevel, callingUid);
707 }
Jeff Sharkey70c70532012-05-16 14:51:19 -0700708 }
709
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700710 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
711 assertSystemReady();
Jeff Sharkey4190a042012-04-21 15:36:48 -0700712 assertBandwidthControlEnabled();
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600713
714 // NOTE: if callers want to get non-augmented data, they should go
715 // through the public API
716 return internalGetSummaryForNetwork(template,
717 NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN, start, end,
718 NetworkStatsAccess.Level.DEVICE, Binder.getCallingUid()).getTotalBytes();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700719 }
720
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700721 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
722 assertSystemReady();
723 assertBandwidthControlEnabled();
724
725 final NetworkStatsCollection uidComplete;
726 synchronized (mStatsLock) {
727 uidComplete = mUidRecorder.getOrLoadCompleteLocked();
728 }
729 return uidComplete.getSummary(template, start, end, NetworkStatsAccess.Level.DEVICE,
730 android.os.Process.SYSTEM_UID);
731 }
732
Jeff Sharkey350083e2011-06-29 10:45:16 -0700733 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700734 public NetworkStats getDataLayerSnapshotForUid(int uid) throws RemoteException {
735 if (Binder.getCallingUid() != uid) {
736 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
737 }
Jeff Sharkey4190a042012-04-21 15:36:48 -0700738 assertBandwidthControlEnabled();
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700739
740 // TODO: switch to data layer stats once kernel exports
741 // for now, read network layer stats and flatten across all ifaces
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800742 final long token = Binder.clearCallingIdentity();
743 final NetworkStats networkLayer;
744 try {
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +0900745 networkLayer = mNetworkManager.getNetworkStatsUidDetail(uid,
746 NetworkStats.INTERFACES_ALL);
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800747 } finally {
748 Binder.restoreCallingIdentity(token);
749 }
750
Jeff Sharkey21a54782012-04-09 10:27:55 -0700751 // splice in operation counts
752 networkLayer.spliceOperationsFrom(mUidOperations);
753
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700754 final NetworkStats dataLayer = new NetworkStats(
755 networkLayer.getElapsedRealtime(), networkLayer.size());
756
757 NetworkStats.Entry entry = null;
758 for (int i = 0; i < networkLayer.size(); i++) {
759 entry = networkLayer.getValues(i, entry);
760 entry.iface = IFACE_ALL;
761 dataLayer.combineValues(entry);
762 }
763
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700764 return dataLayer;
765 }
766
767 @Override
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +0900768 public NetworkStats getDetailedUidStats(String[] requiredIfaces) {
769 try {
770 final String[] ifacesToQuery =
Remi NGUYEN VAN75525b32018-02-27 16:47:22 +0900771 NetworkStatsFactory.augmentWithStackedInterfaces(requiredIfaces);
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +0900772 return getNetworkStatsUidDetail(ifacesToQuery);
773 } catch (RemoteException e) {
774 Log.wtf(TAG, "Error compiling UID stats", e);
775 return new NetworkStats(0L, 0);
776 }
777 }
778
779 @Override
Jeff Sharkey234766a2012-04-10 19:48:07 -0700780 public String[] getMobileIfaces() {
781 return mMobileIfaces;
782 }
783
784 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700785 public void incrementOperationCount(int uid, int tag, int operationCount) {
786 if (Binder.getCallingUid() != uid) {
Jeff Sharkey9f09e6a72017-06-26 11:24:47 -0600787 mContext.enforceCallingOrSelfPermission(
788 android.Manifest.permission.UPDATE_DEVICE_STATS, TAG);
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700789 }
790
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700791 if (operationCount < 0) {
792 throw new IllegalArgumentException("operation count can only be incremented");
793 }
794 if (tag == TAG_NONE) {
795 throw new IllegalArgumentException("operation count must have specific tag");
796 }
797
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700798 synchronized (mStatsLock) {
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700799 final int set = mActiveUidCounterSet.get(uid, SET_DEFAULT);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800800 mUidOperations.combineValues(
801 mActiveIface, uid, set, tag, 0L, 0L, 0L, 0L, operationCount);
802 mUidOperations.combineValues(
803 mActiveIface, uid, set, TAG_NONE, 0L, 0L, 0L, 0L, operationCount);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700804 }
805 }
806
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700807 @VisibleForTesting
808 void setUidForeground(int uid, boolean uidForeground) {
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700809 synchronized (mStatsLock) {
810 final int set = uidForeground ? SET_FOREGROUND : SET_DEFAULT;
811 final int oldSet = mActiveUidCounterSet.get(uid, SET_DEFAULT);
812 if (oldSet != set) {
813 mActiveUidCounterSet.put(uid, set);
814 setKernelCounterSet(uid, set);
815 }
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700816 }
817 }
818
819 @Override
Lorenzo Colittic78da292018-01-19 00:50:48 +0900820 public void forceUpdateIfaces(Network[] defaultNetworks) {
Jeff Sharkey69736342014-12-08 14:50:12 -0800821 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
822 assertBandwidthControlEnabled();
823
824 final long token = Binder.clearCallingIdentity();
825 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +0900826 updateIfaces(defaultNetworks);
Jeff Sharkey69736342014-12-08 14:50:12 -0800827 } finally {
828 Binder.restoreCallingIdentity(token);
829 }
830 }
831
832 @Override
Jeff Sharkey350083e2011-06-29 10:45:16 -0700833 public void forceUpdate() {
834 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700835 assertBandwidthControlEnabled();
Jeff Sharkeye630f7b2012-01-31 17:12:53 -0800836
837 final long token = Binder.clearCallingIdentity();
838 try {
839 performPoll(FLAG_PERSIST_ALL);
840 } finally {
841 Binder.restoreCallingIdentity(token);
842 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700843 }
844
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700845 private void advisePersistThreshold(long thresholdBytes) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700846 assertBandwidthControlEnabled();
847
848 // clamp threshold into safe range
849 mPersistThreshold = MathUtils.constrain(thresholdBytes, 128 * KB_IN_BYTES, 2 * MB_IN_BYTES);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700850 if (LOGV) {
851 Slog.v(TAG, "advisePersistThreshold() given " + thresholdBytes + ", clamped to "
852 + mPersistThreshold);
853 }
854
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700855 // update and persist if beyond new thresholds
Jeff Sharkey9911a282018-02-14 22:29:11 -0700856 final long currentTime = mClock.millis();
Jeff Sharkey58015972012-05-07 11:08:49 -0700857 synchronized (mStatsLock) {
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700858 if (!mSystemReady) return;
859
Jeff Sharkey4635f102017-09-01 11:27:13 -0600860 updatePersistThresholdsLocked();
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700861
Jeff Sharkey58015972012-05-07 11:08:49 -0700862 mDevRecorder.maybePersistLocked(currentTime);
863 mXtRecorder.maybePersistLocked(currentTime);
864 mUidRecorder.maybePersistLocked(currentTime);
865 mUidTagRecorder.maybePersistLocked(currentTime);
866 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700867
868 // re-arm global alert
869 registerGlobalAlert();
870 }
871
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800872 @Override
Antonio Cansado6965c182016-03-30 11:37:18 -0700873 public DataUsageRequest registerUsageCallback(String callingPackage,
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800874 DataUsageRequest request, Messenger messenger, IBinder binder) {
875 checkNotNull(callingPackage, "calling package is null");
876 checkNotNull(request, "DataUsageRequest is null");
Antonio Cansado6965c182016-03-30 11:37:18 -0700877 checkNotNull(request.template, "NetworkTemplate is null");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800878 checkNotNull(messenger, "messenger is null");
879 checkNotNull(binder, "binder is null");
880
881 int callingUid = Binder.getCallingUid();
882 @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(callingPackage);
883 DataUsageRequest normalizedRequest;
884 final long token = Binder.clearCallingIdentity();
885 try {
886 normalizedRequest = mStatsObservers.register(request, messenger, binder,
887 callingUid, accessLevel);
888 } finally {
889 Binder.restoreCallingIdentity(token);
890 }
891
892 // Create baseline stats
893 mHandler.sendMessage(mHandler.obtainMessage(MSG_PERFORM_POLL, FLAG_PERSIST_ALL));
894
895 return normalizedRequest;
896 }
897
898 @Override
Antonio Cansado6965c182016-03-30 11:37:18 -0700899 public void unregisterUsageRequest(DataUsageRequest request) {
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800900 checkNotNull(request, "DataUsageRequest is null");
901
902 int callingUid = Binder.getCallingUid();
903 final long token = Binder.clearCallingIdentity();
904 try {
905 mStatsObservers.unregister(request, callingUid);
906 } finally {
907 Binder.restoreCallingIdentity(token);
908 }
909 }
910
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800911 @Override
912 public long getUidStats(int uid, int type) {
Chenbo Fengaedd6a32017-11-20 18:23:46 -0800913 return nativeGetUidStat(uid, type, checkBpfStatsEnable());
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800914 }
915
916 @Override
917 public long getIfaceStats(String iface, int type) {
Chenbo Fengaedd6a32017-11-20 18:23:46 -0800918 return nativeGetIfaceStat(iface, type, checkBpfStatsEnable());
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800919 }
920
921 @Override
922 public long getTotalStats(int type) {
Chenbo Fengaedd6a32017-11-20 18:23:46 -0800923 return nativeGetTotalStat(type, checkBpfStatsEnable());
924 }
925
926 private boolean checkBpfStatsEnable() {
927 return new File("/sys/fs/bpf/traffic_uid_stats_map").exists();
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800928 }
929
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700930 /**
931 * Update {@link NetworkStatsRecorder} and {@link #mGlobalAlertBytes} to
932 * reflect current {@link #mPersistThreshold} value. Always defers to
Jeff Sharkey625239a2012-09-26 22:03:49 -0700933 * {@link Global} values when defined.
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700934 */
Andreas Gampea36dc622018-02-05 17:19:22 -0800935 @GuardedBy("mStatsLock")
Jeff Sharkey4635f102017-09-01 11:27:13 -0600936 private void updatePersistThresholdsLocked() {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700937 mDevRecorder.setPersistThreshold(mSettings.getDevPersistBytes(mPersistThreshold));
938 mXtRecorder.setPersistThreshold(mSettings.getXtPersistBytes(mPersistThreshold));
939 mUidRecorder.setPersistThreshold(mSettings.getUidPersistBytes(mPersistThreshold));
940 mUidTagRecorder.setPersistThreshold(mSettings.getUidTagPersistBytes(mPersistThreshold));
941 mGlobalAlertBytes = mSettings.getGlobalAlertBytes(mPersistThreshold);
942 }
943
Jeff Sharkey75279902011-05-24 18:39:45 -0700944 /**
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700945 * Receiver that watches for {@link Tethering} to claim interface pairs.
946 */
947 private BroadcastReceiver mTetherReceiver = new BroadcastReceiver() {
948 @Override
949 public void onReceive(Context context, Intent intent) {
950 // on background handler thread, and verified CONNECTIVITY_INTERNAL
951 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700952 performPoll(FLAG_PERSIST_NETWORK);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700953 }
954 };
955
Jeff Sharkey75279902011-05-24 18:39:45 -0700956 private BroadcastReceiver mPollReceiver = new BroadcastReceiver() {
957 @Override
958 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700959 // on background handler thread, and verified UPDATE_DEVICE_STATS
960 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700961 performPoll(FLAG_PERSIST_ALL);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700962
963 // verify that we're watching global alert
964 registerGlobalAlert();
Jeff Sharkey75279902011-05-24 18:39:45 -0700965 }
966 };
967
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700968 private BroadcastReceiver mRemovedReceiver = new BroadcastReceiver() {
969 @Override
970 public void onReceive(Context context, Intent intent) {
971 // on background handler thread, and UID_REMOVED is protected
972 // broadcast.
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700973
974 final int uid = intent.getIntExtra(EXTRA_UID, -1);
975 if (uid == -1) return;
976
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700977 synchronized (mStatsLock) {
Jeff Sharkey62489262011-07-17 12:53:28 -0700978 mWakeLock.acquire();
979 try {
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700980 removeUidsLocked(uid);
981 } finally {
982 mWakeLock.release();
983 }
984 }
985 }
986 };
987
988 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
989 @Override
990 public void onReceive(Context context, Intent intent) {
991 // On background handler thread, and USER_REMOVED is protected
992 // broadcast.
993
994 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
995 if (userId == -1) return;
996
997 synchronized (mStatsLock) {
998 mWakeLock.acquire();
999 try {
1000 removeUserLocked(userId);
Jeff Sharkey62489262011-07-17 12:53:28 -07001001 } finally {
1002 mWakeLock.release();
1003 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001004 }
1005 }
1006 };
1007
Jeff Sharkey75279902011-05-24 18:39:45 -07001008 private BroadcastReceiver mShutdownReceiver = new BroadcastReceiver() {
1009 @Override
1010 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001011 // SHUTDOWN is protected broadcast.
Jeff Sharkey75279902011-05-24 18:39:45 -07001012 synchronized (mStatsLock) {
Jeff Sharkey3f391352011-06-05 17:42:53 -07001013 shutdownLocked();
Jeff Sharkey75279902011-05-24 18:39:45 -07001014 }
1015 }
1016 };
1017
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001018 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001019 * Observer that watches for {@link INetworkManagementService} alerts.
1020 */
Jeff Sharkey216c1812012-08-05 14:29:23 -07001021 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001022 @Override
1023 public void limitReached(String limitName, String iface) {
1024 // only someone like NMS should be calling us
1025 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1026
1027 if (LIMIT_GLOBAL_ALERT.equals(limitName)) {
1028 // kick off background poll to collect network stats; UID stats
1029 // are handled during normal polling interval.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001030 final int flags = FLAG_PERSIST_NETWORK;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001031 mHandler.obtainMessage(MSG_PERFORM_POLL, flags, 0).sendToTarget();
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001032
1033 // re-arm global alert for next update
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001034 mHandler.obtainMessage(MSG_REGISTER_GLOBAL_ALERT).sendToTarget();
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001035 }
1036 }
1037 };
1038
Lorenzo Colittic78da292018-01-19 00:50:48 +09001039 private void updateIfaces(Network[] defaultNetworks) {
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001040 synchronized (mStatsLock) {
1041 mWakeLock.acquire();
1042 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09001043 updateIfacesLocked(defaultNetworks);
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001044 } finally {
1045 mWakeLock.release();
1046 }
1047 }
1048 }
1049
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001050 /**
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001051 * Inspect all current {@link NetworkState} to derive mapping from {@code
1052 * iface} to {@link NetworkStatsHistory}. When multiple {@link NetworkInfo}
1053 * are active on a single {@code iface}, they are combined under a single
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001054 * {@link NetworkIdentitySet}.
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001055 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001056 @GuardedBy("mStatsLock")
Lorenzo Colittic78da292018-01-19 00:50:48 +09001057 private void updateIfacesLocked(Network[] defaultNetworks) {
Jeff Sharkey6341fce2012-03-06 19:59:57 -08001058 if (!mSystemReady) return;
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001059 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001060
1061 // take one last stats snapshot before updating iface mapping. this
1062 // isn't perfect, since the kernel may already be counting traffic from
1063 // the updated network.
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001064
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001065 // poll, but only persist network stats to keep codepath fast. UID stats
1066 // will be persisted during next alarm poll event.
1067 performPollLocked(FLAG_PERSIST_NETWORK);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001068
1069 final NetworkState[] states;
Jeff Sharkey63abc372012-01-11 18:38:16 -08001070 final LinkProperties activeLink;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001071 try {
1072 states = mConnManager.getAllNetworkState();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001073 activeLink = mConnManager.getActiveLinkProperties();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001074 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001075 // ignored; service lives in system_server
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001076 return;
1077 }
1078
Jeff Sharkey63abc372012-01-11 18:38:16 -08001079 mActiveIface = activeLink != null ? activeLink.getInterfaceName() : null;
1080
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001081 // Rebuild active interfaces based on connected networks
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001082 mActiveIfaces.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001083 mActiveUidIfaces.clear();
Lorenzo Colittic78da292018-01-19 00:50:48 +09001084 if (defaultNetworks != null) {
1085 // Caller is ConnectivityService. Update the list of default networks.
1086 mDefaultNetworks = defaultNetworks;
1087 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001088
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001089 final ArraySet<String> mobileIfaces = new ArraySet<>();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001090 for (NetworkState state : states) {
1091 if (state.networkInfo.isConnected()) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001092 final boolean isMobile = isNetworkTypeMobile(state.networkInfo.getType());
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001093 final boolean isDefault = ArrayUtils.contains(mDefaultNetworks, state.network);
1094 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1095 isDefault);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001096
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001097 // Traffic occurring on the base interface is always counted for
1098 // both total usage and UID details.
1099 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001100 if (baseIface != null) {
1101 findOrCreateNetworkIdentitySet(mActiveIfaces, baseIface).add(ident);
1102 findOrCreateNetworkIdentitySet(mActiveUidIfaces, baseIface).add(ident);
Jack Yub6587ea2016-06-22 11:35:10 -07001103
1104 // Build a separate virtual interface for VT (Video Telephony) data usage.
1105 // Only do this when IMS is not metered, but VT is metered.
1106 // If IMS is metered, then the IMS network usage has already included VT usage.
1107 // VT is considered always metered in framework's layer. If VT is not metered
1108 // per carrier's policy, modem will report 0 usage for VT calls.
1109 if (state.networkCapabilities.hasCapability(
1110 NetworkCapabilities.NET_CAPABILITY_IMS) && !ident.getMetered()) {
1111
1112 // Copy the identify from IMS one but mark it as metered.
1113 NetworkIdentity vtIdent = new NetworkIdentity(ident.getType(),
1114 ident.getSubType(), ident.getSubscriberId(), ident.getNetworkId(),
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001115 ident.getRoaming(), true /* metered */,
1116 true /* onDefaultNetwork */);
Jack Yub6587ea2016-06-22 11:35:10 -07001117 findOrCreateNetworkIdentitySet(mActiveIfaces, VT_INTERFACE).add(vtIdent);
1118 findOrCreateNetworkIdentitySet(mActiveUidIfaces, VT_INTERFACE).add(vtIdent);
1119 }
1120
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001121 if (isMobile) {
1122 mobileIfaces.add(baseIface);
1123 }
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001124 }
1125
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001126 // Traffic occurring on stacked interfaces is usually clatd,
1127 // which is already accounted against its final egress interface
1128 // by the kernel. Thus, we only need to collect stacked
1129 // interface stats at the UID level.
1130 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1131 for (LinkProperties stackedLink : stackedLinks) {
1132 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001133 if (stackedIface != null) {
1134 findOrCreateNetworkIdentitySet(mActiveUidIfaces, stackedIface).add(ident);
1135 if (isMobile) {
1136 mobileIfaces.add(stackedIface);
1137 }
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001138
1139 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
Jeff Sharkey234766a2012-04-10 19:48:07 -07001140 }
1141 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001142 }
1143 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001144
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001145 mMobileIfaces = mobileIfaces.toArray(new String[mobileIfaces.size()]);
1146 }
1147
1148 private static <K> NetworkIdentitySet findOrCreateNetworkIdentitySet(
1149 ArrayMap<K, NetworkIdentitySet> map, K key) {
1150 NetworkIdentitySet ident = map.get(key);
1151 if (ident == null) {
1152 ident = new NetworkIdentitySet();
1153 map.put(key, ident);
1154 }
1155 return ident;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001156 }
1157
Andreas Gampea36dc622018-02-05 17:19:22 -08001158 @GuardedBy("mStatsLock")
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001159 private void recordSnapshotLocked(long currentTime) throws RemoteException {
1160 // snapshot and record current counters; read UID stats first to
Jack Yub6587ea2016-06-22 11:35:10 -07001161 // avoid over counting dev stats.
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001162 final NetworkStats uidSnapshot = getNetworkStatsUidDetail(INTERFACES_ALL);
Jack Yuf9d559c2017-05-26 16:08:22 -07001163 final NetworkStats xtSnapshot = getNetworkStatsXt();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001164 final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
1165
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001166 // Tethering snapshot for dev and xt stats. Counts per-interface data from tethering stats
1167 // providers that isn't already counted by dev and XT stats.
1168 final NetworkStats tetherSnapshot = getNetworkStatsTethering(STATS_PER_IFACE);
1169 xtSnapshot.combineAllValues(tetherSnapshot);
1170 devSnapshot.combineAllValues(tetherSnapshot);
Jeff Davidson4ff3bcf2016-06-15 13:31:52 -07001171
1172 // For xt/dev, we pass a null VPN array because usage is aggregated by UID, so VPN traffic
1173 // can't be reattributed to responsible apps.
1174 mDevRecorder.recordSnapshotLocked(
1175 devSnapshot, mActiveIfaces, null /* vpnArray */, currentTime);
1176 mXtRecorder.recordSnapshotLocked(
1177 xtSnapshot, mActiveIfaces, null /* vpnArray */, currentTime);
1178
1179 // For per-UID stats, pass the VPN info so VPN traffic is reattributed to responsible apps.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001180 VpnInfo[] vpnArray = mConnManager.getAllVpnInfo();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001181 mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
1182 mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001183
1184 // We need to make copies of member fields that are sent to the observer to avoid
1185 // a race condition between the service handler thread and the observer's
1186 mStatsObservers.updateStats(xtSnapshot, uidSnapshot, new ArrayMap<>(mActiveIfaces),
1187 new ArrayMap<>(mActiveUidIfaces), vpnArray, currentTime);
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001188 }
1189
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001190 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001191 * Bootstrap initial stats snapshot, usually during {@link #systemReady()}
1192 * so we have baseline values without double-counting.
1193 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001194 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -08001195 private void bootstrapStatsLocked() {
Jeff Sharkey9911a282018-02-14 22:29:11 -07001196 final long currentTime = mClock.millis();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001197
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001198 try {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001199 recordSnapshotLocked(currentTime);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001200 } catch (IllegalStateException e) {
1201 Slog.w(TAG, "problem reading network stats: " + e);
1202 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001203 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001204 }
1205 }
1206
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001207 private void performPoll(int flags) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001208 synchronized (mStatsLock) {
1209 mWakeLock.acquire();
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001210
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001211 try {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001212 performPollLocked(flags);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001213 } finally {
1214 mWakeLock.release();
1215 }
1216 }
1217 }
1218
1219 /**
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001220 * Periodic poll operation, reading current statistics and recording into
1221 * {@link NetworkStatsHistory}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001222 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001223 @GuardedBy("mStatsLock")
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001224 private void performPollLocked(int flags) {
Jeff Sharkey6341fce2012-03-06 19:59:57 -08001225 if (!mSystemReady) return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001226 if (LOGV) Slog.v(TAG, "performPollLocked(flags=0x" + Integer.toHexString(flags) + ")");
Jeff Sharkey6341fce2012-03-06 19:59:57 -08001227
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001228 final long startRealtime = SystemClock.elapsedRealtime();
Jeff Sharkey75279902011-05-24 18:39:45 -07001229
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001230 final boolean persistNetwork = (flags & FLAG_PERSIST_NETWORK) != 0;
1231 final boolean persistUid = (flags & FLAG_PERSIST_UID) != 0;
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001232 final boolean persistForce = (flags & FLAG_PERSIST_FORCE) != 0;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001233
Jeff Sharkey75279902011-05-24 18:39:45 -07001234 // TODO: consider marking "untrusted" times in historical stats
Jeff Sharkey9911a282018-02-14 22:29:11 -07001235 final long currentTime = mClock.millis();
Jeff Sharkey75279902011-05-24 18:39:45 -07001236
Jeff Sharkey75279902011-05-24 18:39:45 -07001237 try {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001238 recordSnapshotLocked(currentTime);
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001239 } catch (IllegalStateException e) {
1240 Log.wtf(TAG, "problem reading network stats", e);
Jeff Sharkey905b5892011-09-30 15:19:49 -07001241 return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001242 } catch (RemoteException e) {
1243 // ignored; service lives in system_server
Jeff Sharkey905b5892011-09-30 15:19:49 -07001244 return;
1245 }
1246
Jeff Sharkey63abc372012-01-11 18:38:16 -08001247 // persist any pending data depending on requested flags
1248 if (persistForce) {
1249 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001250 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001251 mUidRecorder.forcePersistLocked(currentTime);
1252 mUidTagRecorder.forcePersistLocked(currentTime);
1253 } else {
1254 if (persistNetwork) {
1255 mDevRecorder.maybePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001256 mXtRecorder.maybePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001257 }
1258 if (persistUid) {
1259 mUidRecorder.maybePersistLocked(currentTime);
1260 mUidTagRecorder.maybePersistLocked(currentTime);
1261 }
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001262 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001263
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001264 if (LOGV) {
1265 final long duration = SystemClock.elapsedRealtime() - startRealtime;
1266 Slog.v(TAG, "performPollLocked() took " + duration + "ms");
1267 }
1268
Jeff Sharkey63abc372012-01-11 18:38:16 -08001269 if (mSettings.getSampleEnabled()) {
Jeff Sharkey905b5892011-09-30 15:19:49 -07001270 // sample stats after each full poll
Jeff Sharkey63abc372012-01-11 18:38:16 -08001271 performSampleLocked();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001272 }
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001273
Jeff Sharkey497e4432011-06-14 17:27:29 -07001274 // finally, dispatch updated event to any listeners
1275 final Intent updatedIntent = new Intent(ACTION_NETWORK_STATS_UPDATED);
1276 updatedIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001277 mContext.sendBroadcastAsUser(updatedIntent, UserHandle.ALL,
1278 READ_NETWORK_USAGE_HISTORY);
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001279 }
1280
1281 /**
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001282 * Sample recent statistics summary into {@link EventLog}.
1283 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001284 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -08001285 private void performSampleLocked() {
1286 // TODO: migrate trustedtime fixes to separate binary log events
Jeff Sharkey9911a282018-02-14 22:29:11 -07001287 final long currentTime = mClock.millis();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001288
Jeff Sharkey63abc372012-01-11 18:38:16 -08001289 NetworkTemplate template;
1290 NetworkStats.Entry devTotal;
1291 NetworkStats.Entry xtTotal;
1292 NetworkStats.Entry uidTotal;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001293
1294 // collect mobile sample
Jeff Sharkey234766a2012-04-10 19:48:07 -07001295 template = buildTemplateMobileWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001296 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001297 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001298 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001299
Jeff Sharkey905b5892011-09-30 15:19:49 -07001300 EventLogTags.writeNetstatsMobileSample(
1301 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1302 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1303 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey9911a282018-02-14 22:29:11 -07001304 currentTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001305
1306 // collect wifi sample
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001307 template = buildTemplateWifiWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001308 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001309 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001310 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
1311
Jeff Sharkey905b5892011-09-30 15:19:49 -07001312 EventLogTags.writeNetstatsWifiSample(
1313 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1314 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1315 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey9911a282018-02-14 22:29:11 -07001316 currentTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001317 }
1318
1319 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001320 * Clean up {@link #mUidRecorder} after UID is removed.
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001321 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001322 @GuardedBy("mStatsLock")
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001323 private void removeUidsLocked(int... uids) {
1324 if (LOGV) Slog.v(TAG, "removeUidsLocked() for UIDs " + Arrays.toString(uids));
1325
1326 // Perform one last poll before removing
Jeff Sharkey163e6442011-10-31 16:37:52 -07001327 performPollLocked(FLAG_PERSIST_ALL);
1328
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001329 mUidRecorder.removeUidsLocked(uids);
1330 mUidTagRecorder.removeUidsLocked(uids);
Jeff Sharkey163e6442011-10-31 16:37:52 -07001331
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001332 // Clear kernel stats associated with UID
1333 for (int uid : uids) {
1334 resetKernelUidStats(uid);
1335 }
1336 }
1337
1338 /**
1339 * Clean up {@link #mUidRecorder} after user is removed.
1340 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001341 @GuardedBy("mStatsLock")
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001342 private void removeUserLocked(int userId) {
1343 if (LOGV) Slog.v(TAG, "removeUserLocked() for userId=" + userId);
1344
1345 // Build list of UIDs that we should clean up
1346 int[] uids = new int[0];
1347 final List<ApplicationInfo> apps = mContext.getPackageManager().getInstalledApplications(
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001348 PackageManager.MATCH_ANY_USER
1349 | PackageManager.MATCH_DISABLED_COMPONENTS);
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001350 for (ApplicationInfo app : apps) {
1351 final int uid = UserHandle.getUid(userId, app.uid);
1352 uids = ArrayUtils.appendInt(uids, uid);
1353 }
1354
1355 removeUidsLocked(uids);
Jeff Sharkey75279902011-05-24 18:39:45 -07001356 }
1357
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001358 private class NetworkStatsManagerInternalImpl extends NetworkStatsManagerInternal {
1359 @Override
1360 public long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
1361 return NetworkStatsService.this.getNetworkTotalBytes(template, start, end);
1362 }
1363
1364 @Override
1365 public NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
1366 return NetworkStatsService.this.getNetworkUidBytes(template, start, end);
1367 }
1368
1369 @Override
1370 public void setUidForeground(int uid, boolean uidForeground) {
1371 NetworkStatsService.this.setUidForeground(uid, uidForeground);
1372 }
1373
1374 @Override
1375 public void advisePersistThreshold(long thresholdBytes) {
1376 NetworkStatsService.this.advisePersistThreshold(thresholdBytes);
1377 }
1378
1379 @Override
1380 public void forceUpdate() {
1381 NetworkStatsService.this.forceUpdate();
1382 }
1383 }
1384
Jeff Sharkey75279902011-05-24 18:39:45 -07001385 @Override
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001386 protected void dump(FileDescriptor fd, PrintWriter rawWriter, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001387 if (!DumpUtils.checkDumpPermission(mContext, TAG, rawWriter)) return;
Jeff Sharkey75279902011-05-24 18:39:45 -07001388
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001389 long duration = DateUtils.DAY_IN_MILLIS;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001390 final HashSet<String> argSet = new HashSet<String>();
1391 for (String arg : args) {
1392 argSet.add(arg);
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001393
1394 if (arg.startsWith("--duration=")) {
1395 try {
1396 duration = Long.parseLong(arg.substring(11));
1397 } catch (NumberFormatException ignored) {
1398 }
1399 }
Jeff Sharkey75279902011-05-24 18:39:45 -07001400 }
1401
Jeff Sharkey706498d2012-02-06 17:35:07 -08001402 // usage: dumpsys netstats --full --uid --tag --poll --checkin
Jeff Sharkey63abc372012-01-11 18:38:16 -08001403 final boolean poll = argSet.contains("--poll") || argSet.contains("poll");
Jeff Sharkey706498d2012-02-06 17:35:07 -08001404 final boolean checkin = argSet.contains("--checkin");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001405 final boolean fullHistory = argSet.contains("--full") || argSet.contains("full");
1406 final boolean includeUid = argSet.contains("--uid") || argSet.contains("detail");
1407 final boolean includeTag = argSet.contains("--tag") || argSet.contains("detail");
1408
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001409 final IndentingPrintWriter pw = new IndentingPrintWriter(rawWriter, " ");
Jeff Sharkey350083e2011-06-29 10:45:16 -07001410
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001411 synchronized (mStatsLock) {
Makoto Onukida65a522017-01-13 10:23:30 -08001412 if (args.length > 0 && "--proto".equals(args[0])) {
1413 // In this case ignore all other arguments.
Jeff Sharkey4635f102017-09-01 11:27:13 -06001414 dumpProtoLocked(fd);
Makoto Onukida65a522017-01-13 10:23:30 -08001415 return;
1416 }
1417
Jeff Sharkey63abc372012-01-11 18:38:16 -08001418 if (poll) {
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001419 performPollLocked(FLAG_PERSIST_ALL | FLAG_PERSIST_FORCE);
Jeff Sharkey3f391352011-06-05 17:42:53 -07001420 pw.println("Forced poll");
1421 return;
1422 }
1423
Jeff Sharkey706498d2012-02-06 17:35:07 -08001424 if (checkin) {
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001425 final long end = System.currentTimeMillis();
1426 final long start = end - duration;
1427
1428 pw.print("v1,");
1429 pw.print(start / SECOND_IN_MILLIS); pw.print(',');
1430 pw.print(end / SECOND_IN_MILLIS); pw.println();
1431
1432 pw.println("xt");
1433 mXtRecorder.dumpCheckin(rawWriter, start, end);
1434
1435 if (includeUid) {
1436 pw.println("uid");
1437 mUidRecorder.dumpCheckin(rawWriter, start, end);
Jeff Sharkey706498d2012-02-06 17:35:07 -08001438 }
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001439 if (includeTag) {
1440 pw.println("tag");
1441 mUidTagRecorder.dumpCheckin(rawWriter, start, end);
1442 }
Jeff Sharkey706498d2012-02-06 17:35:07 -08001443 return;
1444 }
1445
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001446 pw.println("Active interfaces:");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001447 pw.increaseIndent();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001448 for (int i = 0; i < mActiveIfaces.size(); i++) {
1449 pw.printPair("iface", mActiveIfaces.keyAt(i));
1450 pw.printPair("ident", mActiveIfaces.valueAt(i));
1451 pw.println();
1452 }
1453 pw.decreaseIndent();
1454
1455 pw.println("Active UID interfaces:");
1456 pw.increaseIndent();
1457 for (int i = 0; i < mActiveUidIfaces.size(); i++) {
1458 pw.printPair("iface", mActiveUidIfaces.keyAt(i));
1459 pw.printPair("ident", mActiveUidIfaces.valueAt(i));
1460 pw.println();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001461 }
Jeff Sharkey63abc372012-01-11 18:38:16 -08001462 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001463
Jeff Sharkey63abc372012-01-11 18:38:16 -08001464 pw.println("Dev stats:");
1465 pw.increaseIndent();
1466 mDevRecorder.dumpLocked(pw, fullHistory);
1467 pw.decreaseIndent();
1468
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001469 pw.println("Xt stats:");
1470 pw.increaseIndent();
1471 mXtRecorder.dumpLocked(pw, fullHistory);
1472 pw.decreaseIndent();
1473
Jeff Sharkey63abc372012-01-11 18:38:16 -08001474 if (includeUid) {
1475 pw.println("UID stats:");
1476 pw.increaseIndent();
1477 mUidRecorder.dumpLocked(pw, fullHistory);
1478 pw.decreaseIndent();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001479 }
1480
Jeff Sharkey63abc372012-01-11 18:38:16 -08001481 if (includeTag) {
1482 pw.println("UID tag stats:");
1483 pw.increaseIndent();
1484 mUidTagRecorder.dumpLocked(pw, fullHistory);
1485 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001486 }
1487 }
1488 }
1489
Andreas Gampea36dc622018-02-05 17:19:22 -08001490 @GuardedBy("mStatsLock")
Jeff Sharkey4635f102017-09-01 11:27:13 -06001491 private void dumpProtoLocked(FileDescriptor fd) {
Makoto Onukida65a522017-01-13 10:23:30 -08001492 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1493
1494 // TODO Right now it writes all history. Should it limit to the "since-boot" log?
1495
1496 dumpInterfaces(proto, NetworkStatsServiceDumpProto.ACTIVE_INTERFACES, mActiveIfaces);
1497 dumpInterfaces(proto, NetworkStatsServiceDumpProto.ACTIVE_UID_INTERFACES, mActiveUidIfaces);
1498 mDevRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.DEV_STATS);
1499 mXtRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.XT_STATS);
1500 mUidRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.UID_STATS);
1501 mUidTagRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.UID_TAG_STATS);
1502
1503 proto.flush();
1504 }
1505
1506 private static void dumpInterfaces(ProtoOutputStream proto, long tag,
1507 ArrayMap<String, NetworkIdentitySet> ifaces) {
1508 for (int i = 0; i < ifaces.size(); i++) {
1509 final long start = proto.start(tag);
1510
1511 proto.write(NetworkInterfaceProto.INTERFACE, ifaces.keyAt(i));
1512 ifaces.valueAt(i).writeToProto(proto, NetworkInterfaceProto.IDENTITIES);
1513
1514 proto.end(start);
1515 }
1516 }
1517
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001518 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001519 * Return snapshot of current UID statistics, including any
Jack Yuf9d559c2017-05-26 16:08:22 -07001520 * {@link TrafficStats#UID_TETHERING}, video calling data usage, and {@link #mUidOperations}
1521 * values.
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001522 *
1523 * @param ifaces A list of interfaces the stats should be restricted to, or
1524 * {@link NetworkStats#INTERFACES_ALL}.
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001525 */
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001526 private NetworkStats getNetworkStatsUidDetail(String[] ifaces)
1527 throws RemoteException {
1528
Remi NGUYEN VAN75525b32018-02-27 16:47:22 +09001529 // TODO: remove 464xlat adjustments from NetworkStatsFactory and apply all at once here.
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001530 final NetworkStats uidSnapshot = mNetworkManager.getNetworkStatsUidDetail(UID_ALL,
1531 ifaces);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001532
Jeff Sharkey63abc372012-01-11 18:38:16 -08001533 // fold tethering stats and operations into uid snapshot
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001534 final NetworkStats tetherSnapshot = getNetworkStatsTethering(STATS_PER_UID);
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001535 tetherSnapshot.filter(UID_ALL, ifaces, TAG_ALL);
Remi NGUYEN VAN75525b32018-02-27 16:47:22 +09001536 NetworkStatsFactory.apply464xlatAdjustments(uidSnapshot, tetherSnapshot);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001537 uidSnapshot.combineAllValues(tetherSnapshot);
Jack Yuf9d559c2017-05-26 16:08:22 -07001538
1539 final TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(
1540 Context.TELEPHONY_SERVICE);
1541
1542 // fold video calling data usage stats into uid snapshot
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001543 final NetworkStats vtStats = telephonyManager.getVtDataUsage(STATS_PER_UID);
Jack Yuf9d559c2017-05-26 16:08:22 -07001544 if (vtStats != null) {
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001545 vtStats.filter(UID_ALL, ifaces, TAG_ALL);
Remi NGUYEN VAN75525b32018-02-27 16:47:22 +09001546 NetworkStatsFactory.apply464xlatAdjustments(uidSnapshot, vtStats);
Jack Yuf9d559c2017-05-26 16:08:22 -07001547 uidSnapshot.combineAllValues(vtStats);
1548 }
Remi NGUYEN VANb6a92012018-03-06 12:36:54 +09001549
Jeff Sharkey63abc372012-01-11 18:38:16 -08001550 uidSnapshot.combineAllValues(mUidOperations);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001551
Jeff Sharkey63abc372012-01-11 18:38:16 -08001552 return uidSnapshot;
Jeff Sharkey75279902011-05-24 18:39:45 -07001553 }
1554
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001555 /**
Jack Yuf9d559c2017-05-26 16:08:22 -07001556 * Return snapshot of current XT statistics with video calling data usage statistics.
Jack Yub6587ea2016-06-22 11:35:10 -07001557 */
Jack Yuf9d559c2017-05-26 16:08:22 -07001558 private NetworkStats getNetworkStatsXt() throws RemoteException {
Jack Yub6587ea2016-06-22 11:35:10 -07001559 final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
1560
Jack Yuf9d559c2017-05-26 16:08:22 -07001561 final TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(
Jack Yub6587ea2016-06-22 11:35:10 -07001562 Context.TELEPHONY_SERVICE);
1563
Jack Yuf9d559c2017-05-26 16:08:22 -07001564 // Merge video calling data usage into XT
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001565 final NetworkStats vtSnapshot = telephonyManager.getVtDataUsage(STATS_PER_IFACE);
Jack Yuf9d559c2017-05-26 16:08:22 -07001566 if (vtSnapshot != null) {
1567 xtSnapshot.combineAllValues(vtSnapshot);
1568 }
Jack Yub6587ea2016-06-22 11:35:10 -07001569
1570 return xtSnapshot;
1571 }
1572
1573 /**
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001574 * Return snapshot of current tethering statistics. Will return empty
1575 * {@link NetworkStats} if any problems are encountered.
1576 */
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001577 private NetworkStats getNetworkStatsTethering(int how) throws RemoteException {
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001578 try {
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001579 return mNetworkManager.getNetworkStatsTethering(how);
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001580 } catch (IllegalStateException e) {
1581 Log.wtf(TAG, "problem reading network stats", e);
1582 return new NetworkStats(0L, 10);
1583 }
1584 }
1585
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001586 @VisibleForTesting
1587 static class HandlerCallback implements Handler.Callback {
1588 private final NetworkStatsService mService;
1589
1590 HandlerCallback(NetworkStatsService service) {
1591 this.mService = service;
1592 }
1593
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001594 @Override
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001595 public boolean handleMessage(Message msg) {
1596 switch (msg.what) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001597 case MSG_PERFORM_POLL: {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001598 final int flags = msg.arg1;
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001599 mService.performPoll(flags);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001600 return true;
1601 }
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001602 case MSG_UPDATE_IFACES: {
Lorenzo Colittic78da292018-01-19 00:50:48 +09001603 mService.updateIfaces(null);
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001604 return true;
1605 }
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001606 case MSG_REGISTER_GLOBAL_ALERT: {
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001607 mService.registerGlobalAlert();
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001608 return true;
1609 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001610 default: {
1611 return false;
1612 }
1613 }
1614 }
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001615 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001616
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001617 private void assertSystemReady() {
1618 if (!mSystemReady) {
1619 throw new IllegalStateException("System not ready");
1620 }
1621 }
1622
Jeff Sharkey4190a042012-04-21 15:36:48 -07001623 private void assertBandwidthControlEnabled() {
1624 if (!isBandwidthControlEnabled()) {
1625 throw new IllegalStateException("Bandwidth module disabled");
1626 }
1627 }
1628
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001629 private boolean isBandwidthControlEnabled() {
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001630 final long token = Binder.clearCallingIdentity();
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001631 try {
1632 return mNetworkManager.isBandwidthControlEnabled();
1633 } catch (RemoteException e) {
1634 // ignored; service lives in system_server
1635 return false;
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001636 } finally {
1637 Binder.restoreCallingIdentity(token);
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001638 }
1639 }
1640
Jeff Sharkey63abc372012-01-11 18:38:16 -08001641 private class DropBoxNonMonotonicObserver implements NonMonotonicObserver<String> {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001642 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001643 public void foundNonMonotonic(NetworkStats left, int leftIndex, NetworkStats right,
1644 int rightIndex, String cookie) {
1645 Log.w(TAG, "found non-monotonic values; saving to dropbox");
1646
1647 // record error for debugging
1648 final StringBuilder builder = new StringBuilder();
1649 builder.append("found non-monotonic " + cookie + " values at left[" + leftIndex
1650 + "] - right[" + rightIndex + "]\n");
1651 builder.append("left=").append(left).append('\n');
1652 builder.append("right=").append(right).append('\n');
1653
1654 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
1655 Context.DROPBOX_SERVICE);
1656 dropBox.addText(TAG_NETSTATS_ERROR, builder.toString());
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001657 }
1658 }
1659
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001660 /**
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001661 * Default external settings that read from
Jeff Sharkey625239a2012-09-26 22:03:49 -07001662 * {@link android.provider.Settings.Global}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001663 */
1664 private static class DefaultNetworkStatsSettings implements NetworkStatsSettings {
1665 private final ContentResolver mResolver;
1666
1667 public DefaultNetworkStatsSettings(Context context) {
1668 mResolver = checkNotNull(context.getContentResolver());
1669 // TODO: adjust these timings for production builds
1670 }
1671
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001672 private long getGlobalLong(String name, long def) {
1673 return Settings.Global.getLong(mResolver, name, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001674 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001675 private boolean getGlobalBoolean(String name, boolean def) {
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001676 final int defInt = def ? 1 : 0;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001677 return Settings.Global.getInt(mResolver, name, defInt) != 0;
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001678 }
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001679
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001680 @Override
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001681 public long getPollInterval() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001682 return getGlobalLong(NETSTATS_POLL_INTERVAL, 30 * MINUTE_IN_MILLIS);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001683 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001684 @Override
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001685 public long getGlobalAlertBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001686 return getGlobalLong(NETSTATS_GLOBAL_ALERT_BYTES, def);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001687 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001688 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001689 public boolean getSampleEnabled() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001690 return getGlobalBoolean(NETSTATS_SAMPLE_ENABLED, true);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001691 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001692 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -06001693 public boolean getAugmentEnabled() {
1694 return getGlobalBoolean(NETSTATS_AUGMENT_ENABLED, true);
1695 }
1696 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001697 public Config getDevConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001698 return new Config(getGlobalLong(NETSTATS_DEV_BUCKET_DURATION, HOUR_IN_MILLIS),
1699 getGlobalLong(NETSTATS_DEV_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1700 getGlobalLong(NETSTATS_DEV_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001701 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001702 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001703 public Config getXtConfig() {
1704 return getDevConfig();
1705 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001706 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001707 public Config getUidConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001708 return new Config(getGlobalLong(NETSTATS_UID_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1709 getGlobalLong(NETSTATS_UID_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1710 getGlobalLong(NETSTATS_UID_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001711 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001712 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001713 public Config getUidTagConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001714 return new Config(getGlobalLong(NETSTATS_UID_TAG_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1715 getGlobalLong(NETSTATS_UID_TAG_ROTATE_AGE, 5 * DAY_IN_MILLIS),
1716 getGlobalLong(NETSTATS_UID_TAG_DELETE_AGE, 15 * DAY_IN_MILLIS));
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001717 }
1718 @Override
1719 public long getDevPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001720 return getGlobalLong(NETSTATS_DEV_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001721 }
1722 @Override
1723 public long getXtPersistBytes(long def) {
1724 return getDevPersistBytes(def);
1725 }
1726 @Override
1727 public long getUidPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001728 return getGlobalLong(NETSTATS_UID_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001729 }
1730 @Override
1731 public long getUidTagPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001732 return getGlobalLong(NETSTATS_UID_TAG_PERSIST_BYTES, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001733 }
1734 }
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -08001735
1736 private static int TYPE_RX_BYTES;
1737 private static int TYPE_RX_PACKETS;
1738 private static int TYPE_TX_BYTES;
1739 private static int TYPE_TX_PACKETS;
1740 private static int TYPE_TCP_RX_PACKETS;
1741 private static int TYPE_TCP_TX_PACKETS;
1742
Chenbo Fengaedd6a32017-11-20 18:23:46 -08001743 private static native long nativeGetTotalStat(int type, boolean useBpfStats);
1744 private static native long nativeGetIfaceStat(String iface, int type, boolean useBpfStats);
1745 private static native long nativeGetUidStat(int uid, int type, boolean useBpfStats);
Jeff Sharkey75279902011-05-24 18:39:45 -07001746}