use of android.net.NetworkStats in project android_frameworks_base by ResurrectionRemix.
the class NetworkStatsObserversTest method testUpdateStats_deviceAccess_notifies.
public void testUpdateStats_deviceAccess_notifies() throws Exception {
DataUsageRequest inputRequest = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET, sTemplateImsi1, THRESHOLD_BYTES);
DataUsageRequest request = mStatsObservers.register(inputRequest, mMessenger, mockBinder, Process.SYSTEM_UID, NetworkStatsAccess.Level.DEVICE);
assertTrue(request.requestId > 0);
assertTrue(Objects.equals(sTemplateImsi1, request.template));
assertEquals(THRESHOLD_BYTES, request.thresholdInBytes);
NetworkIdentitySet identSet = new NetworkIdentitySet();
identSet.add(new NetworkIdentity(TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, IMSI_1, null, /* networkId */
false, /* roaming */
true));
mActiveIfaces.put(TEST_IFACE, identSet);
// Baseline
NetworkStats xtSnapshot = new NetworkStats(TEST_START, 1).addIfaceValues(TEST_IFACE, BASE_BYTES, 8L, BASE_BYTES, 16L);
NetworkStats uidSnapshot = null;
mStatsObservers.updateStats(xtSnapshot, uidSnapshot, mActiveIfaces, mActiveUidIfaces, VPN_INFO, TEST_START);
// Delta
xtSnapshot = new NetworkStats(TEST_START + MINUTE_IN_MILLIS, 1).addIfaceValues(TEST_IFACE, BASE_BYTES + THRESHOLD_BYTES, 12L, BASE_BYTES + THRESHOLD_BYTES, 22L);
mStatsObservers.updateStats(xtSnapshot, uidSnapshot, mActiveIfaces, mActiveUidIfaces, VPN_INFO, TEST_START);
waitForObserverToIdle();
assertTrue(mCv.block(WAIT_TIMEOUT));
assertEquals(NetworkStatsManager.CALLBACK_LIMIT_REACHED, mHandler.mLastMessageType);
}
use of android.net.NetworkStats in project android_frameworks_base by ResurrectionRemix.
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;
}
};
}
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;
}
use of android.net.NetworkStats in project android_frameworks_base by ResurrectionRemix.
the class NetworkStatsServiceTest method testRegisterUsageCallback.
public void testRegisterUsageCallback() throws Exception {
// pretend that wifi network comes online; service should ask about full
// network state, and poll any existing interfaces before updating.
expectCurrentTime();
expectDefaultSettings();
expectNetworkState(buildWifiState());
expectNetworkStatsSummary(buildEmptyStats());
expectNetworkStatsUidDetail(buildEmptyStats());
expectNetworkStatsPoll();
expectBandwidthControlCheck();
replay();
mService.forceUpdateIfaces();
// verify service has empty history for wifi
assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
verifyAndReset();
String callingPackage = "the.calling.package";
// very small; should be overriden by framework
long thresholdInBytes = 1L;
DataUsageRequest inputRequest = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET, sTemplateWifi, thresholdInBytes);
// Create a messenger that waits for callback activity
ConditionVariable cv = new ConditionVariable(false);
LatchedHandler latchedHandler = new LatchedHandler(Looper.getMainLooper(), cv);
Messenger messenger = new Messenger(latchedHandler);
// Allow binder to connect
IBinder mockBinder = createMock(IBinder.class);
mockBinder.linkToDeath((IBinder.DeathRecipient) anyObject(), anyInt());
EasyMock.replay(mockBinder);
// Force poll
expectCurrentTime();
expectDefaultSettings();
expectNetworkStatsSummary(buildEmptyStats());
expectNetworkStatsUidDetail(buildEmptyStats());
expectNetworkStatsPoll();
replay();
// Register and verify request and that binder was called
DataUsageRequest request = mService.registerUsageCallback(callingPackage, inputRequest, messenger, mockBinder);
assertTrue(request.requestId > 0);
assertTrue(Objects.equals(sTemplateWifi, request.template));
// 2 MB
long minThresholdInBytes = 2 * 1024 * 1024;
assertEquals(minThresholdInBytes, request.thresholdInBytes);
// Send dummy message to make sure that any previous message has been handled
mHandler.sendMessage(mHandler.obtainMessage(-1));
mHandlerThread.waitForIdle(WAIT_TIMEOUT);
verifyAndReset();
// Make sure that the caller binder gets connected
EasyMock.verify(mockBinder);
EasyMock.reset(mockBinder);
// modify some number on wifi, and trigger poll event
// not enough traffic to call data usage callback
incrementCurrentTime(HOUR_IN_MILLIS);
expectCurrentTime();
expectDefaultSettings();
expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 1024L, 1L, 2048L, 2L));
expectNetworkStatsUidDetail(buildEmptyStats());
expectNetworkStatsPoll();
replay();
forcePollAndWaitForIdle();
// verify service recorded history
verifyAndReset();
assertNetworkTotal(sTemplateWifi, 1024L, 1L, 2048L, 2L, 0);
// make sure callback has not being called
assertEquals(INVALID_TYPE, latchedHandler.mLastMessageType);
// and bump forward again, with counters going higher. this is
// important, since it will trigger the data usage callback
incrementCurrentTime(DAY_IN_MILLIS);
expectCurrentTime();
expectDefaultSettings();
expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 4096000L, 4L, 8192000L, 8L));
expectNetworkStatsUidDetail(buildEmptyStats());
expectNetworkStatsPoll();
replay();
forcePollAndWaitForIdle();
// verify service recorded history
assertNetworkTotal(sTemplateWifi, 4096000L, 4L, 8192000L, 8L, 0);
verifyAndReset();
// Wait for the caller to ack receipt of CALLBACK_LIMIT_REACHED
assertTrue(cv.block(WAIT_TIMEOUT));
assertEquals(NetworkStatsManager.CALLBACK_LIMIT_REACHED, latchedHandler.mLastMessageType);
cv.close();
// Allow binder to disconnect
expect(mockBinder.unlinkToDeath((IBinder.DeathRecipient) anyObject(), anyInt())).andReturn(true);
EasyMock.replay(mockBinder);
// Unregister request
mService.unregisterUsageRequest(request);
// Wait for the caller to ack receipt of CALLBACK_RELEASED
assertTrue(cv.block(WAIT_TIMEOUT));
assertEquals(NetworkStatsManager.CALLBACK_RELEASED, latchedHandler.mLastMessageType);
// Make sure that the caller binder gets disconnected
EasyMock.verify(mockBinder);
}
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);
}
}
Aggregations