blob: 205ddb07ec44df4ec4a33d4bcbb965417d7fb8cd [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 VAN088ff682018-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 VAN088ff682018-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 Sharkey00072392018-04-12 14:26:32 -060046import static android.os.Trace.TRACE_TAG_NETWORK;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -060047import static android.provider.Settings.Global.NETSTATS_AUGMENT_ENABLED;
Jeff Sharkey023c05a2012-09-14 13:09:57 -070048import static android.provider.Settings.Global.NETSTATS_DEV_BUCKET_DURATION;
49import static android.provider.Settings.Global.NETSTATS_DEV_DELETE_AGE;
50import static android.provider.Settings.Global.NETSTATS_DEV_PERSIST_BYTES;
51import static android.provider.Settings.Global.NETSTATS_DEV_ROTATE_AGE;
52import static android.provider.Settings.Global.NETSTATS_GLOBAL_ALERT_BYTES;
53import static android.provider.Settings.Global.NETSTATS_POLL_INTERVAL;
Jeff Sharkey023c05a2012-09-14 13:09:57 -070054import static android.provider.Settings.Global.NETSTATS_SAMPLE_ENABLED;
Jeff Sharkey023c05a2012-09-14 13:09:57 -070055import static android.provider.Settings.Global.NETSTATS_UID_BUCKET_DURATION;
56import static android.provider.Settings.Global.NETSTATS_UID_DELETE_AGE;
57import static android.provider.Settings.Global.NETSTATS_UID_PERSIST_BYTES;
58import static android.provider.Settings.Global.NETSTATS_UID_ROTATE_AGE;
59import static android.provider.Settings.Global.NETSTATS_UID_TAG_BUCKET_DURATION;
60import static android.provider.Settings.Global.NETSTATS_UID_TAG_DELETE_AGE;
61import static android.provider.Settings.Global.NETSTATS_UID_TAG_PERSIST_BYTES;
62import static android.provider.Settings.Global.NETSTATS_UID_TAG_ROTATE_AGE;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -070063import static android.text.format.DateUtils.DAY_IN_MILLIS;
64import static android.text.format.DateUtils.HOUR_IN_MILLIS;
65import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070066import static android.text.format.DateUtils.SECOND_IN_MILLIS;
Jack Yuf9d559c2017-05-26 16:08:22 -070067
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070068import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070069import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070070import static com.android.server.NetworkManagementSocketTagger.resetKernelUidStats;
71import static com.android.server.NetworkManagementSocketTagger.setKernelCounterSet;
Jeff Sharkey75279902011-05-24 18:39:45 -070072
Jeff Sharkey9911a282018-02-14 22:29:11 -070073import android.annotation.NonNull;
Jeff Sharkey75279902011-05-24 18:39:45 -070074import android.app.AlarmManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070075import android.app.PendingIntent;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -060076import android.app.usage.NetworkStatsManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070077import android.content.BroadcastReceiver;
Jeff Sharkey39ebc212011-06-11 17:25:42 -070078import android.content.ContentResolver;
Jeff Sharkey75279902011-05-24 18:39:45 -070079import android.content.Context;
80import android.content.Intent;
81import android.content.IntentFilter;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -070082import android.content.pm.ApplicationInfo;
83import android.content.pm.PackageManager;
Antonio Cansadocd42acd2016-02-17 13:03:38 -080084import android.net.DataUsageRequest;
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;
Olivier Gaillardf9867ad2018-09-10 15:35:58 +0100107import android.os.Looper;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700108import android.os.Message;
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800109import android.os.Messenger;
Jeff Sharkey62489262011-07-17 12:53:28 -0700110import android.os.PowerManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700111import android.os.RemoteException;
112import android.os.SystemClock;
Jeff Sharkey00072392018-04-12 14:26:32 -0600113import android.os.Trace;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700114import android.os.UserHandle;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700115import android.provider.Settings;
Jeff Sharkey625239a2012-09-26 22:03:49 -0700116import android.provider.Settings.Global;
Makoto Onukida65a522017-01-13 10:23:30 -0800117import android.service.NetworkInterfaceProto;
118import android.service.NetworkStatsServiceDumpProto;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600119import android.telephony.SubscriptionPlan;
Jeff Sharkey75279902011-05-24 18:39:45 -0700120import android.telephony.TelephonyManager;
Jeff Sharkey55a442e2014-11-18 18:22:21 -0800121import android.text.format.DateUtils;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import android.util.ArrayMap;
123import android.util.ArraySet;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -0700124import android.util.EventLog;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700125import android.util.Log;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700126import android.util.MathUtils;
Jeff Sharkey75279902011-05-24 18:39:45 -0700127import android.util.Slog;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700128import android.util.SparseIntArray;
Makoto Onukida65a522017-01-13 10:23:30 -0800129import android.util.proto.ProtoOutputStream;
Jeff Sharkey75279902011-05-24 18:39:45 -0700130
Jeff Sharkey4635f102017-09-01 11:27:13 -0600131import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800132import com.android.internal.annotations.VisibleForTesting;
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +0900133import com.android.internal.net.NetworkStatsFactory;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800134import com.android.internal.net.VpnInfo;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700135import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600136import com.android.internal.util.DumpUtils;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800137import com.android.internal.util.FileRotator;
138import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -0700139import com.android.server.EventLogTags;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700140import com.android.server.LocalServices;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700141import com.android.server.connectivity.Tethering;
Jeff Sharkey75279902011-05-24 18:39:45 -0700142
Jeff Sharkey3f391352011-06-05 17:42:53 -0700143import java.io.File;
Jeff Sharkey75279902011-05-24 18:39:45 -0700144import java.io.FileDescriptor;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700145import java.io.IOException;
Jeff Sharkey75279902011-05-24 18:39:45 -0700146import java.io.PrintWriter;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700147import java.time.Clock;
148import java.time.ZoneOffset;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700149import java.util.Arrays;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700150import java.util.HashSet;
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700151import java.util.List;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700152
Jeff Sharkey75279902011-05-24 18:39:45 -0700153/**
154 * Collect and persist detailed network statistics, and provide this data to
155 * other system services.
156 */
157public class NetworkStatsService extends INetworkStatsService.Stub {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600158 static final String TAG = "NetworkStats";
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700159 static final boolean LOGD = Log.isLoggable(TAG, Log.DEBUG);
160 static final boolean LOGV = Log.isLoggable(TAG, Log.VERBOSE);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700161
Chalard Jeand7c6e122018-08-22 10:21:26 +0900162 // Perform polling and persist all (FLAG_PERSIST_ALL).
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700163 private static final int MSG_PERFORM_POLL = 1;
Chalard Jeand7c6e122018-08-22 10:21:26 +0900164 // Perform polling, persist network, and register the global alert again.
165 private static final int MSG_PERFORM_POLL_REGISTER_ALERT = 2;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700166
167 /** Flags to control detail level of poll event. */
Jeff Sharkey905b5892011-09-30 15:19:49 -0700168 private static final int FLAG_PERSIST_NETWORK = 0x1;
169 private static final int FLAG_PERSIST_UID = 0x2;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700170 private static final int FLAG_PERSIST_ALL = FLAG_PERSIST_NETWORK | FLAG_PERSIST_UID;
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -0700171 private static final int FLAG_PERSIST_FORCE = 0x100;
Jeff Sharkey3f391352011-06-05 17:42:53 -0700172
Chalard Jeand7c6e122018-08-22 10:21:26 +0900173 /**
174 * When global alert quota is high, wait for this delay before processing each polling,
175 * and do not schedule further polls once there is already one queued.
176 * This avoids firing the global alert too often on devices with high transfer speeds and
177 * high quota.
178 */
179 private static final int PERFORM_POLL_DELAY_MS = 1000;
180
Jeff Sharkey163e6442011-10-31 16:37:52 -0700181 private static final String TAG_NETSTATS_ERROR = "netstats_error";
182
Jeff Sharkey75279902011-05-24 18:39:45 -0700183 private final Context mContext;
184 private final INetworkManagementService mNetworkManager;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700185 private final AlarmManager mAlarmManager;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700186 private final Clock mClock;
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700187 private final TelephonyManager mTeleManager;
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700188 private final NetworkStatsSettings mSettings;
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800189 private final NetworkStatsObservers mStatsObservers;
Jeff Sharkey75279902011-05-24 18:39:45 -0700190
Jeff Sharkey63abc372012-01-11 18:38:16 -0800191 private final File mSystemDir;
192 private final File mBaseDir;
193
Jeff Sharkey62489262011-07-17 12:53:28 -0700194 private final PowerManager.WakeLock mWakeLock;
195
Chenbo Feng00499822018-05-18 17:10:07 -0700196 private final boolean mUseBpfTrafficStats;
197
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800198 @VisibleForTesting
Jeff Sharkey3f391352011-06-05 17:42:53 -0700199 public static final String ACTION_NETWORK_STATS_POLL =
Jeff Sharkey75279902011-05-24 18:39:45 -0700200 "com.android.server.action.NETWORK_STATS_POLL";
Jeff Sharkey497e4432011-06-14 17:27:29 -0700201 public static final String ACTION_NETWORK_STATS_UPDATED =
202 "com.android.server.action.NETWORK_STATS_UPDATED";
Jeff Sharkey75279902011-05-24 18:39:45 -0700203
204 private PendingIntent mPollIntent;
205
Jeff Sharkey63abc372012-01-11 18:38:16 -0800206 private static final String PREFIX_DEV = "dev";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700207 private static final String PREFIX_XT = "xt";
Jeff Sharkey63abc372012-01-11 18:38:16 -0800208 private static final String PREFIX_UID = "uid";
209 private static final String PREFIX_UID_TAG = "uid_tag";
210
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700211 /**
Jack Yub6587ea2016-06-22 11:35:10 -0700212 * Virtual network interface for video telephony. This is for VT data usage counting purpose.
213 */
214 public static final String VT_INTERFACE = "vt_data0";
215
216 /**
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700217 * Settings that can be changed externally.
218 */
219 public interface NetworkStatsSettings {
220 public long getPollInterval();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800221 public boolean getSampleEnabled();
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600222 public boolean getAugmentEnabled();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800223
224 public static class Config {
225 public final long bucketDuration;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800226 public final long rotateAgeMillis;
227 public final long deleteAgeMillis;
228
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700229 public Config(long bucketDuration, long rotateAgeMillis, long deleteAgeMillis) {
Jeff Sharkey63abc372012-01-11 18:38:16 -0800230 this.bucketDuration = bucketDuration;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800231 this.rotateAgeMillis = rotateAgeMillis;
232 this.deleteAgeMillis = deleteAgeMillis;
233 }
234 }
235
236 public Config getDevConfig();
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700237 public Config getXtConfig();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800238 public Config getUidConfig();
239 public Config getUidTagConfig();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700240
241 public long getGlobalAlertBytes(long def);
242 public long getDevPersistBytes(long def);
243 public long getXtPersistBytes(long def);
244 public long getUidPersistBytes(long def);
245 public long getUidTagPersistBytes(long def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700246 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700247
248 private final Object mStatsLock = new Object();
249
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700250 /** Set of currently active ifaces. */
Lorenzo Colittic78da292018-01-19 00:50:48 +0900251 @GuardedBy("mStatsLock")
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700252 private final ArrayMap<String, NetworkIdentitySet> mActiveIfaces = new ArrayMap<>();
Lorenzo Colittic78da292018-01-19 00:50:48 +0900253
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700254 /** Set of currently active ifaces for UID stats. */
Lorenzo Colittic78da292018-01-19 00:50:48 +0900255 @GuardedBy("mStatsLock")
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700256 private final ArrayMap<String, NetworkIdentitySet> mActiveUidIfaces = new ArrayMap<>();
Lorenzo Colittic78da292018-01-19 00:50:48 +0900257
Jeff Sharkey63abc372012-01-11 18:38:16 -0800258 /** Current default active iface. */
Varun Anand02c50ef2019-02-07 14:13:13 -0800259 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800260 private String mActiveIface;
Lorenzo Colittic78da292018-01-19 00:50:48 +0900261
Jeff Sharkey234766a2012-04-10 19:48:07 -0700262 /** Set of any ifaces associated with mobile networks since boot. */
Lorenzo Colittic78da292018-01-19 00:50:48 +0900263 @GuardedBy("mStatsLock")
Jeff Sharkey234766a2012-04-10 19:48:07 -0700264 private String[] mMobileIfaces = new String[0];
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700265
Lorenzo Colittic78da292018-01-19 00:50:48 +0900266 /** Set of all ifaces currently used by traffic that does not explicitly specify a Network. */
267 @GuardedBy("mStatsLock")
268 private Network[] mDefaultNetworks = new Network[0];
269
Varun Anand02c50ef2019-02-07 14:13:13 -0800270 /** Set containing info about active VPNs and their underlying networks. */
271 @GuardedBy("mStatsLock")
272 private VpnInfo[] mVpnInfos = new VpnInfo[0];
273
Jeff Sharkey63abc372012-01-11 18:38:16 -0800274 private final DropBoxNonMonotonicObserver mNonMonotonicObserver =
275 new DropBoxNonMonotonicObserver();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -0700276
Jeff Sharkey4635f102017-09-01 11:27:13 -0600277 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800278 private NetworkStatsRecorder mDevRecorder;
Jeff Sharkey4635f102017-09-01 11:27:13 -0600279 @GuardedBy("mStatsLock")
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700280 private NetworkStatsRecorder mXtRecorder;
Jeff Sharkey4635f102017-09-01 11:27:13 -0600281 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800282 private NetworkStatsRecorder mUidRecorder;
Jeff Sharkey4635f102017-09-01 11:27:13 -0600283 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800284 private NetworkStatsRecorder mUidTagRecorder;
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700285
Jeff Sharkey70c70532012-05-16 14:51:19 -0700286 /** Cached {@link #mXtRecorder} stats. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600287 @GuardedBy("mStatsLock")
Jeff Sharkey70c70532012-05-16 14:51:19 -0700288 private NetworkStatsCollection mXtStatsCached;
Jeff Sharkey75279902011-05-24 18:39:45 -0700289
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700290 /** Current counter sets for each UID. */
291 private SparseIntArray mActiveUidCounterSet = new SparseIntArray();
292
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700293 /** Data layer operation counters for splicing into other structures. */
Jeff Sharkey63abc372012-01-11 18:38:16 -0800294 private NetworkStats mUidOperations = new NetworkStats(0L, 10);
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700295
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800296 /** Must be set in factory by calling #setHandler. */
297 private Handler mHandler;
298 private Handler.Callback mHandlerCallback;
Jeff Sharkey75279902011-05-24 18:39:45 -0700299
Jeff Sharkey050151e2018-04-13 14:28:30 -0600300 private volatile boolean mSystemReady;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700301 private long mPersistThreshold = 2 * MB_IN_BYTES;
302 private long mGlobalAlertBytes;
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800303
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900304 private static final long POLL_RATE_LIMIT_MS = 15_000;
305
306 private long mLastStatsSessionPoll;
307
308 /** Map from UID to number of opened sessions */
309 @GuardedBy("mOpenSessionCallsPerUid")
310 private final SparseIntArray mOpenSessionCallsPerUid = new SparseIntArray();
311
312 private final static int DUMP_STATS_SESSION_COUNT = 20;
313
Jeff Sharkey9911a282018-02-14 22:29:11 -0700314 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey3f391352011-06-05 17:42:53 -0700315 return new File(Environment.getDataDirectory(), "system");
Jeff Sharkey75279902011-05-24 18:39:45 -0700316 }
317
Jeff Sharkey9911a282018-02-14 22:29:11 -0700318 private static @NonNull File getDefaultBaseDir() {
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800319 File baseDir = new File(getDefaultSystemDir(), "netstats");
320 baseDir.mkdirs();
321 return baseDir;
322 }
323
Jeff Sharkey9911a282018-02-14 22:29:11 -0700324 private static @NonNull Clock getDefaultClock() {
325 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
326 Clock.systemUTC());
327 }
328
Olivier Gaillardf9867ad2018-09-10 15:35:58 +0100329 private static final class NetworkStatsHandler extends Handler {
330 NetworkStatsHandler(Looper looper, Handler.Callback callback) {
331 super(looper, callback);
332 }
333 }
334
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800335 public static NetworkStatsService create(Context context,
336 INetworkManagementService networkManager) {
337 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
338 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
339 PowerManager.WakeLock wakeLock =
340 powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
341
342 NetworkStatsService service = new NetworkStatsService(context, networkManager, alarmManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700343 wakeLock, getDefaultClock(), TelephonyManager.getDefault(),
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800344 new DefaultNetworkStatsSettings(context), new NetworkStatsObservers(),
345 getDefaultSystemDir(), getDefaultBaseDir());
Remi NGUYEN VAN4cdb2b72018-04-26 17:52:03 +0900346 service.registerLocalService();
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800347
348 HandlerThread handlerThread = new HandlerThread(TAG);
349 Handler.Callback callback = new HandlerCallback(service);
350 handlerThread.start();
Olivier Gaillardf9867ad2018-09-10 15:35:58 +0100351 Handler handler = new NetworkStatsHandler(handlerThread.getLooper(), callback);
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800352 service.setHandler(handler, callback);
353 return service;
354 }
355
Remi NGUYEN VAN4cdb2b72018-04-26 17:52:03 +0900356 // This must not be called outside of tests, even within the same package, as this constructor
357 // does not register the local service. Use the create() helper above.
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800358 @VisibleForTesting
359 NetworkStatsService(Context context, INetworkManagementService networkManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700360 AlarmManager alarmManager, PowerManager.WakeLock wakeLock, Clock clock,
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800361 TelephonyManager teleManager, NetworkStatsSettings settings,
362 NetworkStatsObservers statsObservers, File systemDir, File baseDir) {
Jeff Sharkey75279902011-05-24 18:39:45 -0700363 mContext = checkNotNull(context, "missing Context");
364 mNetworkManager = checkNotNull(networkManager, "missing INetworkManagementService");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800365 mAlarmManager = checkNotNull(alarmManager, "missing AlarmManager");
Jeff Sharkey9911a282018-02-14 22:29:11 -0700366 mClock = checkNotNull(clock, "missing Clock");
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700367 mSettings = checkNotNull(settings, "missing NetworkStatsSettings");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800368 mTeleManager = checkNotNull(teleManager, "missing TelephonyManager");
369 mWakeLock = checkNotNull(wakeLock, "missing WakeLock");
370 mStatsObservers = checkNotNull(statsObservers, "missing NetworkStatsObservers");
371 mSystemDir = checkNotNull(systemDir, "missing systemDir");
372 mBaseDir = checkNotNull(baseDir, "missing baseDir");
Chenbo Feng6880d632018-12-22 13:20:31 -0800373 mUseBpfTrafficStats = new File("/sys/fs/bpf/map_netd_app_uid_stats_map").exists();
Remi NGUYEN VAN4cdb2b72018-04-26 17:52:03 +0900374 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700375
Remi NGUYEN VAN4cdb2b72018-04-26 17:52:03 +0900376 private void registerLocalService() {
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700377 LocalServices.addService(NetworkStatsManagerInternal.class,
378 new NetworkStatsManagerInternalImpl());
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800379 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700380
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800381 @VisibleForTesting
382 void setHandler(Handler handler, Handler.Callback callback) {
383 mHandler = handler;
384 mHandlerCallback = callback;
Jeff Sharkey75279902011-05-24 18:39:45 -0700385 }
386
387 public void systemReady() {
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800388 mSystemReady = true;
389
Jeff Sharkey418d12d2011-12-13 15:38:03 -0800390 if (!isBandwidthControlEnabled()) {
391 Slog.w(TAG, "bandwidth controls disabled, unable to track stats");
392 return;
393 }
394
Jeff Sharkey63abc372012-01-11 18:38:16 -0800395 synchronized (mStatsLock) {
Jeff Sharkey4635f102017-09-01 11:27:13 -0600396 // create data recorders along with historical rotators
397 mDevRecorder = buildRecorder(PREFIX_DEV, mSettings.getDevConfig(), false);
398 mXtRecorder = buildRecorder(PREFIX_XT, mSettings.getXtConfig(), false);
399 mUidRecorder = buildRecorder(PREFIX_UID, mSettings.getUidConfig(), false);
400 mUidTagRecorder = buildRecorder(PREFIX_UID_TAG, mSettings.getUidTagConfig(), true);
401
402 updatePersistThresholdsLocked();
403
Jeff Sharkey63abc372012-01-11 18:38:16 -0800404 // upgrade any legacy stats, migrating them to rotated files
405 maybeUpgradeLegacyStatsLocked();
406
407 // read historical network stats from disk, since policy service
408 // might need them right away.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700409 mXtStatsCached = mXtRecorder.getOrLoadCompleteLocked();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800410
411 // bootstrap initial stats to prevent double-counting later
412 bootstrapStatsLocked();
413 }
Jeff Sharkey3359aca2011-11-08 18:08:48 -0800414
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700415 // watch for tethering changes
416 final IntentFilter tetherFilter = new IntentFilter(ACTION_TETHER_STATE_CHANGED);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700417 mContext.registerReceiver(mTetherReceiver, tetherFilter, null, mHandler);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700418
Jeff Sharkey75279902011-05-24 18:39:45 -0700419 // listen for periodic polling events
420 final IntentFilter pollFilter = new IntentFilter(ACTION_NETWORK_STATS_POLL);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700421 mContext.registerReceiver(mPollReceiver, pollFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
Jeff Sharkey75279902011-05-24 18:39:45 -0700422
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700423 // listen for uid removal to clean stats
424 final IntentFilter removedFilter = new IntentFilter(ACTION_UID_REMOVED);
425 mContext.registerReceiver(mRemovedReceiver, removedFilter, null, mHandler);
426
Jeff Sharkeydaa57e82012-09-19 14:10:39 -0700427 // listen for user changes to clean stats
428 final IntentFilter userFilter = new IntentFilter(ACTION_USER_REMOVED);
429 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
430
Jeff Sharkey75279902011-05-24 18:39:45 -0700431 // persist stats during clean shutdown
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700432 final IntentFilter shutdownFilter = new IntentFilter(ACTION_SHUTDOWN);
433 mContext.registerReceiver(mShutdownReceiver, shutdownFilter);
Jeff Sharkey75279902011-05-24 18:39:45 -0700434
435 try {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700436 mNetworkManager.registerObserver(mAlertObserver);
Jeff Sharkey75279902011-05-24 18:39:45 -0700437 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700438 // ignored; service lives in system_server
Jeff Sharkey75279902011-05-24 18:39:45 -0700439 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700440
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700441 registerPollAlarmLocked();
442 registerGlobalAlert();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800443 }
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700444
Jeff Sharkey63abc372012-01-11 18:38:16 -0800445 private NetworkStatsRecorder buildRecorder(
446 String prefix, NetworkStatsSettings.Config config, boolean includeTags) {
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700447 final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
448 Context.DROPBOX_SERVICE);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700449 return new NetworkStatsRecorder(new FileRotator(
450 mBaseDir, prefix, config.rotateAgeMillis, config.deleteAgeMillis),
Jeff Sharkey6de357e2012-05-09 13:33:52 -0700451 mNonMonotonicObserver, dropBox, prefix, config.bucketDuration, includeTags);
Jeff Sharkey75279902011-05-24 18:39:45 -0700452 }
453
Andreas Gampea36dc622018-02-05 17:19:22 -0800454 @GuardedBy("mStatsLock")
Jeff Sharkey3f391352011-06-05 17:42:53 -0700455 private void shutdownLocked() {
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700456 mContext.unregisterReceiver(mTetherReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700457 mContext.unregisterReceiver(mPollReceiver);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700458 mContext.unregisterReceiver(mRemovedReceiver);
Ryuki Nakamuraa47b0c92017-03-01 10:40:36 +0900459 mContext.unregisterReceiver(mUserReceiver);
Jeff Sharkey3f391352011-06-05 17:42:53 -0700460 mContext.unregisterReceiver(mShutdownReceiver);
461
Jeff Sharkey9911a282018-02-14 22:29:11 -0700462 final long currentTime = mClock.millis();
Jeff Sharkey63abc372012-01-11 18:38:16 -0800463
464 // persist any pending stats
465 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700466 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800467 mUidRecorder.forcePersistLocked(currentTime);
468 mUidTagRecorder.forcePersistLocked(currentTime);
469
Jeff Sharkey6341fce2012-03-06 19:59:57 -0800470 mSystemReady = false;
Jeff Sharkey63abc372012-01-11 18:38:16 -0800471 }
472
Andreas Gampea36dc622018-02-05 17:19:22 -0800473 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -0800474 private void maybeUpgradeLegacyStatsLocked() {
475 File file;
476 try {
477 file = new File(mSystemDir, "netstats.bin");
478 if (file.exists()) {
479 mDevRecorder.importLegacyNetworkLocked(file);
480 file.delete();
481 }
482
483 file = new File(mSystemDir, "netstats_xt.bin");
484 if (file.exists()) {
485 file.delete();
486 }
487
488 file = new File(mSystemDir, "netstats_uid.bin");
489 if (file.exists()) {
490 mUidRecorder.importLegacyUidLocked(file);
491 mUidTagRecorder.importLegacyUidLocked(file);
492 file.delete();
493 }
494 } catch (IOException e) {
495 Log.wtf(TAG, "problem during legacy upgrade", e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700496 } catch (OutOfMemoryError e) {
497 Log.wtf(TAG, "problem during legacy upgrade", e);
Jeff Sharkeyc506ff62011-11-17 11:59:29 -0800498 }
Jeff Sharkey3f391352011-06-05 17:42:53 -0700499 }
500
Jeff Sharkey75279902011-05-24 18:39:45 -0700501 /**
502 * Clear any existing {@link #ACTION_NETWORK_STATS_POLL} alarms, and
Jeff Sharkey39ebc212011-06-11 17:25:42 -0700503 * reschedule based on current {@link NetworkStatsSettings#getPollInterval()}.
Jeff Sharkey75279902011-05-24 18:39:45 -0700504 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700505 private void registerPollAlarmLocked() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506 if (mPollIntent != null) {
507 mAlarmManager.cancel(mPollIntent);
Jeff Sharkey75279902011-05-24 18:39:45 -0700508 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700509
510 mPollIntent = PendingIntent.getBroadcast(
511 mContext, 0, new Intent(ACTION_NETWORK_STATS_POLL), 0);
512
513 final long currentRealtime = SystemClock.elapsedRealtime();
514 mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, currentRealtime,
515 mSettings.getPollInterval(), mPollIntent);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700516 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700517
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700518 /**
519 * Register for a global alert that is delivered through
520 * {@link INetworkManagementEventObserver} once a threshold amount of data
521 * has been transferred.
522 */
523 private void registerGlobalAlert() {
524 try {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700525 mNetworkManager.setGlobalAlert(mGlobalAlertBytes);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700526 } catch (IllegalStateException e) {
527 Slog.w(TAG, "problem registering for global alert: " + e);
528 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700529 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700530 }
Jeff Sharkey75279902011-05-24 18:39:45 -0700531 }
532
533 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700534 public INetworkStatsSession openSession() {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600535 // NOTE: if callers want to get non-augmented data, they should go
536 // through the public API
537 return openSessionInternal(NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN, null);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000538 }
539
540 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600541 public INetworkStatsSession openSessionForUsageStats(int flags, String callingPackage) {
542 return openSessionInternal(flags, callingPackage);
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100543 }
544
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900545 private boolean isRateLimitedForPoll(int callingUid) {
546 if (callingUid == android.os.Process.SYSTEM_UID) {
547 return false;
548 }
549
550 final long lastCallTime;
551 final long now = SystemClock.elapsedRealtime();
552 synchronized (mOpenSessionCallsPerUid) {
553 int calls = mOpenSessionCallsPerUid.get(callingUid, 0);
554 mOpenSessionCallsPerUid.put(callingUid, calls + 1);
555 lastCallTime = mLastStatsSessionPoll;
556 mLastStatsSessionPoll = now;
557 }
558
559 return now - lastCallTime < POLL_RATE_LIMIT_MS;
560 }
561
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600562 private INetworkStatsSession openSessionInternal(final int flags, final String callingPackage) {
Jeff Sharkey4190a042012-04-21 15:36:48 -0700563 assertBandwidthControlEnabled();
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700564
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900565 final int callingUid = Binder.getCallingUid();
566 final int usedFlags = isRateLimitedForPoll(callingUid)
567 ? flags & (~NetworkStatsManager.FLAG_POLL_ON_OPEN)
568 : flags;
Jeff Sharkeyc3c8d162018-04-20 10:59:09 -0600569 if ((usedFlags & (NetworkStatsManager.FLAG_POLL_ON_OPEN
570 | NetworkStatsManager.FLAG_POLL_FORCE)) != 0) {
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100571 final long ident = Binder.clearCallingIdentity();
572 try {
573 performPoll(FLAG_PERSIST_ALL);
574 } finally {
575 Binder.restoreCallingIdentity(ident);
576 }
577 }
578
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700579 // return an IBinder which holds strong references to any loaded stats
580 // for its lifetime; when caller closes only weak references remain.
581
582 return new INetworkStatsSession.Stub() {
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900583 private final int mCallingUid = callingUid;
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600584 private final String mCallingPackage = callingPackage;
585 private final @NetworkStatsAccess.Level int mAccessLevel = checkAccessLevel(
586 callingPackage);
587
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700588 private NetworkStatsCollection mUidComplete;
589 private NetworkStatsCollection mUidTagComplete;
590
591 private NetworkStatsCollection getUidComplete() {
Ashish Sharmac13b9452013-11-01 14:57:30 -0700592 synchronized (mStatsLock) {
593 if (mUidComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700594 mUidComplete = mUidRecorder.getOrLoadCompleteLocked();
595 }
Ashish Sharmac13b9452013-11-01 14:57:30 -0700596 return mUidComplete;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700597 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700598 }
599
600 private NetworkStatsCollection getUidTagComplete() {
Ashish Sharmac13b9452013-11-01 14:57:30 -0700601 synchronized (mStatsLock) {
602 if (mUidTagComplete == null) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700603 mUidTagComplete = mUidTagRecorder.getOrLoadCompleteLocked();
604 }
Ashish Sharmac13b9452013-11-01 14:57:30 -0700605 return mUidTagComplete;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700606 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700607 }
608
609 @Override
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000610 public int[] getRelevantUids() {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600611 return getUidComplete().getRelevantUids(mAccessLevel);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000612 }
613
614 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600615 public NetworkStats getDeviceSummaryForNetwork(
616 NetworkTemplate template, long start, long end) {
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900617 return internalGetSummaryForNetwork(template, usedFlags, start, end, mAccessLevel,
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600618 mCallingUid);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000619 }
620
621 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700622 public NetworkStats getSummaryForNetwork(
623 NetworkTemplate template, long start, long end) {
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900624 return internalGetSummaryForNetwork(template, usedFlags, start, end, mAccessLevel,
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600625 mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700626 }
627
628 @Override
629 public NetworkStatsHistory getHistoryForNetwork(NetworkTemplate template, int fields) {
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +0900630 return internalGetHistoryForNetwork(template, usedFlags, fields, mAccessLevel,
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600631 mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700632 }
633
634 @Override
635 public NetworkStats getSummaryForAllUid(
636 NetworkTemplate template, long start, long end, boolean includeTags) {
Jeff Davidson39583b52016-12-12 11:55:37 -0800637 try {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600638 final NetworkStats stats = getUidComplete()
639 .getSummary(template, start, end, mAccessLevel, mCallingUid);
Jeff Davidson39583b52016-12-12 11:55:37 -0800640 if (includeTags) {
641 final NetworkStats tagStats = getUidTagComplete()
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600642 .getSummary(template, start, end, mAccessLevel, mCallingUid);
Jeff Davidson39583b52016-12-12 11:55:37 -0800643 stats.combineAllValues(tagStats);
644 }
645 return stats;
646 } catch (NullPointerException e) {
647 // TODO: Track down and fix the cause of this crash and remove this catch block.
648 Slog.wtf(TAG, "NullPointerException in getSummaryForAllUid", e);
649 throw e;
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700650 }
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700651 }
652
653 @Override
654 public NetworkStatsHistory getHistoryForUid(
655 NetworkTemplate template, int uid, int set, int tag, int fields) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600656 // NOTE: We don't augment UID-level statistics
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700657 if (tag == TAG_NONE) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600658 return getUidComplete().getHistory(template, null, uid, set, tag, fields,
659 Long.MIN_VALUE, Long.MAX_VALUE, mAccessLevel, mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700660 } else {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600661 return getUidTagComplete().getHistory(template, null, uid, set, tag, fields,
662 Long.MIN_VALUE, Long.MAX_VALUE, mAccessLevel, mCallingUid);
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700663 }
664 }
665
666 @Override
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100667 public NetworkStatsHistory getHistoryIntervalForUid(
668 NetworkTemplate template, int uid, int set, int tag, int fields,
669 long start, long end) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600670 // NOTE: We don't augment UID-level statistics
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100671 if (tag == TAG_NONE) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600672 return getUidComplete().getHistory(template, null, uid, set, tag, fields,
673 start, end, mAccessLevel, mCallingUid);
Antonio Cansado6965c182016-03-30 11:37:18 -0700674 } else if (uid == Binder.getCallingUid()) {
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600675 return getUidTagComplete().getHistory(template, null, uid, set, tag, fields,
676 start, end, mAccessLevel, mCallingUid);
Antonio Cansado6965c182016-03-30 11:37:18 -0700677 } else {
678 throw new SecurityException("Calling package " + mCallingPackage
679 + " cannot access tag information from a different uid");
Zoltan Szatmary-Ban72027d22015-06-16 15:49:16 +0100680 }
681 }
682
683 @Override
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -0700684 public void close() {
685 mUidComplete = null;
686 mUidTagComplete = null;
687 }
688 };
Jeff Sharkey905b5892011-09-30 15:19:49 -0700689 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700690
Jeff Davidson1efb1332015-12-09 18:04:50 -0800691 private @NetworkStatsAccess.Level int checkAccessLevel(String callingPackage) {
692 return NetworkStatsAccess.checkAccessLevel(
693 mContext, Binder.getCallingUid(), callingPackage);
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +0000694 }
695
Jeff Sharkey70c70532012-05-16 14:51:19 -0700696 /**
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600697 * Find the most relevant {@link SubscriptionPlan} for the given
698 * {@link NetworkTemplate} and flags. This is typically used to augment
699 * local measurement results to match a known anchor from the carrier.
700 */
701 private SubscriptionPlan resolveSubscriptionPlan(NetworkTemplate template, int flags) {
702 SubscriptionPlan plan = null;
703 if ((flags & NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN) != 0
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600704 && mSettings.getAugmentEnabled()) {
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700705 if (LOGD) Slog.d(TAG, "Resolving plan for " + template);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600706 final long token = Binder.clearCallingIdentity();
707 try {
Jeff Sharkey146bb332018-04-18 15:42:57 -0600708 plan = LocalServices.getService(NetworkPolicyManagerInternal.class)
709 .getSubscriptionPlan(template);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600710 } finally {
711 Binder.restoreCallingIdentity(token);
712 }
Jeff Sharkey4e0d3072018-02-20 13:36:14 -0700713 if (LOGD) Slog.d(TAG, "Resolved to plan " + plan);
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600714 }
715 return plan;
716 }
717
718 /**
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700719 * Return network summary, splicing between DEV and XT stats when
720 * appropriate.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700721 */
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600722 private NetworkStats internalGetSummaryForNetwork(NetworkTemplate template, int flags,
723 long start, long end, @NetworkStatsAccess.Level int accessLevel, int callingUid) {
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700724 // We've been using pure XT stats long enough that we no longer need to
725 // splice DEV and XT together.
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600726 final NetworkStatsHistory history = internalGetHistoryForNetwork(template, flags, FIELD_ALL,
727 accessLevel, callingUid);
728
729 final long now = System.currentTimeMillis();
730 final NetworkStatsHistory.Entry entry = history.getValues(start, end, now, null);
731
732 final NetworkStats stats = new NetworkStats(end - start, 1);
Lorenzo Colittiada23ed2018-01-19 01:05:20 +0900733 stats.addValues(new NetworkStats.Entry(IFACE_ALL, UID_ALL, SET_ALL, TAG_NONE,
734 METERED_ALL, ROAMING_ALL, DEFAULT_NETWORK_ALL, entry.rxBytes, entry.rxPackets,
735 entry.txBytes, entry.txPackets, entry.operations));
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600736 return stats;
Jeff Sharkey70c70532012-05-16 14:51:19 -0700737 }
738
739 /**
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700740 * Return network history, splicing between DEV and XT stats when
741 * appropriate.
Jeff Sharkey70c70532012-05-16 14:51:19 -0700742 */
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600743 private NetworkStatsHistory internalGetHistoryForNetwork(NetworkTemplate template,
744 int flags, int fields, @NetworkStatsAccess.Level int accessLevel, int callingUid) {
Jeff Sharkey5274dcc2014-10-24 13:15:15 -0700745 // We've been using pure XT stats long enough that we no longer need to
746 // splice DEV and XT together.
Jeff Sharkey4635f102017-09-01 11:27:13 -0600747 final SubscriptionPlan augmentPlan = resolveSubscriptionPlan(template, flags);
748 synchronized (mStatsLock) {
749 return mXtStatsCached.getHistory(template, augmentPlan,
750 UID_ALL, SET_ALL, TAG_NONE, fields, Long.MIN_VALUE, Long.MAX_VALUE,
751 accessLevel, callingUid);
752 }
Jeff Sharkey70c70532012-05-16 14:51:19 -0700753 }
754
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700755 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
756 assertSystemReady();
Jeff Sharkey4190a042012-04-21 15:36:48 -0700757 assertBandwidthControlEnabled();
Jeff Sharkeyf4de2942017-08-29 15:32:13 -0600758
759 // NOTE: if callers want to get non-augmented data, they should go
760 // through the public API
761 return internalGetSummaryForNetwork(template,
762 NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN, start, end,
763 NetworkStatsAccess.Level.DEVICE, Binder.getCallingUid()).getTotalBytes();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700764 }
765
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700766 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
767 assertSystemReady();
768 assertBandwidthControlEnabled();
769
770 final NetworkStatsCollection uidComplete;
771 synchronized (mStatsLock) {
772 uidComplete = mUidRecorder.getOrLoadCompleteLocked();
773 }
774 return uidComplete.getSummary(template, start, end, NetworkStatsAccess.Level.DEVICE,
775 android.os.Process.SYSTEM_UID);
776 }
777
Jeff Sharkey350083e2011-06-29 10:45:16 -0700778 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700779 public NetworkStats getDataLayerSnapshotForUid(int uid) throws RemoteException {
780 if (Binder.getCallingUid() != uid) {
781 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
782 }
Jeff Sharkey4190a042012-04-21 15:36:48 -0700783 assertBandwidthControlEnabled();
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700784
785 // TODO: switch to data layer stats once kernel exports
786 // for now, read network layer stats and flatten across all ifaces
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800787 final long token = Binder.clearCallingIdentity();
788 final NetworkStats networkLayer;
789 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +0900790 networkLayer = mNetworkManager.getNetworkStatsUidDetail(uid,
791 NetworkStats.INTERFACES_ALL);
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800792 } finally {
793 Binder.restoreCallingIdentity(token);
794 }
795
Jeff Sharkey21a54782012-04-09 10:27:55 -0700796 // splice in operation counts
797 networkLayer.spliceOperationsFrom(mUidOperations);
798
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700799 final NetworkStats dataLayer = new NetworkStats(
800 networkLayer.getElapsedRealtime(), networkLayer.size());
801
802 NetworkStats.Entry entry = null;
803 for (int i = 0; i < networkLayer.size(); i++) {
804 entry = networkLayer.getValues(i, entry);
805 entry.iface = IFACE_ALL;
806 dataLayer.combineValues(entry);
807 }
808
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700809 return dataLayer;
810 }
811
812 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +0900813 public NetworkStats getDetailedUidStats(String[] requiredIfaces) {
814 try {
815 final String[] ifacesToQuery =
Remi NGUYEN VAN9fb55e42018-02-27 16:47:22 +0900816 NetworkStatsFactory.augmentWithStackedInterfaces(requiredIfaces);
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +0900817 return getNetworkStatsUidDetail(ifacesToQuery);
818 } catch (RemoteException e) {
819 Log.wtf(TAG, "Error compiling UID stats", e);
820 return new NetworkStats(0L, 0);
821 }
822 }
823
824 @Override
Jeff Sharkey234766a2012-04-10 19:48:07 -0700825 public String[] getMobileIfaces() {
826 return mMobileIfaces;
827 }
828
829 @Override
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700830 public void incrementOperationCount(int uid, int tag, int operationCount) {
831 if (Binder.getCallingUid() != uid) {
Jeff Sharkey9f09e6a72017-06-26 11:24:47 -0600832 mContext.enforceCallingOrSelfPermission(
833 android.Manifest.permission.UPDATE_DEVICE_STATS, TAG);
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700834 }
835
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700836 if (operationCount < 0) {
837 throw new IllegalArgumentException("operation count can only be incremented");
838 }
839 if (tag == TAG_NONE) {
840 throw new IllegalArgumentException("operation count must have specific tag");
841 }
842
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700843 synchronized (mStatsLock) {
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700844 final int set = mActiveUidCounterSet.get(uid, SET_DEFAULT);
Jeff Sharkey63abc372012-01-11 18:38:16 -0800845 mUidOperations.combineValues(
846 mActiveIface, uid, set, tag, 0L, 0L, 0L, 0L, operationCount);
847 mUidOperations.combineValues(
848 mActiveIface, uid, set, TAG_NONE, 0L, 0L, 0L, 0L, operationCount);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700849 }
850 }
851
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700852 @VisibleForTesting
853 void setUidForeground(int uid, boolean uidForeground) {
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700854 synchronized (mStatsLock) {
855 final int set = uidForeground ? SET_FOREGROUND : SET_DEFAULT;
856 final int oldSet = mActiveUidCounterSet.get(uid, SET_DEFAULT);
857 if (oldSet != set) {
858 mActiveUidCounterSet.put(uid, set);
859 setKernelCounterSet(uid, set);
860 }
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700861 }
862 }
863
864 @Override
Varun Anand02c50ef2019-02-07 14:13:13 -0800865 public void forceUpdateIfaces(
866 Network[] defaultNetworks,
867 VpnInfo[] vpnArray,
868 NetworkState[] networkStates,
869 String activeIface) {
Jeff Sharkey69736342014-12-08 14:50:12 -0800870 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
871 assertBandwidthControlEnabled();
872
873 final long token = Binder.clearCallingIdentity();
874 try {
Varun Anand02c50ef2019-02-07 14:13:13 -0800875 updateIfaces(defaultNetworks, vpnArray, networkStates, activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -0800876 } finally {
877 Binder.restoreCallingIdentity(token);
878 }
879 }
880
881 @Override
Jeff Sharkey350083e2011-06-29 10:45:16 -0700882 public void forceUpdate() {
883 mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
Jeff Sharkey4190a042012-04-21 15:36:48 -0700884 assertBandwidthControlEnabled();
Jeff Sharkeye630f7b2012-01-31 17:12:53 -0800885
886 final long token = Binder.clearCallingIdentity();
887 try {
888 performPoll(FLAG_PERSIST_ALL);
889 } finally {
890 Binder.restoreCallingIdentity(token);
891 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700892 }
893
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700894 private void advisePersistThreshold(long thresholdBytes) {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700895 assertBandwidthControlEnabled();
896
897 // clamp threshold into safe range
898 mPersistThreshold = MathUtils.constrain(thresholdBytes, 128 * KB_IN_BYTES, 2 * MB_IN_BYTES);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700899 if (LOGV) {
900 Slog.v(TAG, "advisePersistThreshold() given " + thresholdBytes + ", clamped to "
901 + mPersistThreshold);
902 }
903
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700904 // update and persist if beyond new thresholds
Jeff Sharkey9911a282018-02-14 22:29:11 -0700905 final long currentTime = mClock.millis();
Jeff Sharkey58015972012-05-07 11:08:49 -0700906 synchronized (mStatsLock) {
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700907 if (!mSystemReady) return;
908
Jeff Sharkey4635f102017-09-01 11:27:13 -0600909 updatePersistThresholdsLocked();
Jeff Sharkey20f5c3d2012-05-09 19:59:07 -0700910
Jeff Sharkey58015972012-05-07 11:08:49 -0700911 mDevRecorder.maybePersistLocked(currentTime);
912 mXtRecorder.maybePersistLocked(currentTime);
913 mUidRecorder.maybePersistLocked(currentTime);
914 mUidTagRecorder.maybePersistLocked(currentTime);
915 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700916
917 // re-arm global alert
918 registerGlobalAlert();
919 }
920
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800921 @Override
Antonio Cansado6965c182016-03-30 11:37:18 -0700922 public DataUsageRequest registerUsageCallback(String callingPackage,
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800923 DataUsageRequest request, Messenger messenger, IBinder binder) {
924 checkNotNull(callingPackage, "calling package is null");
925 checkNotNull(request, "DataUsageRequest is null");
Antonio Cansado6965c182016-03-30 11:37:18 -0700926 checkNotNull(request.template, "NetworkTemplate is null");
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800927 checkNotNull(messenger, "messenger is null");
928 checkNotNull(binder, "binder is null");
929
930 int callingUid = Binder.getCallingUid();
931 @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(callingPackage);
932 DataUsageRequest normalizedRequest;
933 final long token = Binder.clearCallingIdentity();
934 try {
935 normalizedRequest = mStatsObservers.register(request, messenger, binder,
936 callingUid, accessLevel);
937 } finally {
938 Binder.restoreCallingIdentity(token);
939 }
940
941 // Create baseline stats
Chalard Jeand7c6e122018-08-22 10:21:26 +0900942 mHandler.sendMessage(mHandler.obtainMessage(MSG_PERFORM_POLL));
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800943
944 return normalizedRequest;
945 }
946
947 @Override
Antonio Cansado6965c182016-03-30 11:37:18 -0700948 public void unregisterUsageRequest(DataUsageRequest request) {
Antonio Cansadocd42acd2016-02-17 13:03:38 -0800949 checkNotNull(request, "DataUsageRequest is null");
950
951 int callingUid = Binder.getCallingUid();
952 final long token = Binder.clearCallingIdentity();
953 try {
954 mStatsObservers.unregister(request, callingUid);
955 } finally {
956 Binder.restoreCallingIdentity(token);
957 }
958 }
959
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800960 @Override
961 public long getUidStats(int uid, int type) {
Chenbo Fengaedd6a32017-11-20 18:23:46 -0800962 return nativeGetUidStat(uid, type, checkBpfStatsEnable());
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800963 }
964
965 @Override
966 public long getIfaceStats(String iface, int type) {
Mike SU1f9ed0b2018-11-26 15:05:13 +0800967 long nativeIfaceStats = nativeGetIfaceStat(iface, type, checkBpfStatsEnable());
968 if (nativeIfaceStats == -1) {
969 return nativeIfaceStats;
970 } else {
971 // When tethering offload is in use, nativeIfaceStats does not contain usage from
972 // offload, add it back here.
973 // When tethering offload is not in use, nativeIfaceStats contains tethering usage.
974 // this does not cause double-counting of tethering traffic, because
975 // NetdTetheringStatsProvider returns zero NetworkStats
976 // when called with STATS_PER_IFACE.
977 return nativeIfaceStats + getTetherStats(iface, type);
978 }
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -0800979 }
980
981 @Override
982 public long getTotalStats(int type) {
Mike SU1f9ed0b2018-11-26 15:05:13 +0800983 long nativeTotalStats = nativeGetTotalStat(type, checkBpfStatsEnable());
984 if (nativeTotalStats == -1) {
985 return nativeTotalStats;
986 } else {
987 // Refer to comment in getIfaceStats
988 return nativeTotalStats + getTetherStats(IFACE_ALL, type);
989 }
990 }
991
992 private long getTetherStats(String iface, int type) {
993 final NetworkStats tetherSnapshot;
994 final long token = Binder.clearCallingIdentity();
995 try {
996 tetherSnapshot = getNetworkStatsTethering(STATS_PER_IFACE);
997 } catch (RemoteException e) {
998 Slog.w(TAG, "Error get TetherStats: " + e);
999 return 0;
1000 } finally {
1001 Binder.restoreCallingIdentity(token);
1002 }
1003 HashSet<String> limitIfaces;
1004 if (iface == IFACE_ALL) {
1005 limitIfaces = null;
1006 } else {
1007 limitIfaces = new HashSet<String>();
1008 limitIfaces.add(iface);
1009 }
1010 NetworkStats.Entry entry = tetherSnapshot.getTotal(null, limitIfaces);
1011 if (LOGD) Slog.d(TAG, "TetherStats: iface=" + iface + " type=" + type +
1012 " entry=" + entry);
1013 switch (type) {
1014 case 0: // TYPE_RX_BYTES
1015 return entry.rxBytes;
1016 case 1: // TYPE_RX_PACKETS
1017 return entry.rxPackets;
1018 case 2: // TYPE_TX_BYTES
1019 return entry.txBytes;
1020 case 3: // TYPE_TX_PACKETS
1021 return entry.txPackets;
1022 default:
1023 return 0;
1024 }
Chenbo Fengaedd6a32017-11-20 18:23:46 -08001025 }
1026
1027 private boolean checkBpfStatsEnable() {
Chenbo Feng00499822018-05-18 17:10:07 -07001028 return mUseBpfTrafficStats;
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -08001029 }
1030
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001031 /**
1032 * Update {@link NetworkStatsRecorder} and {@link #mGlobalAlertBytes} to
1033 * reflect current {@link #mPersistThreshold} value. Always defers to
Jeff Sharkey625239a2012-09-26 22:03:49 -07001034 * {@link Global} values when defined.
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001035 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001036 @GuardedBy("mStatsLock")
Jeff Sharkey4635f102017-09-01 11:27:13 -06001037 private void updatePersistThresholdsLocked() {
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001038 mDevRecorder.setPersistThreshold(mSettings.getDevPersistBytes(mPersistThreshold));
1039 mXtRecorder.setPersistThreshold(mSettings.getXtPersistBytes(mPersistThreshold));
1040 mUidRecorder.setPersistThreshold(mSettings.getUidPersistBytes(mPersistThreshold));
1041 mUidTagRecorder.setPersistThreshold(mSettings.getUidTagPersistBytes(mPersistThreshold));
1042 mGlobalAlertBytes = mSettings.getGlobalAlertBytes(mPersistThreshold);
1043 }
1044
Jeff Sharkey75279902011-05-24 18:39:45 -07001045 /**
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001046 * Receiver that watches for {@link Tethering} to claim interface pairs.
1047 */
1048 private BroadcastReceiver mTetherReceiver = new BroadcastReceiver() {
1049 @Override
1050 public void onReceive(Context context, Intent intent) {
1051 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1052 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001053 performPoll(FLAG_PERSIST_NETWORK);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001054 }
1055 };
1056
Jeff Sharkey75279902011-05-24 18:39:45 -07001057 private BroadcastReceiver mPollReceiver = new BroadcastReceiver() {
1058 @Override
1059 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001060 // on background handler thread, and verified UPDATE_DEVICE_STATS
1061 // permission above.
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001062 performPoll(FLAG_PERSIST_ALL);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001063
1064 // verify that we're watching global alert
1065 registerGlobalAlert();
Jeff Sharkey75279902011-05-24 18:39:45 -07001066 }
1067 };
1068
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001069 private BroadcastReceiver mRemovedReceiver = new BroadcastReceiver() {
1070 @Override
1071 public void onReceive(Context context, Intent intent) {
1072 // on background handler thread, and UID_REMOVED is protected
1073 // broadcast.
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001074
1075 final int uid = intent.getIntExtra(EXTRA_UID, -1);
1076 if (uid == -1) return;
1077
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001078 synchronized (mStatsLock) {
Jeff Sharkey62489262011-07-17 12:53:28 -07001079 mWakeLock.acquire();
1080 try {
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001081 removeUidsLocked(uid);
1082 } finally {
1083 mWakeLock.release();
1084 }
1085 }
1086 }
1087 };
1088
1089 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
1090 @Override
1091 public void onReceive(Context context, Intent intent) {
1092 // On background handler thread, and USER_REMOVED is protected
1093 // broadcast.
1094
1095 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1096 if (userId == -1) return;
1097
1098 synchronized (mStatsLock) {
1099 mWakeLock.acquire();
1100 try {
1101 removeUserLocked(userId);
Jeff Sharkey62489262011-07-17 12:53:28 -07001102 } finally {
1103 mWakeLock.release();
1104 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001105 }
1106 }
1107 };
1108
Jeff Sharkey75279902011-05-24 18:39:45 -07001109 private BroadcastReceiver mShutdownReceiver = new BroadcastReceiver() {
1110 @Override
1111 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001112 // SHUTDOWN is protected broadcast.
Jeff Sharkey75279902011-05-24 18:39:45 -07001113 synchronized (mStatsLock) {
Jeff Sharkey3f391352011-06-05 17:42:53 -07001114 shutdownLocked();
Jeff Sharkey75279902011-05-24 18:39:45 -07001115 }
1116 }
1117 };
1118
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001119 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001120 * Observer that watches for {@link INetworkManagementService} alerts.
1121 */
Jeff Sharkey216c1812012-08-05 14:29:23 -07001122 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001123 @Override
1124 public void limitReached(String limitName, String iface) {
1125 // only someone like NMS should be calling us
1126 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1127
1128 if (LIMIT_GLOBAL_ALERT.equals(limitName)) {
Chalard Jeand7c6e122018-08-22 10:21:26 +09001129 // kick off background poll to collect network stats unless there is already
1130 // such a call pending; UID stats are handled during normal polling interval.
1131 if (!mHandler.hasMessages(MSG_PERFORM_POLL_REGISTER_ALERT)) {
1132 mHandler.sendEmptyMessageDelayed(MSG_PERFORM_POLL_REGISTER_ALERT,
1133 PERFORM_POLL_DELAY_MS);
1134 }
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001135 }
1136 }
1137 };
1138
Varun Anand02c50ef2019-02-07 14:13:13 -08001139 private void updateIfaces(
1140 Network[] defaultNetworks,
1141 VpnInfo[] vpnArray,
1142 NetworkState[] networkStates,
1143 String activeIface) {
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001144 synchronized (mStatsLock) {
1145 mWakeLock.acquire();
1146 try {
Varun Anand02c50ef2019-02-07 14:13:13 -08001147 mVpnInfos = vpnArray;
1148 mActiveIface = activeIface;
1149 updateIfacesLocked(defaultNetworks, networkStates);
Jeff Sharkey367d15a2011-09-22 14:59:51 -07001150 } finally {
1151 mWakeLock.release();
1152 }
1153 }
1154 }
1155
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001156 /**
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001157 * Inspect all current {@link NetworkState} to derive mapping from {@code
1158 * iface} to {@link NetworkStatsHistory}. When multiple {@link NetworkInfo}
1159 * are active on a single {@code iface}, they are combined under a single
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001160 * {@link NetworkIdentitySet}.
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001161 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001162 @GuardedBy("mStatsLock")
Varun Anand02c50ef2019-02-07 14:13:13 -08001163 private void updateIfacesLocked(Network[] defaultNetworks, NetworkState[] states) {
Jeff Sharkey6341fce2012-03-06 19:59:57 -08001164 if (!mSystemReady) return;
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001165 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001166
1167 // take one last stats snapshot before updating iface mapping. this
1168 // isn't perfect, since the kernel may already be counting traffic from
1169 // the updated network.
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001170
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001171 // poll, but only persist network stats to keep codepath fast. UID stats
1172 // will be persisted during next alarm poll event.
1173 performPollLocked(FLAG_PERSIST_NETWORK);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001174
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001175 // Rebuild active interfaces based on connected networks
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001176 mActiveIfaces.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001177 mActiveUidIfaces.clear();
Lorenzo Colittic78da292018-01-19 00:50:48 +09001178 if (defaultNetworks != null) {
1179 // Caller is ConnectivityService. Update the list of default networks.
1180 mDefaultNetworks = defaultNetworks;
1181 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001182
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001183 final ArraySet<String> mobileIfaces = new ArraySet<>();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001184 for (NetworkState state : states) {
1185 if (state.networkInfo.isConnected()) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001186 final boolean isMobile = isNetworkTypeMobile(state.networkInfo.getType());
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001187 final boolean isDefault = ArrayUtils.contains(mDefaultNetworks, state.network);
1188 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1189 isDefault);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001190
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001191 // Traffic occurring on the base interface is always counted for
1192 // both total usage and UID details.
1193 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001194 if (baseIface != null) {
1195 findOrCreateNetworkIdentitySet(mActiveIfaces, baseIface).add(ident);
1196 findOrCreateNetworkIdentitySet(mActiveUidIfaces, baseIface).add(ident);
Jack Yub6587ea2016-06-22 11:35:10 -07001197
1198 // Build a separate virtual interface for VT (Video Telephony) data usage.
1199 // Only do this when IMS is not metered, but VT is metered.
1200 // If IMS is metered, then the IMS network usage has already included VT usage.
1201 // VT is considered always metered in framework's layer. If VT is not metered
1202 // per carrier's policy, modem will report 0 usage for VT calls.
1203 if (state.networkCapabilities.hasCapability(
1204 NetworkCapabilities.NET_CAPABILITY_IMS) && !ident.getMetered()) {
1205
1206 // Copy the identify from IMS one but mark it as metered.
1207 NetworkIdentity vtIdent = new NetworkIdentity(ident.getType(),
1208 ident.getSubType(), ident.getSubscriberId(), ident.getNetworkId(),
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001209 ident.getRoaming(), true /* metered */,
1210 true /* onDefaultNetwork */);
Jack Yub6587ea2016-06-22 11:35:10 -07001211 findOrCreateNetworkIdentitySet(mActiveIfaces, VT_INTERFACE).add(vtIdent);
1212 findOrCreateNetworkIdentitySet(mActiveUidIfaces, VT_INTERFACE).add(vtIdent);
1213 }
1214
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001215 if (isMobile) {
1216 mobileIfaces.add(baseIface);
1217 }
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001218 }
1219
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001220 // Traffic occurring on stacked interfaces is usually clatd,
1221 // which is already accounted against its final egress interface
1222 // by the kernel. Thus, we only need to collect stacked
1223 // interface stats at the UID level.
1224 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1225 for (LinkProperties stackedLink : stackedLinks) {
1226 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001227 if (stackedIface != null) {
1228 findOrCreateNetworkIdentitySet(mActiveUidIfaces, stackedIface).add(ident);
1229 if (isMobile) {
1230 mobileIfaces.add(stackedIface);
1231 }
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001232
1233 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
Jeff Sharkey234766a2012-04-10 19:48:07 -07001234 }
1235 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001236 }
1237 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001238
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001239 mMobileIfaces = mobileIfaces.toArray(new String[mobileIfaces.size()]);
1240 }
1241
1242 private static <K> NetworkIdentitySet findOrCreateNetworkIdentitySet(
1243 ArrayMap<K, NetworkIdentitySet> map, K key) {
1244 NetworkIdentitySet ident = map.get(key);
1245 if (ident == null) {
1246 ident = new NetworkIdentitySet();
1247 map.put(key, ident);
1248 }
1249 return ident;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001250 }
1251
Andreas Gampea36dc622018-02-05 17:19:22 -08001252 @GuardedBy("mStatsLock")
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001253 private void recordSnapshotLocked(long currentTime) throws RemoteException {
1254 // snapshot and record current counters; read UID stats first to
Jack Yub6587ea2016-06-22 11:35:10 -07001255 // avoid over counting dev stats.
Jeff Sharkey00072392018-04-12 14:26:32 -06001256 Trace.traceBegin(TRACE_TAG_NETWORK, "snapshotUid");
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001257 final NetworkStats uidSnapshot = getNetworkStatsUidDetail(INTERFACES_ALL);
Jeff Sharkey00072392018-04-12 14:26:32 -06001258 Trace.traceEnd(TRACE_TAG_NETWORK);
1259 Trace.traceBegin(TRACE_TAG_NETWORK, "snapshotXt");
Jack Yuf9d559c2017-05-26 16:08:22 -07001260 final NetworkStats xtSnapshot = getNetworkStatsXt();
Jeff Sharkey00072392018-04-12 14:26:32 -06001261 Trace.traceEnd(TRACE_TAG_NETWORK);
1262 Trace.traceBegin(TRACE_TAG_NETWORK, "snapshotDev");
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001263 final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
Jeff Sharkey00072392018-04-12 14:26:32 -06001264 Trace.traceEnd(TRACE_TAG_NETWORK);
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001265
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001266 // Tethering snapshot for dev and xt stats. Counts per-interface data from tethering stats
1267 // providers that isn't already counted by dev and XT stats.
Jeff Sharkey00072392018-04-12 14:26:32 -06001268 Trace.traceBegin(TRACE_TAG_NETWORK, "snapshotTether");
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001269 final NetworkStats tetherSnapshot = getNetworkStatsTethering(STATS_PER_IFACE);
Jeff Sharkey00072392018-04-12 14:26:32 -06001270 Trace.traceEnd(TRACE_TAG_NETWORK);
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001271 xtSnapshot.combineAllValues(tetherSnapshot);
1272 devSnapshot.combineAllValues(tetherSnapshot);
Jeff Davidson4ff3bcf2016-06-15 13:31:52 -07001273
1274 // For xt/dev, we pass a null VPN array because usage is aggregated by UID, so VPN traffic
1275 // can't be reattributed to responsible apps.
Jeff Sharkey00072392018-04-12 14:26:32 -06001276 Trace.traceBegin(TRACE_TAG_NETWORK, "recordDev");
Jeff Davidson4ff3bcf2016-06-15 13:31:52 -07001277 mDevRecorder.recordSnapshotLocked(
1278 devSnapshot, mActiveIfaces, null /* vpnArray */, currentTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001279 Trace.traceEnd(TRACE_TAG_NETWORK);
1280 Trace.traceBegin(TRACE_TAG_NETWORK, "recordXt");
Jeff Davidson4ff3bcf2016-06-15 13:31:52 -07001281 mXtRecorder.recordSnapshotLocked(
1282 xtSnapshot, mActiveIfaces, null /* vpnArray */, currentTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001283 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Davidson4ff3bcf2016-06-15 13:31:52 -07001284
1285 // For per-UID stats, pass the VPN info so VPN traffic is reattributed to responsible apps.
Varun Anand02c50ef2019-02-07 14:13:13 -08001286 VpnInfo[] vpnArray = mVpnInfos;
Jeff Sharkey00072392018-04-12 14:26:32 -06001287 Trace.traceBegin(TRACE_TAG_NETWORK, "recordUid");
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001288 mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001289 Trace.traceEnd(TRACE_TAG_NETWORK);
1290 Trace.traceBegin(TRACE_TAG_NETWORK, "recordUidTag");
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001291 mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001292 Trace.traceEnd(TRACE_TAG_NETWORK);
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001293
1294 // We need to make copies of member fields that are sent to the observer to avoid
1295 // a race condition between the service handler thread and the observer's
1296 mStatsObservers.updateStats(xtSnapshot, uidSnapshot, new ArrayMap<>(mActiveIfaces),
1297 new ArrayMap<>(mActiveUidIfaces), vpnArray, currentTime);
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001298 }
1299
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001300 /**
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001301 * Bootstrap initial stats snapshot, usually during {@link #systemReady()}
1302 * so we have baseline values without double-counting.
1303 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001304 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -08001305 private void bootstrapStatsLocked() {
Jeff Sharkey9911a282018-02-14 22:29:11 -07001306 final long currentTime = mClock.millis();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001307
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001308 try {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001309 recordSnapshotLocked(currentTime);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001310 } catch (IllegalStateException e) {
1311 Slog.w(TAG, "problem reading network stats: " + e);
1312 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001313 // ignored; service lives in system_server
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001314 }
1315 }
1316
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001317 private void performPoll(int flags) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001318 synchronized (mStatsLock) {
1319 mWakeLock.acquire();
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001320
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001321 try {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001322 performPollLocked(flags);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001323 } finally {
1324 mWakeLock.release();
1325 }
1326 }
1327 }
1328
1329 /**
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001330 * Periodic poll operation, reading current statistics and recording into
1331 * {@link NetworkStatsHistory}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001332 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001333 @GuardedBy("mStatsLock")
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001334 private void performPollLocked(int flags) {
Jeff Sharkey6341fce2012-03-06 19:59:57 -08001335 if (!mSystemReady) return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001336 if (LOGV) Slog.v(TAG, "performPollLocked(flags=0x" + Integer.toHexString(flags) + ")");
Jeff Sharkey00072392018-04-12 14:26:32 -06001337 Trace.traceBegin(TRACE_TAG_NETWORK, "performPollLocked");
Jeff Sharkey75279902011-05-24 18:39:45 -07001338
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001339 final boolean persistNetwork = (flags & FLAG_PERSIST_NETWORK) != 0;
1340 final boolean persistUid = (flags & FLAG_PERSIST_UID) != 0;
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001341 final boolean persistForce = (flags & FLAG_PERSIST_FORCE) != 0;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001342
Jeff Sharkey75279902011-05-24 18:39:45 -07001343 // TODO: consider marking "untrusted" times in historical stats
Jeff Sharkey9911a282018-02-14 22:29:11 -07001344 final long currentTime = mClock.millis();
Jeff Sharkey75279902011-05-24 18:39:45 -07001345
Jeff Sharkey75279902011-05-24 18:39:45 -07001346 try {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001347 recordSnapshotLocked(currentTime);
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001348 } catch (IllegalStateException e) {
1349 Log.wtf(TAG, "problem reading network stats", e);
Jeff Sharkey905b5892011-09-30 15:19:49 -07001350 return;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001351 } catch (RemoteException e) {
1352 // ignored; service lives in system_server
Jeff Sharkey905b5892011-09-30 15:19:49 -07001353 return;
1354 }
1355
Jeff Sharkey63abc372012-01-11 18:38:16 -08001356 // persist any pending data depending on requested flags
Jeff Sharkey00072392018-04-12 14:26:32 -06001357 Trace.traceBegin(TRACE_TAG_NETWORK, "[persisting]");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001358 if (persistForce) {
1359 mDevRecorder.forcePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001360 mXtRecorder.forcePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001361 mUidRecorder.forcePersistLocked(currentTime);
1362 mUidTagRecorder.forcePersistLocked(currentTime);
1363 } else {
1364 if (persistNetwork) {
1365 mDevRecorder.maybePersistLocked(currentTime);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001366 mXtRecorder.maybePersistLocked(currentTime);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001367 }
1368 if (persistUid) {
1369 mUidRecorder.maybePersistLocked(currentTime);
1370 mUidTagRecorder.maybePersistLocked(currentTime);
1371 }
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001372 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001373 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001374
Jeff Sharkey63abc372012-01-11 18:38:16 -08001375 if (mSettings.getSampleEnabled()) {
Jeff Sharkey905b5892011-09-30 15:19:49 -07001376 // sample stats after each full poll
Jeff Sharkey63abc372012-01-11 18:38:16 -08001377 performSampleLocked();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001378 }
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001379
Jeff Sharkey497e4432011-06-14 17:27:29 -07001380 // finally, dispatch updated event to any listeners
1381 final Intent updatedIntent = new Intent(ACTION_NETWORK_STATS_UPDATED);
1382 updatedIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001383 mContext.sendBroadcastAsUser(updatedIntent, UserHandle.ALL,
1384 READ_NETWORK_USAGE_HISTORY);
Jeff Sharkey00072392018-04-12 14:26:32 -06001385
1386 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001387 }
1388
1389 /**
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001390 * Sample recent statistics summary into {@link EventLog}.
1391 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001392 @GuardedBy("mStatsLock")
Jeff Sharkey63abc372012-01-11 18:38:16 -08001393 private void performSampleLocked() {
1394 // TODO: migrate trustedtime fixes to separate binary log events
Jeff Sharkey9911a282018-02-14 22:29:11 -07001395 final long currentTime = mClock.millis();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001396
Jeff Sharkey63abc372012-01-11 18:38:16 -08001397 NetworkTemplate template;
1398 NetworkStats.Entry devTotal;
1399 NetworkStats.Entry xtTotal;
1400 NetworkStats.Entry uidTotal;
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001401
1402 // collect mobile sample
Jeff Sharkey234766a2012-04-10 19:48:07 -07001403 template = buildTemplateMobileWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001404 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001405 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001406 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001407
Jeff Sharkey905b5892011-09-30 15:19:49 -07001408 EventLogTags.writeNetstatsMobileSample(
1409 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1410 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1411 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey9911a282018-02-14 22:29:11 -07001412 currentTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001413
1414 // collect wifi sample
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001415 template = buildTemplateWifiWildcard();
Jeff Sharkey63abc372012-01-11 18:38:16 -08001416 devTotal = mDevRecorder.getTotalSinceBootLocked(template);
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001417 xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001418 uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
1419
Jeff Sharkey905b5892011-09-30 15:19:49 -07001420 EventLogTags.writeNetstatsWifiSample(
1421 devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1422 xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1423 uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
Jeff Sharkey9911a282018-02-14 22:29:11 -07001424 currentTime);
Jeff Sharkey07b0dd92011-09-01 13:06:19 -07001425 }
1426
1427 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001428 * Clean up {@link #mUidRecorder} after UID is removed.
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001429 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001430 @GuardedBy("mStatsLock")
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001431 private void removeUidsLocked(int... uids) {
1432 if (LOGV) Slog.v(TAG, "removeUidsLocked() for UIDs " + Arrays.toString(uids));
1433
1434 // Perform one last poll before removing
Jeff Sharkey163e6442011-10-31 16:37:52 -07001435 performPollLocked(FLAG_PERSIST_ALL);
1436
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001437 mUidRecorder.removeUidsLocked(uids);
1438 mUidTagRecorder.removeUidsLocked(uids);
Jeff Sharkey163e6442011-10-31 16:37:52 -07001439
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001440 // Clear kernel stats associated with UID
1441 for (int uid : uids) {
1442 resetKernelUidStats(uid);
1443 }
1444 }
1445
1446 /**
1447 * Clean up {@link #mUidRecorder} after user is removed.
1448 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001449 @GuardedBy("mStatsLock")
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001450 private void removeUserLocked(int userId) {
1451 if (LOGV) Slog.v(TAG, "removeUserLocked() for userId=" + userId);
1452
1453 // Build list of UIDs that we should clean up
1454 int[] uids = new int[0];
1455 final List<ApplicationInfo> apps = mContext.getPackageManager().getInstalledApplications(
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001456 PackageManager.MATCH_ANY_USER
1457 | PackageManager.MATCH_DISABLED_COMPONENTS);
Jeff Sharkeydaa57e82012-09-19 14:10:39 -07001458 for (ApplicationInfo app : apps) {
1459 final int uid = UserHandle.getUid(userId, app.uid);
1460 uids = ArrayUtils.appendInt(uids, uid);
1461 }
1462
1463 removeUidsLocked(uids);
Jeff Sharkey75279902011-05-24 18:39:45 -07001464 }
1465
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001466 private class NetworkStatsManagerInternalImpl extends NetworkStatsManagerInternal {
1467 @Override
1468 public long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey00072392018-04-12 14:26:32 -06001469 Trace.traceBegin(TRACE_TAG_NETWORK, "getNetworkTotalBytes");
1470 try {
1471 return NetworkStatsService.this.getNetworkTotalBytes(template, start, end);
1472 } finally {
1473 Trace.traceEnd(TRACE_TAG_NETWORK);
1474 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001475 }
1476
1477 @Override
1478 public NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey00072392018-04-12 14:26:32 -06001479 Trace.traceBegin(TRACE_TAG_NETWORK, "getNetworkUidBytes");
1480 try {
1481 return NetworkStatsService.this.getNetworkUidBytes(template, start, end);
1482 } finally {
1483 Trace.traceEnd(TRACE_TAG_NETWORK);
1484 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001485 }
1486
1487 @Override
1488 public void setUidForeground(int uid, boolean uidForeground) {
1489 NetworkStatsService.this.setUidForeground(uid, uidForeground);
1490 }
1491
1492 @Override
1493 public void advisePersistThreshold(long thresholdBytes) {
1494 NetworkStatsService.this.advisePersistThreshold(thresholdBytes);
1495 }
1496
1497 @Override
1498 public void forceUpdate() {
1499 NetworkStatsService.this.forceUpdate();
1500 }
1501 }
1502
Jeff Sharkey75279902011-05-24 18:39:45 -07001503 @Override
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001504 protected void dump(FileDescriptor fd, PrintWriter rawWriter, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001505 if (!DumpUtils.checkDumpPermission(mContext, TAG, rawWriter)) return;
Jeff Sharkey75279902011-05-24 18:39:45 -07001506
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001507 long duration = DateUtils.DAY_IN_MILLIS;
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001508 final HashSet<String> argSet = new HashSet<String>();
1509 for (String arg : args) {
1510 argSet.add(arg);
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001511
1512 if (arg.startsWith("--duration=")) {
1513 try {
1514 duration = Long.parseLong(arg.substring(11));
1515 } catch (NumberFormatException ignored) {
1516 }
1517 }
Jeff Sharkey75279902011-05-24 18:39:45 -07001518 }
1519
Jeff Sharkey706498d2012-02-06 17:35:07 -08001520 // usage: dumpsys netstats --full --uid --tag --poll --checkin
Jeff Sharkey63abc372012-01-11 18:38:16 -08001521 final boolean poll = argSet.contains("--poll") || argSet.contains("poll");
Jeff Sharkey706498d2012-02-06 17:35:07 -08001522 final boolean checkin = argSet.contains("--checkin");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001523 final boolean fullHistory = argSet.contains("--full") || argSet.contains("full");
1524 final boolean includeUid = argSet.contains("--uid") || argSet.contains("detail");
1525 final boolean includeTag = argSet.contains("--tag") || argSet.contains("detail");
1526
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001527 final IndentingPrintWriter pw = new IndentingPrintWriter(rawWriter, " ");
Jeff Sharkey350083e2011-06-29 10:45:16 -07001528
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001529 synchronized (mStatsLock) {
Makoto Onukida65a522017-01-13 10:23:30 -08001530 if (args.length > 0 && "--proto".equals(args[0])) {
1531 // In this case ignore all other arguments.
Jeff Sharkey4635f102017-09-01 11:27:13 -06001532 dumpProtoLocked(fd);
Makoto Onukida65a522017-01-13 10:23:30 -08001533 return;
1534 }
1535
Jeff Sharkey63abc372012-01-11 18:38:16 -08001536 if (poll) {
Jeff Sharkey1f0b13b2011-09-18 13:30:23 -07001537 performPollLocked(FLAG_PERSIST_ALL | FLAG_PERSIST_FORCE);
Jeff Sharkey3f391352011-06-05 17:42:53 -07001538 pw.println("Forced poll");
1539 return;
1540 }
1541
Jeff Sharkey706498d2012-02-06 17:35:07 -08001542 if (checkin) {
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001543 final long end = System.currentTimeMillis();
1544 final long start = end - duration;
1545
1546 pw.print("v1,");
1547 pw.print(start / SECOND_IN_MILLIS); pw.print(',');
1548 pw.print(end / SECOND_IN_MILLIS); pw.println();
1549
1550 pw.println("xt");
1551 mXtRecorder.dumpCheckin(rawWriter, start, end);
1552
1553 if (includeUid) {
1554 pw.println("uid");
1555 mUidRecorder.dumpCheckin(rawWriter, start, end);
Jeff Sharkey706498d2012-02-06 17:35:07 -08001556 }
Jeff Sharkey55a442e2014-11-18 18:22:21 -08001557 if (includeTag) {
1558 pw.println("tag");
1559 mUidTagRecorder.dumpCheckin(rawWriter, start, end);
1560 }
Jeff Sharkey706498d2012-02-06 17:35:07 -08001561 return;
1562 }
1563
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001564 pw.println("Active interfaces:");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001565 pw.increaseIndent();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001566 for (int i = 0; i < mActiveIfaces.size(); i++) {
1567 pw.printPair("iface", mActiveIfaces.keyAt(i));
1568 pw.printPair("ident", mActiveIfaces.valueAt(i));
1569 pw.println();
1570 }
1571 pw.decreaseIndent();
1572
1573 pw.println("Active UID interfaces:");
1574 pw.increaseIndent();
1575 for (int i = 0; i < mActiveUidIfaces.size(); i++) {
1576 pw.printPair("iface", mActiveUidIfaces.keyAt(i));
1577 pw.printPair("ident", mActiveUidIfaces.valueAt(i));
1578 pw.println();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001579 }
Jeff Sharkey63abc372012-01-11 18:38:16 -08001580 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001581
Remi NGUYEN VANabc6e182018-04-12 19:26:34 +09001582 // Get the top openSession callers
1583 final SparseIntArray calls;
1584 synchronized (mOpenSessionCallsPerUid) {
1585 calls = mOpenSessionCallsPerUid.clone();
1586 }
1587
1588 final int N = calls.size();
1589 final long[] values = new long[N];
1590 for (int j = 0; j < N; j++) {
1591 values[j] = ((long) calls.valueAt(j) << 32) | calls.keyAt(j);
1592 }
1593 Arrays.sort(values);
1594
1595 pw.println("Top openSession callers (uid=count):");
1596 pw.increaseIndent();
1597 final int end = Math.max(0, N - DUMP_STATS_SESSION_COUNT);
1598 for (int j = N - 1; j >= end; j--) {
1599 final int uid = (int) (values[j] & 0xffffffff);
1600 final int count = (int) (values[j] >> 32);
1601 pw.print(uid); pw.print("="); pw.println(count);
1602 }
1603 pw.decreaseIndent();
1604 pw.println();
1605
Jeff Sharkey63abc372012-01-11 18:38:16 -08001606 pw.println("Dev stats:");
1607 pw.increaseIndent();
1608 mDevRecorder.dumpLocked(pw, fullHistory);
1609 pw.decreaseIndent();
1610
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001611 pw.println("Xt stats:");
1612 pw.increaseIndent();
1613 mXtRecorder.dumpLocked(pw, fullHistory);
1614 pw.decreaseIndent();
1615
Jeff Sharkey63abc372012-01-11 18:38:16 -08001616 if (includeUid) {
1617 pw.println("UID stats:");
1618 pw.increaseIndent();
1619 mUidRecorder.dumpLocked(pw, fullHistory);
1620 pw.decreaseIndent();
Jeff Sharkey905b5892011-09-30 15:19:49 -07001621 }
1622
Jeff Sharkey63abc372012-01-11 18:38:16 -08001623 if (includeTag) {
1624 pw.println("UID tag stats:");
1625 pw.increaseIndent();
1626 mUidTagRecorder.dumpLocked(pw, fullHistory);
1627 pw.decreaseIndent();
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001628 }
1629 }
1630 }
1631
Andreas Gampea36dc622018-02-05 17:19:22 -08001632 @GuardedBy("mStatsLock")
Jeff Sharkey4635f102017-09-01 11:27:13 -06001633 private void dumpProtoLocked(FileDescriptor fd) {
Makoto Onukida65a522017-01-13 10:23:30 -08001634 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1635
1636 // TODO Right now it writes all history. Should it limit to the "since-boot" log?
1637
1638 dumpInterfaces(proto, NetworkStatsServiceDumpProto.ACTIVE_INTERFACES, mActiveIfaces);
1639 dumpInterfaces(proto, NetworkStatsServiceDumpProto.ACTIVE_UID_INTERFACES, mActiveUidIfaces);
1640 mDevRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.DEV_STATS);
1641 mXtRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.XT_STATS);
1642 mUidRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.UID_STATS);
1643 mUidTagRecorder.writeToProtoLocked(proto, NetworkStatsServiceDumpProto.UID_TAG_STATS);
1644
1645 proto.flush();
1646 }
1647
1648 private static void dumpInterfaces(ProtoOutputStream proto, long tag,
1649 ArrayMap<String, NetworkIdentitySet> ifaces) {
1650 for (int i = 0; i < ifaces.size(); i++) {
1651 final long start = proto.start(tag);
1652
1653 proto.write(NetworkInterfaceProto.INTERFACE, ifaces.keyAt(i));
1654 ifaces.valueAt(i).writeToProto(proto, NetworkInterfaceProto.IDENTITIES);
1655
1656 proto.end(start);
1657 }
1658 }
1659
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001660 /**
Jeff Sharkey63abc372012-01-11 18:38:16 -08001661 * Return snapshot of current UID statistics, including any
Jack Yuf9d559c2017-05-26 16:08:22 -07001662 * {@link TrafficStats#UID_TETHERING}, video calling data usage, and {@link #mUidOperations}
1663 * values.
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001664 *
1665 * @param ifaces A list of interfaces the stats should be restricted to, or
1666 * {@link NetworkStats#INTERFACES_ALL}.
Jeff Sharkey61ee0bb2011-05-29 22:50:42 -07001667 */
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001668 private NetworkStats getNetworkStatsUidDetail(String[] ifaces)
1669 throws RemoteException {
1670
Remi NGUYEN VAN9fb55e42018-02-27 16:47:22 +09001671 // TODO: remove 464xlat adjustments from NetworkStatsFactory and apply all at once here.
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001672 final NetworkStats uidSnapshot = mNetworkManager.getNetworkStatsUidDetail(UID_ALL,
1673 ifaces);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001674
Jeff Sharkey63abc372012-01-11 18:38:16 -08001675 // fold tethering stats and operations into uid snapshot
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001676 final NetworkStats tetherSnapshot = getNetworkStatsTethering(STATS_PER_UID);
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001677 tetherSnapshot.filter(UID_ALL, ifaces, TAG_ALL);
junyulaic33ac0d2018-10-19 21:14:30 +08001678 NetworkStatsFactory.apply464xlatAdjustments(uidSnapshot, tetherSnapshot,
1679 mUseBpfTrafficStats);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001680 uidSnapshot.combineAllValues(tetherSnapshot);
Jack Yuf9d559c2017-05-26 16:08:22 -07001681
1682 final TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(
1683 Context.TELEPHONY_SERVICE);
1684
1685 // fold video calling data usage stats into uid snapshot
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001686 final NetworkStats vtStats = telephonyManager.getVtDataUsage(STATS_PER_UID);
Jack Yuf9d559c2017-05-26 16:08:22 -07001687 if (vtStats != null) {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001688 vtStats.filter(UID_ALL, ifaces, TAG_ALL);
junyulaic33ac0d2018-10-19 21:14:30 +08001689 NetworkStatsFactory.apply464xlatAdjustments(uidSnapshot, vtStats,
1690 mUseBpfTrafficStats);
Jack Yuf9d559c2017-05-26 16:08:22 -07001691 uidSnapshot.combineAllValues(vtStats);
1692 }
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001693
Jeff Sharkey63abc372012-01-11 18:38:16 -08001694 uidSnapshot.combineAllValues(mUidOperations);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001695
Jeff Sharkey63abc372012-01-11 18:38:16 -08001696 return uidSnapshot;
Jeff Sharkey75279902011-05-24 18:39:45 -07001697 }
1698
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001699 /**
Jack Yuf9d559c2017-05-26 16:08:22 -07001700 * Return snapshot of current XT statistics with video calling data usage statistics.
Jack Yub6587ea2016-06-22 11:35:10 -07001701 */
Jack Yuf9d559c2017-05-26 16:08:22 -07001702 private NetworkStats getNetworkStatsXt() throws RemoteException {
Jack Yub6587ea2016-06-22 11:35:10 -07001703 final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
1704
Jack Yuf9d559c2017-05-26 16:08:22 -07001705 final TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(
Jack Yub6587ea2016-06-22 11:35:10 -07001706 Context.TELEPHONY_SERVICE);
1707
Jack Yuf9d559c2017-05-26 16:08:22 -07001708 // Merge video calling data usage into XT
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001709 final NetworkStats vtSnapshot = telephonyManager.getVtDataUsage(STATS_PER_IFACE);
Jack Yuf9d559c2017-05-26 16:08:22 -07001710 if (vtSnapshot != null) {
1711 xtSnapshot.combineAllValues(vtSnapshot);
1712 }
Jack Yub6587ea2016-06-22 11:35:10 -07001713
1714 return xtSnapshot;
1715 }
1716
1717 /**
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001718 * Return snapshot of current tethering statistics. Will return empty
1719 * {@link NetworkStats} if any problems are encountered.
1720 */
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001721 private NetworkStats getNetworkStatsTethering(int how) throws RemoteException {
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001722 try {
Lorenzo Colitti5356a352017-08-17 19:23:08 +09001723 return mNetworkManager.getNetworkStatsTethering(how);
Jeff Sharkeyd4ef8c8f2011-11-10 17:54:23 -08001724 } catch (IllegalStateException e) {
1725 Log.wtf(TAG, "problem reading network stats", e);
1726 return new NetworkStats(0L, 10);
1727 }
1728 }
1729
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001730 @VisibleForTesting
1731 static class HandlerCallback implements Handler.Callback {
1732 private final NetworkStatsService mService;
1733
1734 HandlerCallback(NetworkStatsService service) {
1735 this.mService = service;
1736 }
1737
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001738 @Override
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001739 public boolean handleMessage(Message msg) {
1740 switch (msg.what) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001741 case MSG_PERFORM_POLL: {
Chalard Jeand7c6e122018-08-22 10:21:26 +09001742 mService.performPoll(FLAG_PERSIST_ALL);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001743 return true;
1744 }
Chalard Jeand7c6e122018-08-22 10:21:26 +09001745 case MSG_PERFORM_POLL_REGISTER_ALERT: {
1746 mService.performPoll(FLAG_PERSIST_NETWORK);
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001747 mService.registerGlobalAlert();
Jeff Sharkey25ce9ed2012-02-02 13:07:47 -08001748 return true;
1749 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001750 default: {
1751 return false;
1752 }
1753 }
1754 }
Antonio Cansadocd42acd2016-02-17 13:03:38 -08001755 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001756
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001757 private void assertSystemReady() {
1758 if (!mSystemReady) {
1759 throw new IllegalStateException("System not ready");
1760 }
1761 }
1762
Jeff Sharkey4190a042012-04-21 15:36:48 -07001763 private void assertBandwidthControlEnabled() {
1764 if (!isBandwidthControlEnabled()) {
1765 throw new IllegalStateException("Bandwidth module disabled");
1766 }
1767 }
1768
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001769 private boolean isBandwidthControlEnabled() {
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001770 final long token = Binder.clearCallingIdentity();
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001771 try {
1772 return mNetworkManager.isBandwidthControlEnabled();
1773 } catch (RemoteException e) {
1774 // ignored; service lives in system_server
1775 return false;
Jeff Sharkey49c1d172012-04-23 14:39:19 -07001776 } finally {
1777 Binder.restoreCallingIdentity(token);
Jeff Sharkey418d12d2011-12-13 15:38:03 -08001778 }
1779 }
1780
Jeff Sharkey63abc372012-01-11 18:38:16 -08001781 private class DropBoxNonMonotonicObserver implements NonMonotonicObserver<String> {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001782 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001783 public void foundNonMonotonic(NetworkStats left, int leftIndex, NetworkStats right,
1784 int rightIndex, String cookie) {
Jeff Sharkeyb5a97e62018-05-22 11:35:29 -06001785 Log.w(TAG, "Found non-monotonic values; saving to dropbox");
Jeff Sharkey63abc372012-01-11 18:38:16 -08001786
1787 // record error for debugging
1788 final StringBuilder builder = new StringBuilder();
1789 builder.append("found non-monotonic " + cookie + " values at left[" + leftIndex
1790 + "] - right[" + rightIndex + "]\n");
1791 builder.append("left=").append(left).append('\n');
1792 builder.append("right=").append(right).append('\n');
1793
Jeff Sharkeyb5a97e62018-05-22 11:35:29 -06001794 mContext.getSystemService(DropBoxManager.class).addText(TAG_NETSTATS_ERROR,
1795 builder.toString());
1796 }
1797
1798 @Override
1799 public void foundNonMonotonic(
1800 NetworkStats stats, int statsIndex, String cookie) {
1801 Log.w(TAG, "Found non-monotonic values; saving to dropbox");
1802
1803 final StringBuilder builder = new StringBuilder();
1804 builder.append("Found non-monotonic " + cookie + " values at [" + statsIndex + "]\n");
1805 builder.append("stats=").append(stats).append('\n');
1806
1807 mContext.getSystemService(DropBoxManager.class).addText(TAG_NETSTATS_ERROR,
1808 builder.toString());
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001809 }
1810 }
1811
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001812 /**
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001813 * Default external settings that read from
Jeff Sharkey625239a2012-09-26 22:03:49 -07001814 * {@link android.provider.Settings.Global}.
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001815 */
1816 private static class DefaultNetworkStatsSettings implements NetworkStatsSettings {
1817 private final ContentResolver mResolver;
1818
1819 public DefaultNetworkStatsSettings(Context context) {
1820 mResolver = checkNotNull(context.getContentResolver());
1821 // TODO: adjust these timings for production builds
1822 }
1823
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001824 private long getGlobalLong(String name, long def) {
1825 return Settings.Global.getLong(mResolver, name, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001826 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001827 private boolean getGlobalBoolean(String name, boolean def) {
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001828 final int defInt = def ? 1 : 0;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001829 return Settings.Global.getInt(mResolver, name, defInt) != 0;
Jeff Sharkey991d1b12011-09-14 19:31:04 -07001830 }
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001831
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001832 @Override
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001833 public long getPollInterval() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001834 return getGlobalLong(NETSTATS_POLL_INTERVAL, 30 * MINUTE_IN_MILLIS);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001835 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001836 @Override
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001837 public long getGlobalAlertBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001838 return getGlobalLong(NETSTATS_GLOBAL_ALERT_BYTES, def);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001839 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001840 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001841 public boolean getSampleEnabled() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001842 return getGlobalBoolean(NETSTATS_SAMPLE_ENABLED, true);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001843 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001844 @Override
Jeff Sharkeyf4de2942017-08-29 15:32:13 -06001845 public boolean getAugmentEnabled() {
1846 return getGlobalBoolean(NETSTATS_AUGMENT_ENABLED, true);
1847 }
1848 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001849 public Config getDevConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001850 return new Config(getGlobalLong(NETSTATS_DEV_BUCKET_DURATION, HOUR_IN_MILLIS),
1851 getGlobalLong(NETSTATS_DEV_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1852 getGlobalLong(NETSTATS_DEV_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001853 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001854 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001855 public Config getXtConfig() {
1856 return getDevConfig();
1857 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001858 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001859 public Config getUidConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001860 return new Config(getGlobalLong(NETSTATS_UID_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1861 getGlobalLong(NETSTATS_UID_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1862 getGlobalLong(NETSTATS_UID_DELETE_AGE, 90 * DAY_IN_MILLIS));
Jeff Sharkey63abc372012-01-11 18:38:16 -08001863 }
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001864 @Override
Jeff Sharkey63abc372012-01-11 18:38:16 -08001865 public Config getUidTagConfig() {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001866 return new Config(getGlobalLong(NETSTATS_UID_TAG_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1867 getGlobalLong(NETSTATS_UID_TAG_ROTATE_AGE, 5 * DAY_IN_MILLIS),
1868 getGlobalLong(NETSTATS_UID_TAG_DELETE_AGE, 15 * DAY_IN_MILLIS));
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001869 }
1870 @Override
1871 public long getDevPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001872 return getGlobalLong(NETSTATS_DEV_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001873 }
1874 @Override
1875 public long getXtPersistBytes(long def) {
1876 return getDevPersistBytes(def);
1877 }
1878 @Override
1879 public long getUidPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001880 return getGlobalLong(NETSTATS_UID_PERSIST_BYTES, def);
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001881 }
1882 @Override
1883 public long getUidTagPersistBytes(long def) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001884 return getGlobalLong(NETSTATS_UID_TAG_PERSIST_BYTES, def);
Jeff Sharkey39ebc212011-06-11 17:25:42 -07001885 }
1886 }
Chenbo Fengd3d9c4e2017-11-14 17:54:17 -08001887
1888 private static int TYPE_RX_BYTES;
1889 private static int TYPE_RX_PACKETS;
1890 private static int TYPE_TX_BYTES;
1891 private static int TYPE_TX_PACKETS;
1892 private static int TYPE_TCP_RX_PACKETS;
1893 private static int TYPE_TCP_TX_PACKETS;
1894
Chenbo Fengaedd6a32017-11-20 18:23:46 -08001895 private static native long nativeGetTotalStat(int type, boolean useBpfStats);
1896 private static native long nativeGetIfaceStat(String iface, int type, boolean useBpfStats);
1897 private static native long nativeGetUidStat(int uid, int type, boolean useBpfStats);
Jeff Sharkey75279902011-05-24 18:39:45 -07001898}