NetworkStatsService.java revision 9158825f9c41869689d6b1786d7c7aa8bdd524ce
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
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
19import static android.Manifest.permission.ACCESS_NETWORK_STATE;
20import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
21import static android.Manifest.permission.DUMP;
22import static android.Manifest.permission.MODIFY_NETWORK_ACCOUNTING;
23import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
24import static android.content.Intent.ACTION_SHUTDOWN;
25import static android.content.Intent.ACTION_UID_REMOVED;
26import static android.content.Intent.ACTION_USER_REMOVED;
27import static android.content.Intent.EXTRA_UID;
28import static android.net.ConnectivityManager.ACTION_TETHER_STATE_CHANGED;
29import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
30import static android.net.ConnectivityManager.isNetworkTypeMobile;
31import static android.net.NetworkIdentity.COMBINE_SUBTYPE_ENABLED;
32import static android.net.NetworkStats.IFACE_ALL;
33import static android.net.NetworkStats.SET_ALL;
34import static android.net.NetworkStats.SET_DEFAULT;
35import static android.net.NetworkStats.SET_FOREGROUND;
36import static android.net.NetworkStats.TAG_NONE;
37import static android.net.NetworkStats.UID_ALL;
38import static android.net.NetworkTemplate.buildTemplateMobileWildcard;
39import static android.net.NetworkTemplate.buildTemplateWifiWildcard;
40import static android.net.TrafficStats.KB_IN_BYTES;
41import static android.net.TrafficStats.MB_IN_BYTES;
42import static android.provider.Settings.Global.NETSTATS_DEV_BUCKET_DURATION;
43import static android.provider.Settings.Global.NETSTATS_DEV_DELETE_AGE;
44import static android.provider.Settings.Global.NETSTATS_DEV_PERSIST_BYTES;
45import static android.provider.Settings.Global.NETSTATS_DEV_ROTATE_AGE;
46import static android.provider.Settings.Global.NETSTATS_GLOBAL_ALERT_BYTES;
47import static android.provider.Settings.Global.NETSTATS_POLL_INTERVAL;
48import static android.provider.Settings.Global.NETSTATS_REPORT_XT_OVER_DEV;
49import static android.provider.Settings.Global.NETSTATS_SAMPLE_ENABLED;
50import static android.provider.Settings.Global.NETSTATS_TIME_CACHE_MAX_AGE;
51import static android.provider.Settings.Global.NETSTATS_UID_BUCKET_DURATION;
52import static android.provider.Settings.Global.NETSTATS_UID_DELETE_AGE;
53import static android.provider.Settings.Global.NETSTATS_UID_PERSIST_BYTES;
54import static android.provider.Settings.Global.NETSTATS_UID_ROTATE_AGE;
55import static android.provider.Settings.Global.NETSTATS_UID_TAG_BUCKET_DURATION;
56import static android.provider.Settings.Global.NETSTATS_UID_TAG_DELETE_AGE;
57import static android.provider.Settings.Global.NETSTATS_UID_TAG_PERSIST_BYTES;
58import static android.provider.Settings.Global.NETSTATS_UID_TAG_ROTATE_AGE;
59import static android.telephony.PhoneStateListener.LISTEN_DATA_CONNECTION_STATE;
60import static android.telephony.PhoneStateListener.LISTEN_NONE;
61import static android.text.format.DateUtils.DAY_IN_MILLIS;
62import static android.text.format.DateUtils.HOUR_IN_MILLIS;
63import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
64import static android.text.format.DateUtils.SECOND_IN_MILLIS;
65import static com.android.internal.util.ArrayUtils.appendElement;
66import static com.android.internal.util.ArrayUtils.contains;
67import static com.android.internal.util.Preconditions.checkNotNull;
68import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
69import static com.android.server.NetworkManagementSocketTagger.resetKernelUidStats;
70import static com.android.server.NetworkManagementSocketTagger.setKernelCounterSet;
71
72import android.app.AlarmManager;
73import android.app.IAlarmManager;
74import android.app.PendingIntent;
75import android.content.BroadcastReceiver;
76import android.content.ContentResolver;
77import android.content.Context;
78import android.content.Intent;
79import android.content.IntentFilter;
80import android.content.pm.ApplicationInfo;
81import android.content.pm.PackageManager;
82import android.net.IConnectivityManager;
83import android.net.INetworkManagementEventObserver;
84import android.net.INetworkStatsService;
85import android.net.INetworkStatsSession;
86import android.net.LinkProperties;
87import android.net.NetworkIdentity;
88import android.net.NetworkInfo;
89import android.net.NetworkState;
90import android.net.NetworkStats;
91import android.net.NetworkStats.NonMonotonicObserver;
92import android.net.NetworkStatsHistory;
93import android.net.NetworkTemplate;
94import android.net.TrafficStats;
95import android.os.Binder;
96import android.os.DropBoxManager;
97import android.os.Environment;
98import android.os.Handler;
99import android.os.HandlerThread;
100import android.os.INetworkManagementService;
101import android.os.Message;
102import android.os.PowerManager;
103import android.os.RemoteException;
104import android.os.SystemClock;
105import android.os.UserHandle;
106import android.provider.Settings;
107import android.provider.Settings.Global;
108import android.telephony.PhoneStateListener;
109import android.telephony.TelephonyManager;
110import android.util.EventLog;
111import android.util.Log;
112import android.util.MathUtils;
113import android.util.NtpTrustedTime;
114import android.util.Slog;
115import android.util.SparseIntArray;
116import android.util.TrustedTime;
117
118import com.android.internal.annotations.VisibleForTesting;
119import com.android.internal.util.ArrayUtils;
120import com.android.internal.util.FileRotator;
121import com.android.internal.util.IndentingPrintWriter;
122import com.android.server.EventLogTags;
123import com.android.server.connectivity.Tethering;
124import com.google.android.collect.Maps;
125
126import java.io.File;
127import java.io.FileDescriptor;
128import java.io.IOException;
129import java.io.PrintWriter;
130import java.util.Arrays;
131import java.util.HashMap;
132import java.util.HashSet;
133import java.util.List;
134
135/**
136 * Collect and persist detailed network statistics, and provide this data to
137 * other system services.
138 */
139public class NetworkStatsService extends INetworkStatsService.Stub {
140    private static final String TAG = "NetworkStats";
141    private static final boolean LOGV = false;
142
143    private static final int MSG_PERFORM_POLL = 1;
144    private static final int MSG_UPDATE_IFACES = 2;
145    private static final int MSG_REGISTER_GLOBAL_ALERT = 3;
146
147    /** Flags to control detail level of poll event. */
148    private static final int FLAG_PERSIST_NETWORK = 0x1;
149    private static final int FLAG_PERSIST_UID = 0x2;
150    private static final int FLAG_PERSIST_ALL = FLAG_PERSIST_NETWORK | FLAG_PERSIST_UID;
151    private static final int FLAG_PERSIST_FORCE = 0x100;
152
153    private static final String TAG_NETSTATS_ERROR = "netstats_error";
154
155    private final Context mContext;
156    private final INetworkManagementService mNetworkManager;
157    private final AlarmManager mAlarmManager;
158    private final TrustedTime mTime;
159    private final TelephonyManager mTeleManager;
160    private final NetworkStatsSettings mSettings;
161
162    private final File mSystemDir;
163    private final File mBaseDir;
164
165    private final PowerManager.WakeLock mWakeLock;
166
167    private IConnectivityManager mConnManager;
168
169    @VisibleForTesting
170    public static final String ACTION_NETWORK_STATS_POLL =
171            "com.android.server.action.NETWORK_STATS_POLL";
172    public static final String ACTION_NETWORK_STATS_UPDATED =
173            "com.android.server.action.NETWORK_STATS_UPDATED";
174
175    private PendingIntent mPollIntent;
176
177    private static final String PREFIX_DEV = "dev";
178    private static final String PREFIX_XT = "xt";
179    private static final String PREFIX_UID = "uid";
180    private static final String PREFIX_UID_TAG = "uid_tag";
181
182    /**
183     * Settings that can be changed externally.
184     */
185    public interface NetworkStatsSettings {
186        public long getPollInterval();
187        public long getTimeCacheMaxAge();
188        public boolean getSampleEnabled();
189        public boolean getReportXtOverDev();
190
191        public static class Config {
192            public final long bucketDuration;
193            public final long rotateAgeMillis;
194            public final long deleteAgeMillis;
195
196            public Config(long bucketDuration, long rotateAgeMillis, long deleteAgeMillis) {
197                this.bucketDuration = bucketDuration;
198                this.rotateAgeMillis = rotateAgeMillis;
199                this.deleteAgeMillis = deleteAgeMillis;
200            }
201        }
202
203        public Config getDevConfig();
204        public Config getXtConfig();
205        public Config getUidConfig();
206        public Config getUidTagConfig();
207
208        public long getGlobalAlertBytes(long def);
209        public long getDevPersistBytes(long def);
210        public long getXtPersistBytes(long def);
211        public long getUidPersistBytes(long def);
212        public long getUidTagPersistBytes(long def);
213    }
214
215    private final Object mStatsLock = new Object();
216
217    /** Set of currently active ifaces. */
218    private HashMap<String, NetworkIdentitySet> mActiveIfaces = Maps.newHashMap();
219    /** Current default active iface. */
220    private String mActiveIface;
221    /** Set of any ifaces associated with mobile networks since boot. */
222    private String[] mMobileIfaces = new String[0];
223
224    private final DropBoxNonMonotonicObserver mNonMonotonicObserver =
225            new DropBoxNonMonotonicObserver();
226
227    private NetworkStatsRecorder mDevRecorder;
228    private NetworkStatsRecorder mXtRecorder;
229    private NetworkStatsRecorder mUidRecorder;
230    private NetworkStatsRecorder mUidTagRecorder;
231
232    /** Cached {@link #mDevRecorder} stats. */
233    private NetworkStatsCollection mDevStatsCached;
234    /** Cached {@link #mXtRecorder} stats. */
235    private NetworkStatsCollection mXtStatsCached;
236
237    /** Current counter sets for each UID. */
238    private SparseIntArray mActiveUidCounterSet = new SparseIntArray();
239
240    /** Data layer operation counters for splicing into other structures. */
241    private NetworkStats mUidOperations = new NetworkStats(0L, 10);
242
243    private final Handler mHandler;
244
245    private boolean mSystemReady;
246    private long mPersistThreshold = 2 * MB_IN_BYTES;
247    private long mGlobalAlertBytes;
248
249    public NetworkStatsService(
250            Context context, INetworkManagementService networkManager, IAlarmManager alarmManager) {
251        this(context, networkManager, alarmManager, NtpTrustedTime.getInstance(context),
252                getDefaultSystemDir(), new DefaultNetworkStatsSettings(context));
253    }
254
255    private static File getDefaultSystemDir() {
256        return new File(Environment.getDataDirectory(), "system");
257    }
258
259    public NetworkStatsService(Context context, INetworkManagementService networkManager,
260            IAlarmManager alarmManager, TrustedTime time, File systemDir,
261            NetworkStatsSettings settings) {
262        mContext = checkNotNull(context, "missing Context");
263        mNetworkManager = checkNotNull(networkManager, "missing INetworkManagementService");
264        mTime = checkNotNull(time, "missing TrustedTime");
265        mTeleManager = checkNotNull(TelephonyManager.getDefault(), "missing TelephonyManager");
266        mSettings = checkNotNull(settings, "missing NetworkStatsSettings");
267        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
268
269        final PowerManager powerManager = (PowerManager) context.getSystemService(
270                Context.POWER_SERVICE);
271        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
272
273        HandlerThread thread = new HandlerThread(TAG);
274        thread.start();
275        mHandler = new Handler(thread.getLooper(), mHandlerCallback);
276
277        mSystemDir = checkNotNull(systemDir);
278        mBaseDir = new File(systemDir, "netstats");
279        mBaseDir.mkdirs();
280    }
281
282    public void bindConnectivityManager(IConnectivityManager connManager) {
283        mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
284    }
285
286    public void systemReady() {
287        mSystemReady = true;
288
289        if (!isBandwidthControlEnabled()) {
290            Slog.w(TAG, "bandwidth controls disabled, unable to track stats");
291            return;
292        }
293
294        // create data recorders along with historical rotators
295        mDevRecorder = buildRecorder(PREFIX_DEV, mSettings.getDevConfig(), false);
296        mXtRecorder = buildRecorder(PREFIX_XT, mSettings.getXtConfig(), false);
297        mUidRecorder = buildRecorder(PREFIX_UID, mSettings.getUidConfig(), false);
298        mUidTagRecorder = buildRecorder(PREFIX_UID_TAG, mSettings.getUidTagConfig(), true);
299
300        updatePersistThresholds();
301
302        synchronized (mStatsLock) {
303            // upgrade any legacy stats, migrating them to rotated files
304            maybeUpgradeLegacyStatsLocked();
305
306            // read historical network stats from disk, since policy service
307            // might need them right away.
308            mDevStatsCached = mDevRecorder.getOrLoadCompleteLocked();
309            mXtStatsCached = mXtRecorder.getOrLoadCompleteLocked();
310
311            // bootstrap initial stats to prevent double-counting later
312            bootstrapStatsLocked();
313        }
314
315        // watch for network interfaces to be claimed
316        final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
317        mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
318
319        // watch for tethering changes
320        final IntentFilter tetherFilter = new IntentFilter(ACTION_TETHER_STATE_CHANGED);
321        mContext.registerReceiver(mTetherReceiver, tetherFilter, CONNECTIVITY_INTERNAL, mHandler);
322
323        // listen for periodic polling events
324        final IntentFilter pollFilter = new IntentFilter(ACTION_NETWORK_STATS_POLL);
325        mContext.registerReceiver(mPollReceiver, pollFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
326
327        // listen for uid removal to clean stats
328        final IntentFilter removedFilter = new IntentFilter(ACTION_UID_REMOVED);
329        mContext.registerReceiver(mRemovedReceiver, removedFilter, null, mHandler);
330
331        // listen for user changes to clean stats
332        final IntentFilter userFilter = new IntentFilter(ACTION_USER_REMOVED);
333        mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
334
335        // persist stats during clean shutdown
336        final IntentFilter shutdownFilter = new IntentFilter(ACTION_SHUTDOWN);
337        mContext.registerReceiver(mShutdownReceiver, shutdownFilter);
338
339        try {
340            mNetworkManager.registerObserver(mAlertObserver);
341        } catch (RemoteException e) {
342            // ignored; service lives in system_server
343        }
344
345        // watch for networkType changes that aren't broadcast through
346        // CONNECTIVITY_ACTION_IMMEDIATE above.
347        if (!COMBINE_SUBTYPE_ENABLED) {
348            mTeleManager.listen(mPhoneListener, LISTEN_DATA_CONNECTION_STATE);
349        }
350
351        registerPollAlarmLocked();
352        registerGlobalAlert();
353    }
354
355    private NetworkStatsRecorder buildRecorder(
356            String prefix, NetworkStatsSettings.Config config, boolean includeTags) {
357        final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
358                Context.DROPBOX_SERVICE);
359        return new NetworkStatsRecorder(new FileRotator(
360                mBaseDir, prefix, config.rotateAgeMillis, config.deleteAgeMillis),
361                mNonMonotonicObserver, dropBox, prefix, config.bucketDuration, includeTags);
362    }
363
364    private void shutdownLocked() {
365        mContext.unregisterReceiver(mConnReceiver);
366        mContext.unregisterReceiver(mTetherReceiver);
367        mContext.unregisterReceiver(mPollReceiver);
368        mContext.unregisterReceiver(mRemovedReceiver);
369        mContext.unregisterReceiver(mShutdownReceiver);
370
371        if (!COMBINE_SUBTYPE_ENABLED) {
372            mTeleManager.listen(mPhoneListener, LISTEN_NONE);
373        }
374
375        final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
376                : System.currentTimeMillis();
377
378        // persist any pending stats
379        mDevRecorder.forcePersistLocked(currentTime);
380        mXtRecorder.forcePersistLocked(currentTime);
381        mUidRecorder.forcePersistLocked(currentTime);
382        mUidTagRecorder.forcePersistLocked(currentTime);
383
384        mDevRecorder = null;
385        mXtRecorder = null;
386        mUidRecorder = null;
387        mUidTagRecorder = null;
388
389        mDevStatsCached = null;
390        mXtStatsCached = null;
391
392        mSystemReady = false;
393    }
394
395    private void maybeUpgradeLegacyStatsLocked() {
396        File file;
397        try {
398            file = new File(mSystemDir, "netstats.bin");
399            if (file.exists()) {
400                mDevRecorder.importLegacyNetworkLocked(file);
401                file.delete();
402            }
403
404            file = new File(mSystemDir, "netstats_xt.bin");
405            if (file.exists()) {
406                file.delete();
407            }
408
409            file = new File(mSystemDir, "netstats_uid.bin");
410            if (file.exists()) {
411                mUidRecorder.importLegacyUidLocked(file);
412                mUidTagRecorder.importLegacyUidLocked(file);
413                file.delete();
414            }
415        } catch (IOException e) {
416            Log.wtf(TAG, "problem during legacy upgrade", e);
417        } catch (OutOfMemoryError e) {
418            Log.wtf(TAG, "problem during legacy upgrade", e);
419        }
420    }
421
422    /**
423     * Clear any existing {@link #ACTION_NETWORK_STATS_POLL} alarms, and
424     * reschedule based on current {@link NetworkStatsSettings#getPollInterval()}.
425     */
426    private void registerPollAlarmLocked() {
427        if (mPollIntent != null) {
428            mAlarmManager.cancel(mPollIntent);
429        }
430
431        mPollIntent = PendingIntent.getBroadcast(
432                mContext, 0, new Intent(ACTION_NETWORK_STATS_POLL), 0);
433
434        final long currentRealtime = SystemClock.elapsedRealtime();
435        mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, currentRealtime,
436                mSettings.getPollInterval(), mPollIntent);
437    }
438
439    /**
440     * Register for a global alert that is delivered through
441     * {@link INetworkManagementEventObserver} once a threshold amount of data
442     * has been transferred.
443     */
444    private void registerGlobalAlert() {
445        try {
446            mNetworkManager.setGlobalAlert(mGlobalAlertBytes);
447        } catch (IllegalStateException e) {
448            Slog.w(TAG, "problem registering for global alert: " + e);
449        } catch (RemoteException e) {
450            // ignored; service lives in system_server
451        }
452    }
453
454    @Override
455    public INetworkStatsSession openSession() {
456        mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
457        assertBandwidthControlEnabled();
458
459        // return an IBinder which holds strong references to any loaded stats
460        // for its lifetime; when caller closes only weak references remain.
461
462        return new INetworkStatsSession.Stub() {
463            private NetworkStatsCollection mUidComplete;
464            private NetworkStatsCollection mUidTagComplete;
465
466            private NetworkStatsCollection getUidComplete() {
467                if (mUidComplete == null) {
468                    synchronized (mStatsLock) {
469                        mUidComplete = mUidRecorder.getOrLoadCompleteLocked();
470                    }
471                }
472                return mUidComplete;
473            }
474
475            private NetworkStatsCollection getUidTagComplete() {
476                if (mUidTagComplete == null) {
477                    synchronized (mStatsLock) {
478                        mUidTagComplete = mUidTagRecorder.getOrLoadCompleteLocked();
479                    }
480                }
481                return mUidTagComplete;
482            }
483
484            @Override
485            public NetworkStats getSummaryForNetwork(
486                    NetworkTemplate template, long start, long end) {
487                return internalGetSummaryForNetwork(template, start, end);
488            }
489
490            @Override
491            public NetworkStatsHistory getHistoryForNetwork(NetworkTemplate template, int fields) {
492                return internalGetHistoryForNetwork(template, fields);
493            }
494
495            @Override
496            public NetworkStats getSummaryForAllUid(
497                    NetworkTemplate template, long start, long end, boolean includeTags) {
498                final NetworkStats stats = getUidComplete().getSummary(template, start, end);
499                if (includeTags) {
500                    final NetworkStats tagStats = getUidTagComplete()
501                            .getSummary(template, start, end);
502                    stats.combineAllValues(tagStats);
503                }
504                return stats;
505            }
506
507            @Override
508            public NetworkStatsHistory getHistoryForUid(
509                    NetworkTemplate template, int uid, int set, int tag, int fields) {
510                if (tag == TAG_NONE) {
511                    return getUidComplete().getHistory(template, uid, set, tag, fields);
512                } else {
513                    return getUidTagComplete().getHistory(template, uid, set, tag, fields);
514                }
515            }
516
517            @Override
518            public void close() {
519                mUidComplete = null;
520                mUidTagComplete = null;
521            }
522        };
523    }
524
525    /**
526     * Return network summary, splicing between {@link #mDevStatsCached}
527     * and {@link #mXtStatsCached} when appropriate.
528     */
529    private NetworkStats internalGetSummaryForNetwork(
530            NetworkTemplate template, long start, long end) {
531        if (!mSettings.getReportXtOverDev()) {
532            // shortcut when XT reporting disabled
533            return mDevStatsCached.getSummary(template, start, end);
534        }
535
536        // splice stats between DEV and XT, switching over from DEV to XT at
537        // first atomic bucket.
538        final long firstAtomicBucket = mXtStatsCached.getFirstAtomicBucketMillis();
539        final NetworkStats dev = mDevStatsCached.getSummary(
540                template, Math.min(start, firstAtomicBucket), Math.min(end, firstAtomicBucket));
541        final NetworkStats xt = mXtStatsCached.getSummary(
542                template, Math.max(start, firstAtomicBucket), Math.max(end, firstAtomicBucket));
543
544        xt.combineAllValues(dev);
545        return xt;
546    }
547
548    /**
549     * Return network history, splicing between {@link #mDevStatsCached}
550     * and {@link #mXtStatsCached} when appropriate.
551     */
552    private NetworkStatsHistory internalGetHistoryForNetwork(NetworkTemplate template, int fields) {
553        if (!mSettings.getReportXtOverDev()) {
554            // shortcut when XT reporting disabled
555            return mDevStatsCached.getHistory(template, UID_ALL, SET_ALL, TAG_NONE, fields);
556        }
557
558        // splice stats between DEV and XT, switching over from DEV to XT at
559        // first atomic bucket.
560        final long firstAtomicBucket = mXtStatsCached.getFirstAtomicBucketMillis();
561        final NetworkStatsHistory dev = mDevStatsCached.getHistory(
562                template, UID_ALL, SET_ALL, TAG_NONE, fields, Long.MIN_VALUE, firstAtomicBucket);
563        final NetworkStatsHistory xt = mXtStatsCached.getHistory(
564                template, UID_ALL, SET_ALL, TAG_NONE, fields, firstAtomicBucket, Long.MAX_VALUE);
565
566        xt.recordEntireHistory(dev);
567        return xt;
568    }
569
570    @Override
571    public long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
572        mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
573        assertBandwidthControlEnabled();
574        return internalGetSummaryForNetwork(template, start, end).getTotalBytes();
575    }
576
577    @Override
578    public NetworkStats getDataLayerSnapshotForUid(int uid) throws RemoteException {
579        if (Binder.getCallingUid() != uid) {
580            mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
581        }
582        assertBandwidthControlEnabled();
583
584        // TODO: switch to data layer stats once kernel exports
585        // for now, read network layer stats and flatten across all ifaces
586        final long token = Binder.clearCallingIdentity();
587        final NetworkStats networkLayer;
588        try {
589            networkLayer = mNetworkManager.getNetworkStatsUidDetail(uid);
590        } finally {
591            Binder.restoreCallingIdentity(token);
592        }
593
594        // splice in operation counts
595        networkLayer.spliceOperationsFrom(mUidOperations);
596
597        final NetworkStats dataLayer = new NetworkStats(
598                networkLayer.getElapsedRealtime(), networkLayer.size());
599
600        NetworkStats.Entry entry = null;
601        for (int i = 0; i < networkLayer.size(); i++) {
602            entry = networkLayer.getValues(i, entry);
603            entry.iface = IFACE_ALL;
604            dataLayer.combineValues(entry);
605        }
606
607        return dataLayer;
608    }
609
610    @Override
611    public String[] getMobileIfaces() {
612        return mMobileIfaces;
613    }
614
615    @Override
616    public void incrementOperationCount(int uid, int tag, int operationCount) {
617        if (Binder.getCallingUid() != uid) {
618            mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
619        }
620
621        if (operationCount < 0) {
622            throw new IllegalArgumentException("operation count can only be incremented");
623        }
624        if (tag == TAG_NONE) {
625            throw new IllegalArgumentException("operation count must have specific tag");
626        }
627
628        synchronized (mStatsLock) {
629            final int set = mActiveUidCounterSet.get(uid, SET_DEFAULT);
630            mUidOperations.combineValues(
631                    mActiveIface, uid, set, tag, 0L, 0L, 0L, 0L, operationCount);
632            mUidOperations.combineValues(
633                    mActiveIface, uid, set, TAG_NONE, 0L, 0L, 0L, 0L, operationCount);
634        }
635    }
636
637    @Override
638    public void setUidForeground(int uid, boolean uidForeground) {
639        mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
640
641        synchronized (mStatsLock) {
642            final int set = uidForeground ? SET_FOREGROUND : SET_DEFAULT;
643            final int oldSet = mActiveUidCounterSet.get(uid, SET_DEFAULT);
644            if (oldSet != set) {
645                mActiveUidCounterSet.put(uid, set);
646                setKernelCounterSet(uid, set);
647            }
648        }
649    }
650
651    @Override
652    public void forceUpdate() {
653        mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
654        assertBandwidthControlEnabled();
655
656        final long token = Binder.clearCallingIdentity();
657        try {
658            performPoll(FLAG_PERSIST_ALL);
659        } finally {
660            Binder.restoreCallingIdentity(token);
661        }
662    }
663
664    @Override
665    public void advisePersistThreshold(long thresholdBytes) {
666        mContext.enforceCallingOrSelfPermission(MODIFY_NETWORK_ACCOUNTING, TAG);
667        assertBandwidthControlEnabled();
668
669        // clamp threshold into safe range
670        mPersistThreshold = MathUtils.constrain(thresholdBytes, 128 * KB_IN_BYTES, 2 * MB_IN_BYTES);
671        if (LOGV) {
672            Slog.v(TAG, "advisePersistThreshold() given " + thresholdBytes + ", clamped to "
673                    + mPersistThreshold);
674        }
675
676        // update and persist if beyond new thresholds
677        final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
678                : System.currentTimeMillis();
679        synchronized (mStatsLock) {
680            if (!mSystemReady) return;
681
682            updatePersistThresholds();
683
684            mDevRecorder.maybePersistLocked(currentTime);
685            mXtRecorder.maybePersistLocked(currentTime);
686            mUidRecorder.maybePersistLocked(currentTime);
687            mUidTagRecorder.maybePersistLocked(currentTime);
688        }
689
690        // re-arm global alert
691        registerGlobalAlert();
692    }
693
694    /**
695     * Update {@link NetworkStatsRecorder} and {@link #mGlobalAlertBytes} to
696     * reflect current {@link #mPersistThreshold} value. Always defers to
697     * {@link Global} values when defined.
698     */
699    private void updatePersistThresholds() {
700        mDevRecorder.setPersistThreshold(mSettings.getDevPersistBytes(mPersistThreshold));
701        mXtRecorder.setPersistThreshold(mSettings.getXtPersistBytes(mPersistThreshold));
702        mUidRecorder.setPersistThreshold(mSettings.getUidPersistBytes(mPersistThreshold));
703        mUidTagRecorder.setPersistThreshold(mSettings.getUidTagPersistBytes(mPersistThreshold));
704        mGlobalAlertBytes = mSettings.getGlobalAlertBytes(mPersistThreshold);
705    }
706
707    /**
708     * Receiver that watches for {@link IConnectivityManager} to claim network
709     * interfaces. Used to associate {@link TelephonyManager#getSubscriberId()}
710     * with mobile interfaces.
711     */
712    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
713        @Override
714        public void onReceive(Context context, Intent intent) {
715            // on background handler thread, and verified CONNECTIVITY_INTERNAL
716            // permission above.
717            updateIfaces();
718        }
719    };
720
721    /**
722     * Receiver that watches for {@link Tethering} to claim interface pairs.
723     */
724    private BroadcastReceiver mTetherReceiver = new BroadcastReceiver() {
725        @Override
726        public void onReceive(Context context, Intent intent) {
727            // on background handler thread, and verified CONNECTIVITY_INTERNAL
728            // permission above.
729            performPoll(FLAG_PERSIST_NETWORK);
730        }
731    };
732
733    private BroadcastReceiver mPollReceiver = new BroadcastReceiver() {
734        @Override
735        public void onReceive(Context context, Intent intent) {
736            // on background handler thread, and verified UPDATE_DEVICE_STATS
737            // permission above.
738            performPoll(FLAG_PERSIST_ALL);
739
740            // verify that we're watching global alert
741            registerGlobalAlert();
742        }
743    };
744
745    private BroadcastReceiver mRemovedReceiver = new BroadcastReceiver() {
746        @Override
747        public void onReceive(Context context, Intent intent) {
748            // on background handler thread, and UID_REMOVED is protected
749            // broadcast.
750
751            final int uid = intent.getIntExtra(EXTRA_UID, -1);
752            if (uid == -1) return;
753
754            synchronized (mStatsLock) {
755                mWakeLock.acquire();
756                try {
757                    removeUidsLocked(uid);
758                } finally {
759                    mWakeLock.release();
760                }
761            }
762        }
763    };
764
765    private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
766        @Override
767        public void onReceive(Context context, Intent intent) {
768            // On background handler thread, and USER_REMOVED is protected
769            // broadcast.
770
771            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
772            if (userId == -1) return;
773
774            synchronized (mStatsLock) {
775                mWakeLock.acquire();
776                try {
777                    removeUserLocked(userId);
778                } finally {
779                    mWakeLock.release();
780                }
781            }
782        }
783    };
784
785    private BroadcastReceiver mShutdownReceiver = new BroadcastReceiver() {
786        @Override
787        public void onReceive(Context context, Intent intent) {
788            // SHUTDOWN is protected broadcast.
789            synchronized (mStatsLock) {
790                shutdownLocked();
791            }
792        }
793    };
794
795    /**
796     * Observer that watches for {@link INetworkManagementService} alerts.
797     */
798    private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
799        @Override
800        public void limitReached(String limitName, String iface) {
801            // only someone like NMS should be calling us
802            mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
803
804            if (LIMIT_GLOBAL_ALERT.equals(limitName)) {
805                // kick off background poll to collect network stats; UID stats
806                // are handled during normal polling interval.
807                final int flags = FLAG_PERSIST_NETWORK;
808                mHandler.obtainMessage(MSG_PERFORM_POLL, flags, 0).sendToTarget();
809
810                // re-arm global alert for next update
811                mHandler.obtainMessage(MSG_REGISTER_GLOBAL_ALERT).sendToTarget();
812            }
813        }
814    };
815
816    private int mLastPhoneState = TelephonyManager.DATA_UNKNOWN;
817    private int mLastPhoneNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
818
819    /**
820     * Receiver that watches for {@link TelephonyManager} changes, such as
821     * transitioning between network types.
822     */
823    private PhoneStateListener mPhoneListener = new PhoneStateListener() {
824        @Override
825        public void onDataConnectionStateChanged(int state, int networkType) {
826            final boolean stateChanged = state != mLastPhoneState;
827            final boolean networkTypeChanged = networkType != mLastPhoneNetworkType;
828
829            if (networkTypeChanged && !stateChanged) {
830                // networkType changed without a state change, which means we
831                // need to roll our own update. delay long enough for
832                // ConnectivityManager to process.
833                // TODO: add direct event to ConnectivityService instead of
834                // relying on this delay.
835                if (LOGV) Slog.v(TAG, "triggering delayed updateIfaces()");
836                mHandler.sendMessageDelayed(
837                        mHandler.obtainMessage(MSG_UPDATE_IFACES), SECOND_IN_MILLIS);
838            }
839
840            mLastPhoneState = state;
841            mLastPhoneNetworkType = networkType;
842        }
843    };
844
845    private void updateIfaces() {
846        synchronized (mStatsLock) {
847            mWakeLock.acquire();
848            try {
849                updateIfacesLocked();
850            } finally {
851                mWakeLock.release();
852            }
853        }
854    }
855
856    /**
857     * Inspect all current {@link NetworkState} to derive mapping from {@code
858     * iface} to {@link NetworkStatsHistory}. When multiple {@link NetworkInfo}
859     * are active on a single {@code iface}, they are combined under a single
860     * {@link NetworkIdentitySet}.
861     */
862    private void updateIfacesLocked() {
863        if (!mSystemReady) return;
864        if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
865
866        // take one last stats snapshot before updating iface mapping. this
867        // isn't perfect, since the kernel may already be counting traffic from
868        // the updated network.
869
870        // poll, but only persist network stats to keep codepath fast. UID stats
871        // will be persisted during next alarm poll event.
872        performPollLocked(FLAG_PERSIST_NETWORK);
873
874        final NetworkState[] states;
875        final LinkProperties activeLink;
876        try {
877            states = mConnManager.getAllNetworkState();
878            activeLink = mConnManager.getActiveLinkProperties();
879        } catch (RemoteException e) {
880            // ignored; service lives in system_server
881            return;
882        }
883
884        mActiveIface = activeLink != null ? activeLink.getInterfaceName() : null;
885
886        // rebuild active interfaces based on connected networks
887        mActiveIfaces.clear();
888
889        for (NetworkState state : states) {
890            if (state.networkInfo.isConnected()) {
891                // collect networks under their parent interfaces
892                final String iface = state.linkProperties.getInterfaceName();
893
894                NetworkIdentitySet ident = mActiveIfaces.get(iface);
895                if (ident == null) {
896                    ident = new NetworkIdentitySet();
897                    mActiveIfaces.put(iface, ident);
898                }
899
900                ident.add(NetworkIdentity.buildNetworkIdentity(mContext, state));
901
902                // remember any ifaces associated with mobile networks
903                if (isNetworkTypeMobile(state.networkInfo.getType()) && iface != null) {
904                    if (!contains(mMobileIfaces, iface)) {
905                        mMobileIfaces = appendElement(String.class, mMobileIfaces, iface);
906                    }
907                }
908            }
909        }
910    }
911
912    /**
913     * Bootstrap initial stats snapshot, usually during {@link #systemReady()}
914     * so we have baseline values without double-counting.
915     */
916    private void bootstrapStatsLocked() {
917        final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
918                : System.currentTimeMillis();
919
920        try {
921            // snapshot and record current counters; read UID stats first to
922            // avoid overcounting dev stats.
923            final NetworkStats uidSnapshot = getNetworkStatsUidDetail();
924            final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
925            final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
926
927            mDevRecorder.recordSnapshotLocked(devSnapshot, mActiveIfaces, currentTime);
928            mXtRecorder.recordSnapshotLocked(xtSnapshot, mActiveIfaces, currentTime);
929            mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
930            mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
931
932        } catch (IllegalStateException e) {
933            Slog.w(TAG, "problem reading network stats: " + e);
934        } catch (RemoteException e) {
935            // ignored; service lives in system_server
936        }
937    }
938
939    private void performPoll(int flags) {
940        // try refreshing time source when stale
941        if (mTime.getCacheAge() > mSettings.getTimeCacheMaxAge()) {
942            mTime.forceRefresh();
943        }
944
945        synchronized (mStatsLock) {
946            mWakeLock.acquire();
947
948            try {
949                performPollLocked(flags);
950            } finally {
951                mWakeLock.release();
952            }
953        }
954    }
955
956    /**
957     * Periodic poll operation, reading current statistics and recording into
958     * {@link NetworkStatsHistory}.
959     */
960    private void performPollLocked(int flags) {
961        if (!mSystemReady) return;
962        if (LOGV) Slog.v(TAG, "performPollLocked(flags=0x" + Integer.toHexString(flags) + ")");
963
964        final long startRealtime = SystemClock.elapsedRealtime();
965
966        final boolean persistNetwork = (flags & FLAG_PERSIST_NETWORK) != 0;
967        final boolean persistUid = (flags & FLAG_PERSIST_UID) != 0;
968        final boolean persistForce = (flags & FLAG_PERSIST_FORCE) != 0;
969
970        // TODO: consider marking "untrusted" times in historical stats
971        final long currentTime = mTime.hasCache() ? mTime.currentTimeMillis()
972                : System.currentTimeMillis();
973
974        try {
975            // snapshot and record current counters; read UID stats first to
976            // avoid overcounting dev stats.
977            final NetworkStats uidSnapshot = getNetworkStatsUidDetail();
978            final NetworkStats xtSnapshot = mNetworkManager.getNetworkStatsSummaryXt();
979            final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
980
981            mDevRecorder.recordSnapshotLocked(devSnapshot, mActiveIfaces, currentTime);
982            mXtRecorder.recordSnapshotLocked(xtSnapshot, mActiveIfaces, currentTime);
983            mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
984            mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveIfaces, currentTime);
985
986        } catch (IllegalStateException e) {
987            Log.wtf(TAG, "problem reading network stats", e);
988            return;
989        } catch (RemoteException e) {
990            // ignored; service lives in system_server
991            return;
992        }
993
994        // persist any pending data depending on requested flags
995        if (persistForce) {
996            mDevRecorder.forcePersistLocked(currentTime);
997            mXtRecorder.forcePersistLocked(currentTime);
998            mUidRecorder.forcePersistLocked(currentTime);
999            mUidTagRecorder.forcePersistLocked(currentTime);
1000        } else {
1001            if (persistNetwork) {
1002                mDevRecorder.maybePersistLocked(currentTime);
1003                mXtRecorder.maybePersistLocked(currentTime);
1004            }
1005            if (persistUid) {
1006                mUidRecorder.maybePersistLocked(currentTime);
1007                mUidTagRecorder.maybePersistLocked(currentTime);
1008            }
1009        }
1010
1011        if (LOGV) {
1012            final long duration = SystemClock.elapsedRealtime() - startRealtime;
1013            Slog.v(TAG, "performPollLocked() took " + duration + "ms");
1014        }
1015
1016        if (mSettings.getSampleEnabled()) {
1017            // sample stats after each full poll
1018            performSampleLocked();
1019        }
1020
1021        // finally, dispatch updated event to any listeners
1022        final Intent updatedIntent = new Intent(ACTION_NETWORK_STATS_UPDATED);
1023        updatedIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1024        mContext.sendBroadcastAsUser(updatedIntent, UserHandle.ALL,
1025                READ_NETWORK_USAGE_HISTORY);
1026    }
1027
1028    /**
1029     * Sample recent statistics summary into {@link EventLog}.
1030     */
1031    private void performSampleLocked() {
1032        // TODO: migrate trustedtime fixes to separate binary log events
1033        final long trustedTime = mTime.hasCache() ? mTime.currentTimeMillis() : -1;
1034
1035        NetworkTemplate template;
1036        NetworkStats.Entry devTotal;
1037        NetworkStats.Entry xtTotal;
1038        NetworkStats.Entry uidTotal;
1039
1040        // collect mobile sample
1041        template = buildTemplateMobileWildcard();
1042        devTotal = mDevRecorder.getTotalSinceBootLocked(template);
1043        xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
1044        uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
1045
1046        EventLogTags.writeNetstatsMobileSample(
1047                devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1048                xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1049                uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
1050                trustedTime);
1051
1052        // collect wifi sample
1053        template = buildTemplateWifiWildcard();
1054        devTotal = mDevRecorder.getTotalSinceBootLocked(template);
1055        xtTotal = mXtRecorder.getTotalSinceBootLocked(template);
1056        uidTotal = mUidRecorder.getTotalSinceBootLocked(template);
1057
1058        EventLogTags.writeNetstatsWifiSample(
1059                devTotal.rxBytes, devTotal.rxPackets, devTotal.txBytes, devTotal.txPackets,
1060                xtTotal.rxBytes, xtTotal.rxPackets, xtTotal.txBytes, xtTotal.txPackets,
1061                uidTotal.rxBytes, uidTotal.rxPackets, uidTotal.txBytes, uidTotal.txPackets,
1062                trustedTime);
1063    }
1064
1065    /**
1066     * Clean up {@link #mUidRecorder} after UID is removed.
1067     */
1068    private void removeUidsLocked(int... uids) {
1069        if (LOGV) Slog.v(TAG, "removeUidsLocked() for UIDs " + Arrays.toString(uids));
1070
1071        // Perform one last poll before removing
1072        performPollLocked(FLAG_PERSIST_ALL);
1073
1074        mUidRecorder.removeUidsLocked(uids);
1075        mUidTagRecorder.removeUidsLocked(uids);
1076
1077        // Clear kernel stats associated with UID
1078        for (int uid : uids) {
1079            resetKernelUidStats(uid);
1080        }
1081    }
1082
1083    /**
1084     * Clean up {@link #mUidRecorder} after user is removed.
1085     */
1086    private void removeUserLocked(int userId) {
1087        if (LOGV) Slog.v(TAG, "removeUserLocked() for userId=" + userId);
1088
1089        // Build list of UIDs that we should clean up
1090        int[] uids = new int[0];
1091        final List<ApplicationInfo> apps = mContext.getPackageManager().getInstalledApplications(
1092                PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1093        for (ApplicationInfo app : apps) {
1094            final int uid = UserHandle.getUid(userId, app.uid);
1095            uids = ArrayUtils.appendInt(uids, uid);
1096        }
1097
1098        removeUidsLocked(uids);
1099    }
1100
1101    @Override
1102    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1103        mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1104
1105        final HashSet<String> argSet = new HashSet<String>();
1106        for (String arg : args) {
1107            argSet.add(arg);
1108        }
1109
1110        // usage: dumpsys netstats --full --uid --tag --poll --checkin
1111        final boolean poll = argSet.contains("--poll") || argSet.contains("poll");
1112        final boolean checkin = argSet.contains("--checkin");
1113        final boolean fullHistory = argSet.contains("--full") || argSet.contains("full");
1114        final boolean includeUid = argSet.contains("--uid") || argSet.contains("detail");
1115        final boolean includeTag = argSet.contains("--tag") || argSet.contains("detail");
1116
1117        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1118
1119        synchronized (mStatsLock) {
1120            if (poll) {
1121                performPollLocked(FLAG_PERSIST_ALL | FLAG_PERSIST_FORCE);
1122                pw.println("Forced poll");
1123                return;
1124            }
1125
1126            if (checkin) {
1127                // list current stats files to verify rotation
1128                pw.println("Current files:");
1129                pw.increaseIndent();
1130                for (String file : mBaseDir.list()) {
1131                    pw.println(file);
1132                }
1133                pw.decreaseIndent();
1134                return;
1135            }
1136
1137            pw.println("Active interfaces:");
1138            pw.increaseIndent();
1139            for (String iface : mActiveIfaces.keySet()) {
1140                final NetworkIdentitySet ident = mActiveIfaces.get(iface);
1141                pw.print("iface="); pw.print(iface);
1142                pw.print(" ident="); pw.println(ident.toString());
1143            }
1144            pw.decreaseIndent();
1145
1146            pw.println("Dev stats:");
1147            pw.increaseIndent();
1148            mDevRecorder.dumpLocked(pw, fullHistory);
1149            pw.decreaseIndent();
1150
1151            pw.println("Xt stats:");
1152            pw.increaseIndent();
1153            mXtRecorder.dumpLocked(pw, fullHistory);
1154            pw.decreaseIndent();
1155
1156            if (includeUid) {
1157                pw.println("UID stats:");
1158                pw.increaseIndent();
1159                mUidRecorder.dumpLocked(pw, fullHistory);
1160                pw.decreaseIndent();
1161            }
1162
1163            if (includeTag) {
1164                pw.println("UID tag stats:");
1165                pw.increaseIndent();
1166                mUidTagRecorder.dumpLocked(pw, fullHistory);
1167                pw.decreaseIndent();
1168            }
1169        }
1170    }
1171
1172    /**
1173     * Return snapshot of current UID statistics, including any
1174     * {@link TrafficStats#UID_TETHERING} and {@link #mUidOperations} values.
1175     */
1176    private NetworkStats getNetworkStatsUidDetail() throws RemoteException {
1177        final NetworkStats uidSnapshot = mNetworkManager.getNetworkStatsUidDetail(UID_ALL);
1178
1179        // fold tethering stats and operations into uid snapshot
1180        final NetworkStats tetherSnapshot = getNetworkStatsTethering();
1181        uidSnapshot.combineAllValues(tetherSnapshot);
1182        uidSnapshot.combineAllValues(mUidOperations);
1183
1184        return uidSnapshot;
1185    }
1186
1187    /**
1188     * Return snapshot of current tethering statistics. Will return empty
1189     * {@link NetworkStats} if any problems are encountered.
1190     */
1191    private NetworkStats getNetworkStatsTethering() throws RemoteException {
1192        try {
1193            return mNetworkManager.getNetworkStatsTethering();
1194        } catch (IllegalStateException e) {
1195            Log.wtf(TAG, "problem reading network stats", e);
1196            return new NetworkStats(0L, 10);
1197        }
1198    }
1199
1200    private Handler.Callback mHandlerCallback = new Handler.Callback() {
1201        @Override
1202        public boolean handleMessage(Message msg) {
1203            switch (msg.what) {
1204                case MSG_PERFORM_POLL: {
1205                    final int flags = msg.arg1;
1206                    performPoll(flags);
1207                    return true;
1208                }
1209                case MSG_UPDATE_IFACES: {
1210                    updateIfaces();
1211                    return true;
1212                }
1213                case MSG_REGISTER_GLOBAL_ALERT: {
1214                    registerGlobalAlert();
1215                    return true;
1216                }
1217                default: {
1218                    return false;
1219                }
1220            }
1221        }
1222    };
1223
1224    private void assertBandwidthControlEnabled() {
1225        if (!isBandwidthControlEnabled()) {
1226            throw new IllegalStateException("Bandwidth module disabled");
1227        }
1228    }
1229
1230    private boolean isBandwidthControlEnabled() {
1231        final long token = Binder.clearCallingIdentity();
1232        try {
1233            return mNetworkManager.isBandwidthControlEnabled();
1234        } catch (RemoteException e) {
1235            // ignored; service lives in system_server
1236            return false;
1237        } finally {
1238            Binder.restoreCallingIdentity(token);
1239        }
1240    }
1241
1242    private class DropBoxNonMonotonicObserver implements NonMonotonicObserver<String> {
1243        @Override
1244        public void foundNonMonotonic(NetworkStats left, int leftIndex, NetworkStats right,
1245                int rightIndex, String cookie) {
1246            Log.w(TAG, "found non-monotonic values; saving to dropbox");
1247
1248            // record error for debugging
1249            final StringBuilder builder = new StringBuilder();
1250            builder.append("found non-monotonic " + cookie + " values at left[" + leftIndex
1251                    + "] - right[" + rightIndex + "]\n");
1252            builder.append("left=").append(left).append('\n');
1253            builder.append("right=").append(right).append('\n');
1254
1255            final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
1256                    Context.DROPBOX_SERVICE);
1257            dropBox.addText(TAG_NETSTATS_ERROR, builder.toString());
1258        }
1259    }
1260
1261    /**
1262     * Default external settings that read from
1263     * {@link android.provider.Settings.Global}.
1264     */
1265    private static class DefaultNetworkStatsSettings implements NetworkStatsSettings {
1266        private final ContentResolver mResolver;
1267
1268        public DefaultNetworkStatsSettings(Context context) {
1269            mResolver = checkNotNull(context.getContentResolver());
1270            // TODO: adjust these timings for production builds
1271        }
1272
1273        private long getGlobalLong(String name, long def) {
1274            return Settings.Global.getLong(mResolver, name, def);
1275        }
1276        private boolean getGlobalBoolean(String name, boolean def) {
1277            final int defInt = def ? 1 : 0;
1278            return Settings.Global.getInt(mResolver, name, defInt) != 0;
1279        }
1280
1281        @Override
1282        public long getPollInterval() {
1283            return getGlobalLong(NETSTATS_POLL_INTERVAL, 30 * MINUTE_IN_MILLIS);
1284        }
1285        @Override
1286        public long getTimeCacheMaxAge() {
1287            return getGlobalLong(NETSTATS_TIME_CACHE_MAX_AGE, DAY_IN_MILLIS);
1288        }
1289        @Override
1290        public long getGlobalAlertBytes(long def) {
1291            return getGlobalLong(NETSTATS_GLOBAL_ALERT_BYTES, def);
1292        }
1293        @Override
1294        public boolean getSampleEnabled() {
1295            return getGlobalBoolean(NETSTATS_SAMPLE_ENABLED, true);
1296        }
1297        @Override
1298        public boolean getReportXtOverDev() {
1299            return getGlobalBoolean(NETSTATS_REPORT_XT_OVER_DEV, true);
1300        }
1301        @Override
1302        public Config getDevConfig() {
1303            return new Config(getGlobalLong(NETSTATS_DEV_BUCKET_DURATION, HOUR_IN_MILLIS),
1304                    getGlobalLong(NETSTATS_DEV_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1305                    getGlobalLong(NETSTATS_DEV_DELETE_AGE, 90 * DAY_IN_MILLIS));
1306        }
1307        @Override
1308        public Config getXtConfig() {
1309            return getDevConfig();
1310        }
1311        @Override
1312        public Config getUidConfig() {
1313            return new Config(getGlobalLong(NETSTATS_UID_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1314                    getGlobalLong(NETSTATS_UID_ROTATE_AGE, 15 * DAY_IN_MILLIS),
1315                    getGlobalLong(NETSTATS_UID_DELETE_AGE, 90 * DAY_IN_MILLIS));
1316        }
1317        @Override
1318        public Config getUidTagConfig() {
1319            return new Config(getGlobalLong(NETSTATS_UID_TAG_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
1320                    getGlobalLong(NETSTATS_UID_TAG_ROTATE_AGE, 5 * DAY_IN_MILLIS),
1321                    getGlobalLong(NETSTATS_UID_TAG_DELETE_AGE, 15 * DAY_IN_MILLIS));
1322        }
1323        @Override
1324        public long getDevPersistBytes(long def) {
1325            return getGlobalLong(NETSTATS_DEV_PERSIST_BYTES, def);
1326        }
1327        @Override
1328        public long getXtPersistBytes(long def) {
1329            return getDevPersistBytes(def);
1330        }
1331        @Override
1332        public long getUidPersistBytes(long def) {
1333            return getGlobalLong(NETSTATS_UID_PERSIST_BYTES, def);
1334        }
1335        @Override
1336        public long getUidTagPersistBytes(long def) {
1337            return getGlobalLong(NETSTATS_UID_TAG_PERSIST_BYTES, def);
1338        }
1339    }
1340}
1341