use of android.net.NetworkIdentity in project android_frameworks_base by crdroidandroid.
the class NetworkStatsObserversTest method testUpdateStats_userAccess_usageSameUser_notifies.
public void testUpdateStats_userAccess_usageSameUser_notifies() throws Exception {
DataUsageRequest inputRequest = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET, sTemplateImsi1, THRESHOLD_BYTES);
DataUsageRequest request = mStatsObservers.register(inputRequest, mMessenger, mockBinder, UID_BLUE, NetworkStatsAccess.Level.USER);
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));
mActiveUidIfaces.put(TEST_IFACE, identSet);
// Baseline
NetworkStats xtSnapshot = null;
NetworkStats uidSnapshot = new NetworkStats(TEST_START, 2).addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, ROAMING_NO, BASE_BYTES, 2L, BASE_BYTES, 2L, 0L);
mStatsObservers.updateStats(xtSnapshot, uidSnapshot, mActiveIfaces, mActiveUidIfaces, VPN_INFO, TEST_START);
// Delta
uidSnapshot = new NetworkStats(TEST_START + 2 * MINUTE_IN_MILLIS, 2).addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, ROAMING_NO, BASE_BYTES + THRESHOLD_BYTES, 2L, BASE_BYTES + THRESHOLD_BYTES, 2L, 0L);
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.NetworkIdentity in project android_frameworks_base by ParanoidAndroid.
the class NetworkPolicyManagerService method updateNetworkRulesLocked.
/**
* Examine all connected {@link NetworkState}, looking for
* {@link NetworkPolicy} that need to be enforced. When matches found, set
* remaining quota based on usage cycle and historical stats.
*/
private void updateNetworkRulesLocked() {
if (LOGV)
Slog.v(TAG, "updateIfacesLocked()");
final NetworkState[] states;
try {
states = mConnManager.getAllNetworkState();
} catch (RemoteException e) {
// ignored; service lives in system_server
return;
}
// first, derive identity for all connected networks, which can be used
// to match against templates.
final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
for (NetworkState state : states) {
// stash identity and iface away for later use
if (state.networkInfo.isConnected()) {
final String iface = state.linkProperties.getInterfaceName();
final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
networks.put(ident, iface);
}
}
// build list of rules and ifaces to enforce them against
mNetworkRules.clear();
final ArrayList<String> ifaceList = Lists.newArrayList();
for (NetworkPolicy policy : mNetworkPolicy.values()) {
// collect all active ifaces that match this template
ifaceList.clear();
for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
final NetworkIdentity ident = entry.getKey();
if (policy.template.matches(ident)) {
final String iface = entry.getValue();
ifaceList.add(iface);
}
}
if (ifaceList.size() > 0) {
final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
mNetworkRules.put(policy, ifaces);
}
}
long lowestRule = Long.MAX_VALUE;
final HashSet<String> newMeteredIfaces = Sets.newHashSet();
// apply each policy that we found ifaces for; compute remaining data
// based on current cycle and historical stats, and push to kernel.
final long currentTime = currentTimeMillis();
for (NetworkPolicy policy : mNetworkRules.keySet()) {
final String[] ifaces = mNetworkRules.get(policy);
final long start;
final long totalBytes;
if (policy.hasCycle()) {
start = computeLastCycleBoundary(currentTime, policy);
totalBytes = getTotalBytes(policy.template, start, currentTime);
} else {
start = Long.MAX_VALUE;
totalBytes = 0;
}
if (LOGD) {
Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces " + Arrays.toString(ifaces));
}
final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
if (hasLimit || policy.metered) {
final long quotaBytes;
if (!hasLimit) {
// metered network, but no policy limit; we still need to
// restrict apps, so push really high quota.
quotaBytes = Long.MAX_VALUE;
} else if (policy.lastLimitSnooze >= start) {
// snoozing past quota, but we still need to restrict apps,
// so push really high quota.
quotaBytes = Long.MAX_VALUE;
} else {
// remaining "quota" bytes are based on total usage in
// current cycle. kernel doesn't like 0-byte rules, so we
// set 1-byte quota and disable the radio later.
quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
}
if (ifaces.length > 1) {
// TODO: switch to shared quota once NMS supports
Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
}
for (String iface : ifaces) {
removeInterfaceQuota(iface);
setInterfaceQuota(iface, quotaBytes);
newMeteredIfaces.add(iface);
}
}
// keep track of lowest warning or limit of active policies
if (hasWarning && policy.warningBytes < lowestRule) {
lowestRule = policy.warningBytes;
}
if (hasLimit && policy.limitBytes < lowestRule) {
lowestRule = policy.limitBytes;
}
}
mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
// remove quota on any trailing interfaces
for (String iface : mMeteredIfaces) {
if (!newMeteredIfaces.contains(iface)) {
removeInterfaceQuota(iface);
}
}
mMeteredIfaces = newMeteredIfaces;
final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
}
use of android.net.NetworkIdentity in project android_frameworks_base by ParanoidAndroid.
the class NetworkPolicyManagerService method getNetworkQuotaInfoUnchecked.
private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
final NetworkPolicy policy;
synchronized (mRulesLock) {
policy = findPolicyForNetworkLocked(ident);
}
if (policy == null || !policy.hasCycle()) {
// missing policy means we can't derive useful quota info
return null;
}
final long currentTime = currentTimeMillis();
// find total bytes used under policy
final long start = computeLastCycleBoundary(currentTime, policy);
final long end = currentTime;
final long totalBytes = getTotalBytes(policy.template, start, end);
// report soft and hard limits under policy
final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes : NetworkQuotaInfo.NO_LIMIT;
final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes : NetworkQuotaInfo.NO_LIMIT;
return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
}
use of android.net.NetworkIdentity in project android_frameworks_base by ParanoidAndroid.
the class NetworkPolicyManagerService method ensureActiveMobilePolicyLocked.
/**
* Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
* have at least a default mobile policy defined.
*/
private void ensureActiveMobilePolicyLocked() {
if (LOGV)
Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
if (mSuppressDefaultPolicy)
return;
final TelephonyManager tele = TelephonyManager.from(mContext);
// avoid creating policy when SIM isn't ready
if (tele.getSimState() != SIM_STATE_READY)
return;
final String subscriberId = tele.getSubscriberId();
final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
// examine to see if any policy is defined for active mobile
boolean mobileDefined = false;
for (NetworkPolicy policy : mNetworkPolicy.values()) {
if (policy.template.matches(probeIdent)) {
mobileDefined = true;
}
}
if (!mobileDefined) {
Slog.i(TAG, "no policy for active mobile network; generating default policy");
// build default mobile policy, and assume usage cycle starts today
final long warningBytes = mContext.getResources().getInteger(com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
final Time time = new Time();
time.setToNow();
final int cycleDay = time.monthDay;
final String cycleTimezone = time.timezone;
final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone, warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
addNetworkPolicyLocked(policy);
}
}
use of android.net.NetworkIdentity in project platform_frameworks_base by android.
the class NetworkStatsObserversTest method testUpdateStats_initialSample_doesNotNotify.
public void testUpdateStats_initialSample_doesNotNotify() 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);
waitForObserverToIdle();
assertTrue(mCv.block(WAIT_TIMEOUT));
assertEquals(INVALID_TYPE, mHandler.mLastMessageType);
}
Aggregations