Search in sources :

Example 41 with NetworkStats

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

the class BandwidthTest method uploadFile.

/**
     * Helper method that downloads a test file to upload. The stats reported to instrumentation out
     * only include upload stats.
     */
protected void uploadFile() throws Exception {
    // Download a file from the server.
    String ts = Long.toString(System.currentTimeMillis());
    String targetUrl = BandwidthTestUtil.buildDownloadUrl(mTestServer, FILE_SIZE, mDeviceId, ts);
    File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME);
    assertTrue(BandwidthTestUtil.DownloadFromUrl(targetUrl, tmpSaveFile));
    ts = Long.toString(System.currentTimeMillis());
    NetworkStats pre_test_stats = fetchDataFromProc(mUid);
    TrafficStats.startDataProfiling(mContext);
    assertTrue(BandwidthTestUtil.postFileToServer(mTestServer, mDeviceId, ts, tmpSaveFile));
    NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext);
    Log.d(LOG_TAG, prof_stats.toString());
    NetworkStats post_test_stats = fetchDataFromProc(mUid);
    NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats);
    // Output measurements to instrumentation out, so that it can be compared to that of
    // the server.
    Bundle results = new Bundle();
    results.putString("device_id", mDeviceId);
    results.putString("timestamp", ts);
    results.putInt("size", FILE_SIZE);
    addStatsToResults(PROF_LABEL, prof_stats, results, mUid);
    addStatsToResults(PROC_LABEL, proc_stats, results, mUid);
    getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results);
    // Clean up.
    assertTrue(cleanUpFile(tmpSaveFile));
}
Also used : Bundle(android.os.Bundle) NetworkStats(android.net.NetworkStats) File(java.io.File)

Example 42 with NetworkStats

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

the class BandwidthTest method fetchDataFromProc.

/**
     * Fetch network data from /proc/uid_stat/uid
     *
     * @return populated {@link NetworkStats}
     */
public NetworkStats fetchDataFromProc(int uid) {
    String root_filepath = "/proc/uid_stat/" + uid + "/";
    File rcv_stat = new File(root_filepath + "tcp_rcv");
    int rx = BandwidthTestUtil.parseIntValueFromFile(rcv_stat);
    File snd_stat = new File(root_filepath + "tcp_snd");
    int tx = BandwidthTestUtil.parseIntValueFromFile(snd_stat);
    NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
    stats.addValues(NetworkStats.IFACE_ALL, uid, NetworkStats.SET_DEFAULT, NetworkStats.TAG_NONE, rx, 0, tx, 0, 0);
    return stats;
}
Also used : NetworkStats(android.net.NetworkStats) File(java.io.File)

Example 43 with NetworkStats

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

the class NetworkManagementService method getNetworkStatsTethering.

@Override
public NetworkStats getNetworkStatsTethering() {
    mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
    final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
    try {
        final NativeDaemonEvent[] events = mConnector.executeForList("bandwidth", "gettetherstats");
        for (NativeDaemonEvent event : events) {
            if (event.getCode() != TetheringStatsListResult)
                continue;
            // 114 ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets
            final StringTokenizer tok = new StringTokenizer(event.getMessage());
            try {
                final String ifaceIn = tok.nextToken();
                final String ifaceOut = tok.nextToken();
                final NetworkStats.Entry entry = new NetworkStats.Entry();
                entry.iface = ifaceOut;
                entry.uid = UID_TETHERING;
                entry.set = SET_DEFAULT;
                entry.tag = TAG_NONE;
                entry.rxBytes = Long.parseLong(tok.nextToken());
                entry.rxPackets = Long.parseLong(tok.nextToken());
                entry.txBytes = Long.parseLong(tok.nextToken());
                entry.txPackets = Long.parseLong(tok.nextToken());
                stats.combineValues(entry);
            } catch (NoSuchElementException e) {
                throw new IllegalStateException("problem parsing tethering stats: " + event);
            } catch (NumberFormatException e) {
                throw new IllegalStateException("problem parsing tethering stats: " + event);
            }
        }
    } catch (NativeDaemonConnectorException e) {
        throw e.rethrowAsParcelableException();
    }
    return stats;
}
Also used : StringTokenizer(java.util.StringTokenizer) NetworkStats(android.net.NetworkStats) NoSuchElementException(java.util.NoSuchElementException)

Example 44 with NetworkStats

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

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)

Example 45 with NetworkStats

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

the class NetworkPolicyManagerServiceTest method testNetworkPolicyAppliedCycleLastMonth.

@Suppress
public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
    NetworkState[] state = null;
    NetworkStats stats = null;
    Future<Void> future;
    final long TIME_FEB_15 = 1171497600000L;
    final long TIME_MAR_10 = 1173484800000L;
    final int CYCLE_DAY = 15;
    setCurrentTimeMillis(TIME_MAR_10);
    // first, pretend that wifi network comes online. no policy active,
    // which means we shouldn't push limit to interface.
    state = new NetworkState[] { buildWifi() };
    expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
    expectCurrentTime();
    expectClearNotifications();
    expectAdvisePersistThreshold();
    future = expectMeteredIfacesChanged();
    replay();
    mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
    future.get();
    verifyAndReset();
    // now change cycle to be on 15th, and test in early march, to verify we
    // pick cycle day in previous month.
    expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
    expectCurrentTime();
    // pretend that 512 bytes total have happened
    stats = new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
    expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, TIME_MAR_10)).andReturn(stats.getTotalBytes()).atLeastOnce();
    expectPolicyDataEnable(TYPE_WIFI, true);
    // TODO: consider making strongly ordered mock
    expectRemoveInterfaceQuota(TEST_IFACE);
    expectSetInterfaceQuota(TEST_IFACE, (2 * MB_IN_BYTES) - 512);
    expectClearNotifications();
    expectAdvisePersistThreshold();
    future = expectMeteredIfacesChanged(TEST_IFACE);
    replay();
    setNetworkPolicies(new NetworkPolicy(sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
    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