Search in sources :

Example 86 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class NetworkStatsService method getDataLayerSnapshotForUid.

@Override
public NetworkStats getDataLayerSnapshotForUid(int uid) throws RemoteException {
    if (Binder.getCallingUid() != uid) {
        mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
    }
    assertBandwidthControlEnabled();
    // TODO: switch to data layer stats once kernel exports
    // for now, read network layer stats and flatten across all ifaces
    final long token = Binder.clearCallingIdentity();
    final NetworkStats networkLayer;
    try {
        networkLayer = mNetworkManager.getNetworkStatsUidDetail(uid);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
    // splice in operation counts
    networkLayer.spliceOperationsFrom(mUidOperations);
    final NetworkStats dataLayer = new NetworkStats(networkLayer.getElapsedRealtime(), networkLayer.size());
    NetworkStats.Entry entry = null;
    for (int i = 0; i < networkLayer.size(); i++) {
        entry = networkLayer.getValues(i, entry);
        entry.iface = IFACE_ALL;
        dataLayer.combineValues(entry);
    }
    return dataLayer;
}
Also used : NetworkStats(android.net.NetworkStats)

Example 87 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class NetworkStatsService method createSession.

private INetworkStatsSession createSession(final String callingPackage, boolean pollOnCreate) {
    assertBandwidthControlEnabled();
    if (pollOnCreate) {
        final long ident = Binder.clearCallingIdentity();
        try {
            performPoll(FLAG_PERSIST_ALL);
        } finally {
            Binder.restoreCallingIdentity(ident);
        }
    }
    return new INetworkStatsSession.Stub() {

        private NetworkStatsCollection mUidComplete;

        private NetworkStatsCollection mUidTagComplete;

        private String mCallingPackage = callingPackage;

        private NetworkStatsCollection getUidComplete() {
            synchronized (mStatsLock) {
                if (mUidComplete == null) {
                    mUidComplete = mUidRecorder.getOrLoadCompleteLocked();
                }
                return mUidComplete;
            }
        }

        private NetworkStatsCollection getUidTagComplete() {
            synchronized (mStatsLock) {
                if (mUidTagComplete == null) {
                    mUidTagComplete = mUidTagRecorder.getOrLoadCompleteLocked();
                }
                return mUidTagComplete;
            }
        }

        @Override
        public int[] getRelevantUids() {
            return getUidComplete().getRelevantUids(checkAccessLevel(mCallingPackage));
        }

        @Override
        public NetworkStats getDeviceSummaryForNetwork(NetworkTemplate template, long start, long end) {
            @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(mCallingPackage);
            if (accessLevel < NetworkStatsAccess.Level.DEVICESUMMARY) {
                throw new SecurityException("Calling package " + mCallingPackage + " cannot access device summary network stats");
            }
            NetworkStats result = new NetworkStats(end - start, 1);
            final long ident = Binder.clearCallingIdentity();
            try {
                // Using access level higher than the one we checked for above.
                // Reason is that we are combining usage data in a way that is not PII
                // anymore.
                result.combineAllValues(internalGetSummaryForNetwork(template, start, end, NetworkStatsAccess.Level.DEVICE));
            } finally {
                Binder.restoreCallingIdentity(ident);
            }
            return result;
        }

        @Override
        public NetworkStats getSummaryForNetwork(NetworkTemplate template, long start, long end) {
            @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(mCallingPackage);
            return internalGetSummaryForNetwork(template, start, end, accessLevel);
        }

        @Override
        public NetworkStatsHistory getHistoryForNetwork(NetworkTemplate template, int fields) {
            @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(mCallingPackage);
            return internalGetHistoryForNetwork(template, fields, accessLevel);
        }

        @Override
        public NetworkStats getSummaryForAllUid(NetworkTemplate template, long start, long end, boolean includeTags) {
            @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(mCallingPackage);
            final NetworkStats stats = getUidComplete().getSummary(template, start, end, accessLevel);
            if (includeTags) {
                final NetworkStats tagStats = getUidTagComplete().getSummary(template, start, end, accessLevel);
                stats.combineAllValues(tagStats);
            }
            return stats;
        }

        @Override
        public NetworkStatsHistory getHistoryForUid(NetworkTemplate template, int uid, int set, int tag, int fields) {
            @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(mCallingPackage);
            if (tag == TAG_NONE) {
                return getUidComplete().getHistory(template, uid, set, tag, fields, accessLevel);
            } else {
                return getUidTagComplete().getHistory(template, uid, set, tag, fields, accessLevel);
            }
        }

        @Override
        public NetworkStatsHistory getHistoryIntervalForUid(NetworkTemplate template, int uid, int set, int tag, int fields, long start, long end) {
            @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(mCallingPackage);
            if (tag == TAG_NONE) {
                return getUidComplete().getHistory(template, uid, set, tag, fields, start, end, accessLevel);
            } else if (uid == Binder.getCallingUid()) {
                return getUidTagComplete().getHistory(template, uid, set, tag, fields, start, end, accessLevel);
            } else {
                throw new SecurityException("Calling package " + mCallingPackage + " cannot access tag information from a different uid");
            }
        }

        @Override
        public void close() {
            mUidComplete = null;
            mUidTagComplete = null;
        }
    };
}
Also used : NetworkTemplate(android.net.NetworkTemplate) NetworkStats(android.net.NetworkStats)

Example 88 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class NetworkStatsService method recordSnapshotLocked.

private void recordSnapshotLocked(long currentTime) throws RemoteException {
    // snapshot and record current counters; read UID stats first to
    // avoid over counting dev stats.
    final NetworkStats uidSnapshot = getNetworkStatsUidDetail();
    final NetworkStats xtSnapshot = getNetworkStatsXtAndVt();
    final NetworkStats devSnapshot = mNetworkManager.getNetworkStatsSummaryDev();
    // For xt/dev, we pass a null VPN array because usage is aggregated by UID, so VPN traffic
    // can't be reattributed to responsible apps.
    mDevRecorder.recordSnapshotLocked(devSnapshot, mActiveIfaces, null, /* vpnArray */
    currentTime);
    mXtRecorder.recordSnapshotLocked(xtSnapshot, mActiveIfaces, null, /* vpnArray */
    currentTime);
    // For per-UID stats, pass the VPN info so VPN traffic is reattributed to responsible apps.
    VpnInfo[] vpnArray = mConnManager.getAllVpnInfo();
    mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
    mUidTagRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
    // We need to make copies of member fields that are sent to the observer to avoid
    // a race condition between the service handler thread and the observer's
    mStatsObservers.updateStats(xtSnapshot, uidSnapshot, new ArrayMap<>(mActiveIfaces), new ArrayMap<>(mActiveUidIfaces), vpnArray, currentTime);
}
Also used : VpnInfo(com.android.internal.net.VpnInfo) NetworkStats(android.net.NetworkStats)

Example 89 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class NetworkStatsCollection method getSummary.

/**
     * Summarize all {@link NetworkStatsHistory} in this collection which match
     * the requested parameters.
     */
public NetworkStats getSummary(NetworkTemplate template, long start, long end, @NetworkStatsAccess.Level int accessLevel, int callerUid) {
    final long now = System.currentTimeMillis();
    final NetworkStats stats = new NetworkStats(end - start, 24);
    // shortcut when we know stats will be empty
    if (start == end)
        return stats;
    final NetworkStats.Entry entry = new NetworkStats.Entry();
    NetworkStatsHistory.Entry historyEntry = null;
    for (int i = 0; i < mStats.size(); i++) {
        final Key key = mStats.keyAt(i);
        if (templateMatches(template, key.ident) && NetworkStatsAccess.isAccessibleToUser(key.uid, callerUid, accessLevel) && key.set < NetworkStats.SET_DEBUG_START) {
            final NetworkStatsHistory value = mStats.valueAt(i);
            historyEntry = value.getValues(start, end, now, historyEntry);
            entry.iface = IFACE_ALL;
            entry.uid = key.uid;
            entry.set = key.set;
            entry.tag = key.tag;
            entry.roaming = key.ident.isAnyMemberRoaming() ? ROAMING_YES : ROAMING_NO;
            entry.rxBytes = historyEntry.rxBytes;
            entry.rxPackets = historyEntry.rxPackets;
            entry.txBytes = historyEntry.txBytes;
            entry.txPackets = historyEntry.txPackets;
            entry.operations = historyEntry.operations;
            if (!entry.isEmpty()) {
                stats.combineValues(entry);
            }
        }
    }
    return stats;
}
Also used : NetworkStats(android.net.NetworkStats) NetworkStatsHistory(android.net.NetworkStatsHistory)

Example 90 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class NetworkPolicyManagerServiceTest method testOverWarningLimitNotification.

@Suppress
public void testOverWarningLimitNotification() throws Exception {
    NetworkState[] state = null;
    NetworkStats stats = null;
    Future<Void> future;
    Future<String> tagFuture;
    final long TIME_FEB_15 = 1171497600000L;
    final long TIME_MAR_10 = 1173484800000L;
    final int CYCLE_DAY = 15;
    setCurrentTimeMillis(TIME_MAR_10);
    // assign wifi policy
    state = new NetworkState[] {};
    stats = new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
    {
        expectCurrentTime();
        expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
        expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis())).andReturn(stats.getTotalBytes()).atLeastOnce();
        expectPolicyDataEnable(TYPE_WIFI, true);
        expectClearNotifications();
        expectAdvisePersistThreshold();
        future = expectMeteredIfacesChanged();
        replay();
        setNetworkPolicies(new NetworkPolicy(sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
        future.get();
        verifyAndReset();
    }
    // bring up wifi network
    incrementCurrentTime(MINUTE_IN_MILLIS);
    state = new NetworkState[] { buildWifi() };
    stats = new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
    {
        expectCurrentTime();
        expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
        expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis())).andReturn(stats.getTotalBytes()).atLeastOnce();
        expectPolicyDataEnable(TYPE_WIFI, true);
        expectRemoveInterfaceQuota(TEST_IFACE);
        expectSetInterfaceQuota(TEST_IFACE, 2 * MB_IN_BYTES);
        expectClearNotifications();
        expectAdvisePersistThreshold();
        future = expectMeteredIfacesChanged(TEST_IFACE);
        replay();
        mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
        future.get();
        verifyAndReset();
    }
    // go over warning, which should kick notification
    incrementCurrentTime(MINUTE_IN_MILLIS);
    stats = new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 1536 * KB_IN_BYTES, 15L, 0L, 0L);
    {
        expectCurrentTime();
        expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis())).andReturn(stats.getTotalBytes()).atLeastOnce();
        expectPolicyDataEnable(TYPE_WIFI, true);
        expectForceUpdate();
        expectClearNotifications();
        tagFuture = expectEnqueueNotification();
        replay();
        mNetworkObserver.limitReached(null, TEST_IFACE);
        assertNotificationType(TYPE_WARNING, tagFuture.get());
        verifyAndReset();
    }
    // go over limit, which should kick notification and dialog
    incrementCurrentTime(MINUTE_IN_MILLIS);
    stats = new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 5 * MB_IN_BYTES, 512L, 0L, 0L);
    {
        expectCurrentTime();
        expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis())).andReturn(stats.getTotalBytes()).atLeastOnce();
        expectPolicyDataEnable(TYPE_WIFI, false);
        expectForceUpdate();
        expectClearNotifications();
        tagFuture = expectEnqueueNotification();
        replay();
        mNetworkObserver.limitReached(null, TEST_IFACE);
        assertNotificationType(TYPE_LIMIT, tagFuture.get());
        verifyAndReset();
    }
    // now snooze policy, which should remove quota
    incrementCurrentTime(MINUTE_IN_MILLIS);
    {
        expectCurrentTime();
        expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
        expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis())).andReturn(stats.getTotalBytes()).atLeastOnce();
        expectPolicyDataEnable(TYPE_WIFI, true);
        // snoozed interface still has high quota so background data is
        // still restricted.
        expectRemoveInterfaceQuota(TEST_IFACE);
        expectSetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
        expectAdvisePersistThreshold();
        expectMeteredIfacesChanged(TEST_IFACE);
        future = expectClearNotifications();
        tagFuture = expectEnqueueNotification();
        replay();
        mService.snoozeLimit(sTemplateWifi);
        assertNotificationType(TYPE_LIMIT_SNOOZED, tagFuture.get());
        future.get();
        verifyAndReset();
    }
}
Also used : NetworkPolicy(android.net.NetworkPolicy) NetworkStats(android.net.NetworkStats) Intent(android.content.Intent) NetworkState(android.net.NetworkState) Suppress(android.test.suitebuilder.annotation.Suppress)

Aggregations

NetworkStats (android.net.NetworkStats)271 File (java.io.File)49 DataUsageRequest (android.net.DataUsageRequest)32 Intent (android.content.Intent)29 NetworkIdentity (android.net.NetworkIdentity)28 NetworkStatsHistory (android.net.NetworkStatsHistory)21 Bundle (android.os.Bundle)18 StrictMode (android.os.StrictMode)18 ProcFileReader (com.android.internal.util.ProcFileReader)18 FileInputStream (java.io.FileInputStream)18 ProtocolException (java.net.ProtocolException)18 PendingIntent (android.app.PendingIntent)17 IOException (java.io.IOException)17 NetworkPolicy (android.net.NetworkPolicy)15 NetworkState (android.net.NetworkState)15 Test (org.junit.Test)14 Suppress (android.test.suitebuilder.annotation.Suppress)13 VpnInfo (com.android.internal.net.VpnInfo)10 RemoteException (android.os.RemoteException)8 NetworkTemplate (android.net.NetworkTemplate)6