Search in sources :

Example 91 with NetworkStats

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

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 92 with NetworkStats

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

the class BandwidthTestCase method runTest.

@Override
protected void runTest() throws Throwable {
    //This is a copy of {@link InstrumentationTestCase#runTest} with
    //added logic to handle bandwidth measurements
    String fName = getName();
    assertNotNull(fName);
    Method method = null;
    Class testClass = null;
    try {
        // use getMethod to get all public inherited
        // methods. getDeclaredMethods returns all
        // methods of this class but excludes the
        // inherited ones.
        testClass = getClass();
        method = testClass.getMethod(fName, (Class[]) null);
    } catch (NoSuchMethodException e) {
        fail("Method \"" + fName + "\" not found");
    }
    if (!Modifier.isPublic(method.getModifiers())) {
        fail("Method \"" + fName + "\" should be public");
    }
    int runCount = 1;
    boolean isRepetitive = false;
    if (method.isAnnotationPresent(FlakyTest.class)) {
        runCount = method.getAnnotation(FlakyTest.class).tolerance();
    } else if (method.isAnnotationPresent(RepetitiveTest.class)) {
        runCount = method.getAnnotation(RepetitiveTest.class).numIterations();
        isRepetitive = true;
    }
    if (method.isAnnotationPresent(UiThreadTest.class)) {
        final int tolerance = runCount;
        final boolean repetitive = isRepetitive;
        final Method testMethod = method;
        final Throwable[] exceptions = new Throwable[1];
        getInstrumentation().runOnMainSync(new Runnable() {

            public void run() {
                try {
                    runMethod(testMethod, tolerance, repetitive);
                } catch (Throwable throwable) {
                    exceptions[0] = throwable;
                }
            }
        });
        if (exceptions[0] != null) {
            throw exceptions[0];
        }
    } else if (method.isAnnotationPresent(BandwidthTest.class) || testClass.isAnnotationPresent(BandwidthTest.class)) {
        /**
             * If bandwidth profiling fails for whatever reason the test
             * should be allow to execute to its completion.
             * Typically bandwidth profiling would fail when a lower level
             * component is missing, such as the kernel module, for a newly
             * introduced hardware.
             */
        try {
            TrafficStats.startDataProfiling(null);
        } catch (IllegalStateException isx) {
            Log.w(TAG, "Failed to start bandwidth profiling");
        }
        runMethod(method, 1, false);
        try {
            NetworkStats stats = TrafficStats.stopDataProfiling(null);
            NetworkStats.Entry entry = stats.getTotal(null);
            getInstrumentation().sendStatus(2, getBandwidthStats(entry));
        } catch (IllegalStateException isx) {
            Log.w(TAG, "Failed to collect bandwidth stats");
        }
    } else {
        runMethod(method, runCount, isRepetitive);
    }
}
Also used : NetworkStats(android.net.NetworkStats) Method(java.lang.reflect.Method)

Example 93 with NetworkStats

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

the class BatteryStatsImpl method updateMobileRadioStateLocked.

/**
     * Distribute Cell radio energy info and network traffic to apps.
     */
public void updateMobileRadioStateLocked(final long elapsedRealtimeMs, final ModemActivityInfo activityInfo) {
    if (DEBUG_ENERGY) {
        Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
    }
    NetworkStats delta = null;
    try {
        if (!ArrayUtils.isEmpty(mMobileIfaces)) {
            delta = getNetworkStatsDeltaLocked(mMobileIfaces, mMobileNetworkStats);
        }
    } catch (IOException e) {
        Slog.wtf(TAG, "Failed to get mobile network stats", e);
        return;
    }
    if (!mOnBatteryInternal) {
        return;
    }
    long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(elapsedRealtimeMs * 1000);
    mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
    long totalRxPackets = 0;
    long totalTxPackets = 0;
    if (delta != null) {
        final int size = delta.size();
        for (int i = 0; i < size; i++) {
            final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry);
            if (entry.rxPackets == 0 && entry.txPackets == 0) {
                continue;
            }
            if (DEBUG_ENERGY) {
                Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets + " txPackets=" + entry.txPackets);
            }
            totalRxPackets += entry.rxPackets;
            totalTxPackets += entry.txPackets;
            final Uid u = getUidStatsLocked(mapUid(entry.uid));
            u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes, entry.rxPackets);
            u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes, entry.txPackets);
            mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(entry.rxBytes);
            mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(entry.txBytes);
            mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(entry.rxPackets);
            mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(entry.txPackets);
        }
        // Now distribute proportional blame to the apps that did networking.
        long totalPackets = totalRxPackets + totalTxPackets;
        if (totalPackets > 0) {
            for (int i = 0; i < size; i++) {
                final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry);
                if (entry.rxPackets == 0 && entry.txPackets == 0) {
                    continue;
                }
                final Uid u = getUidStatsLocked(mapUid(entry.uid));
                // Distribute total radio active time in to this app.
                final long appPackets = entry.rxPackets + entry.txPackets;
                final long appRadioTime = (radioTime * appPackets) / totalPackets;
                u.noteMobileRadioActiveTimeLocked(appRadioTime);
                // Remove this app from the totals, so that we don't lose any time
                // due to rounding.
                radioTime -= appRadioTime;
                totalPackets -= appPackets;
                if (activityInfo != null) {
                    ControllerActivityCounterImpl activityCounter = u.getOrCreateModemControllerActivityLocked();
                    if (totalRxPackets > 0 && entry.rxPackets > 0) {
                        final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis()) / totalRxPackets;
                        activityCounter.getRxTimeCounter().addCountLocked(rxMs);
                    }
                    if (totalTxPackets > 0 && entry.txPackets > 0) {
                        for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
                            long txMs = entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
                            txMs /= totalTxPackets;
                            activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
                        }
                    }
                }
            }
        }
        if (radioTime > 0) {
            // Whoops, there is some radio time we can't blame on an app!
            mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
            mMobileRadioActiveUnknownCount.addCountLocked(1);
        }
    }
    if (activityInfo != null) {
        mHasModemReporting = true;
        mModemActivity.getIdleTimeCounter().addCountLocked(activityInfo.getIdleTimeMillis());
        mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
        for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
            mModemActivity.getTxTimeCounters()[lvl].addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
        }
        // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
        final double opVolt = mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
        if (opVolt != 0) {
            // We store the power drain as mAms.
            mModemActivity.getPowerCounter().addCountLocked((long) (activityInfo.getEnergyUsed() / opVolt));
        }
    }
}
Also used : NetworkStats(android.net.NetworkStats) IOException(java.io.IOException)

Example 94 with NetworkStats

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

the class BatteryStatsImpl method updateWifiStateLocked.

/**
     * Distribute WiFi energy info and network traffic to apps.
     * @param info The energy information from the WiFi controller.
     */
public void updateWifiStateLocked(@Nullable final WifiActivityEnergyInfo info) {
    if (DEBUG_ENERGY) {
        Slog.d(TAG, "Updating wifi stats");
    }
    final long elapsedRealtimeMs = mClocks.elapsedRealtime();
    NetworkStats delta = null;
    try {
        if (!ArrayUtils.isEmpty(mWifiIfaces)) {
            delta = getNetworkStatsDeltaLocked(mWifiIfaces, mWifiNetworkStats);
        }
    } catch (IOException e) {
        Slog.wtf(TAG, "Failed to get wifi network stats", e);
        return;
    }
    if (!mOnBatteryInternal) {
        return;
    }
    SparseLongArray rxPackets = new SparseLongArray();
    SparseLongArray txPackets = new SparseLongArray();
    long totalTxPackets = 0;
    long totalRxPackets = 0;
    if (delta != null) {
        final int size = delta.size();
        for (int i = 0; i < size; i++) {
            final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry);
            if (DEBUG_ENERGY) {
                Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets + " txPackets=" + entry.txPackets);
            }
            if (entry.rxBytes == 0 && entry.txBytes == 0) {
                // Skip the lookup below since there is no work to do.
                continue;
            }
            final Uid u = getUidStatsLocked(mapUid(entry.uid));
            if (entry.rxBytes != 0) {
                u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes, entry.rxPackets);
                mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(entry.rxBytes);
                mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(entry.rxPackets);
                rxPackets.put(u.getUid(), entry.rxPackets);
                // Sum the total number of packets so that the Rx Power can
                // be evenly distributed amongst the apps.
                totalRxPackets += entry.rxPackets;
            }
            if (entry.txBytes != 0) {
                u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes, entry.txPackets);
                mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(entry.txBytes);
                mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(entry.txPackets);
                txPackets.put(u.getUid(), entry.txPackets);
                // Sum the total number of packets so that the Tx Power can
                // be evenly distributed amongst the apps.
                totalTxPackets += entry.txPackets;
            }
        }
    }
    if (info != null) {
        mHasWifiReporting = true;
        // Measured in mAms
        final long txTimeMs = info.getControllerTxTimeMillis();
        final long rxTimeMs = info.getControllerRxTimeMillis();
        final long idleTimeMs = info.getControllerIdleTimeMillis();
        final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
        long leftOverRxTimeMs = rxTimeMs;
        long leftOverTxTimeMs = txTimeMs;
        if (DEBUG_ENERGY) {
            Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
            Slog.d(TAG, "  Tx Time:    " + txTimeMs + " ms");
            Slog.d(TAG, "  Rx Time:    " + rxTimeMs + " ms");
            Slog.d(TAG, "  Idle Time:  " + idleTimeMs + " ms");
            Slog.d(TAG, "  Total Time: " + totalTimeMs + " ms");
        }
        long totalWifiLockTimeMs = 0;
        long totalScanTimeMs = 0;
        // On the first pass, collect some totals so that we can normalize power
        // calculations if we need to.
        final int uidStatsSize = mUidStats.size();
        for (int i = 0; i < uidStatsSize; i++) {
            final Uid uid = mUidStats.valueAt(i);
            // Sum the total scan power for all apps.
            totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(elapsedRealtimeMs * 1000) / 1000;
            // Sum the total time holding wifi lock for all apps.
            totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(elapsedRealtimeMs * 1000) / 1000;
        }
        if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
            Slog.d(TAG, "  !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > " + rxTimeMs + " ms). Normalizing scan time.");
        }
        if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
            Slog.d(TAG, "  !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > " + txTimeMs + " ms). Normalizing scan time.");
        }
        // Actually assign and distribute power usage to apps.
        for (int i = 0; i < uidStatsSize; i++) {
            final Uid uid = mUidStats.valueAt(i);
            long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(elapsedRealtimeMs * 1000) / 1000;
            if (scanTimeSinceMarkMs > 0) {
                // Set the new mark so that next time we get new data since this point.
                uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
                long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
                long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
                // blamed for this, but this is fine as scans are relatively more expensive.
                if (totalScanTimeMs > rxTimeMs) {
                    scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) / totalScanTimeMs;
                }
                if (totalScanTimeMs > txTimeMs) {
                    scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) / totalScanTimeMs;
                }
                if (DEBUG_ENERGY) {
                    Slog.d(TAG, "  ScanTime for UID " + uid.getUid() + ": Rx:" + scanRxTimeSinceMarkMs + " ms  Tx:" + scanTxTimeSinceMarkMs + " ms)");
                }
                ControllerActivityCounterImpl activityCounter = uid.getOrCreateWifiControllerActivityLocked();
                activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
                activityCounter.getTxTimeCounters()[0].addCountLocked(scanTxTimeSinceMarkMs);
                leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
                leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
            }
            // Distribute evenly the power consumed while Idle to each app holding a WiFi
            // lock.
            final long wifiLockTimeSinceMarkMs = uid.mFullWifiLockTimer.getTimeSinceMarkLocked(elapsedRealtimeMs * 1000) / 1000;
            if (wifiLockTimeSinceMarkMs > 0) {
                // Set the new mark so that next time we get new data since this point.
                uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
                final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs) / totalWifiLockTimeMs;
                if (DEBUG_ENERGY) {
                    Slog.d(TAG, "  IdleTime for UID " + uid.getUid() + ": " + myIdleTimeMs + " ms");
                }
                uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter().addCountLocked(myIdleTimeMs);
            }
        }
        if (DEBUG_ENERGY) {
            Slog.d(TAG, "  New RxPower: " + leftOverRxTimeMs + " ms");
            Slog.d(TAG, "  New TxPower: " + leftOverTxTimeMs + " ms");
        }
        // packets.
        for (int i = 0; i < txPackets.size(); i++) {
            final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
            final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs) / totalTxPackets;
            if (DEBUG_ENERGY) {
                Slog.d(TAG, "  TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
            }
            uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0].addCountLocked(myTxTimeMs);
        }
        // packets.
        for (int i = 0; i < rxPackets.size(); i++) {
            final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
            final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs) / totalRxPackets;
            if (DEBUG_ENERGY) {
                Slog.d(TAG, "  RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
            }
            uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter().addCountLocked(myRxTimeMs);
        }
        // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
        // Update WiFi controller stats.
        mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
        mWifiActivity.getTxTimeCounters()[0].addCountLocked(info.getControllerTxTimeMillis());
        mWifiActivity.getIdleTimeCounter().addCountLocked(info.getControllerIdleTimeMillis());
        // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
        final double opVolt = mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
        if (opVolt != 0) {
            // We store the power drain as mAms.
            mWifiActivity.getPowerCounter().addCountLocked((long) (info.getControllerEnergyUsed() / opVolt));
        }
    }
}
Also used : NetworkStats(android.net.NetworkStats) IOException(java.io.IOException) SparseLongArray(android.util.SparseLongArray)

Example 95 with NetworkStats

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

the class BatteryStatsImpl method init.

private void init(Clocks clocks) {
    mClocks = clocks;
    mMobileNetworkStats = new NetworkStats[] { new NetworkStats(mClocks.elapsedRealtime(), 50), new NetworkStats(mClocks.elapsedRealtime(), 50), new NetworkStats(mClocks.elapsedRealtime(), 50) };
    mWifiNetworkStats = new NetworkStats[] { new NetworkStats(mClocks.elapsedRealtime(), 50), new NetworkStats(mClocks.elapsedRealtime(), 50), new NetworkStats(mClocks.elapsedRealtime(), 50) };
}
Also used : NetworkStats(android.net.NetworkStats)

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