From b8b282e54eb0932bc10430388d2cb52486248d78 Mon Sep 17 00:00:00 2001 From: lesl Date: Thu, 28 Jan 2021 15:58:23 +0800 Subject: [PATCH 1/2] carrier data usage: Use carrier template as default policy The carrier network means any network which linked with sepcific subscriberId (for instances: merged Wifi or mobile). Update default policy to use carrier network template to replace mobile template. No impact for current AOSP user because no any wifi network is merged wifi. (Because the merged wifi network requires to support from the wifi module). Also this change convert all of the old policies which template is TYEP_MOBILE to TYPE_CARRIER to match the default policy. Bug: 176396812 Test: atest -c NetworkPolicyManagerServiceTest Test: atest -c CtsHostsideNetworkTests Test: Manual Test with test code (Force wifi to merged wifi). The data will limit when using merged wifi. And mobile policy also work normally. Merged-In: I33c10f7549e713c52ce9afd5b8c4cce2abbda616 Change-Id: I33c10f7549e713c52ce9afd5b8c4cce2abbda616 --- core/java/android/net/NetworkTemplate.java | 4 + .../net/NetworkPolicyManagerService.java | 122 ++++++++++++------ .../netpolicy/network-policy-mobile.xml | 6 + ...-match-rule-all-and-templateMetered-no.xml | 5 + .../net/NetworkPolicyManagerServiceTest.java | 96 +++++++++----- 5 files changed, 163 insertions(+), 70 deletions(-) create mode 100644 services/tests/servicestests/assets/NetworkPolicyManagerServiceTest/netpolicy/network-policy-mobile.xml create mode 100644 services/tests/servicestests/assets/NetworkPolicyManagerServiceTest/netpolicy/network-policy-wifi-with-subscriberId-match-rule-all-and-templateMetered-no.xml diff --git a/core/java/android/net/NetworkTemplate.java b/core/java/android/net/NetworkTemplate.java index fd446cdf5c7fc..249154aa9129d 100644 --- a/core/java/android/net/NetworkTemplate.java +++ b/core/java/android/net/NetworkTemplate.java @@ -514,6 +514,10 @@ public class NetworkTemplate implements Parcelable { return mSubscriberIdMatchRule; } + public int getMeteredness() { + return mMetered; + } + /** * Test if given {@link NetworkIdentity} matches this template. */ diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java index 8c1fd3693d06e..cfd575080d972 100644 --- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java +++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java @@ -99,8 +99,12 @@ import static android.net.NetworkPolicyManager.resolveNetworkId; import static android.net.NetworkPolicyManager.uidPoliciesToString; import static android.net.NetworkPolicyManager.uidRulesToString; import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK; +import static android.net.NetworkStats.METERED_ALL; +import static android.net.NetworkStats.METERED_YES; +import static android.net.NetworkTemplate.MATCH_CARRIER; import static android.net.NetworkTemplate.MATCH_MOBILE; import static android.net.NetworkTemplate.MATCH_WIFI; +import static android.net.NetworkTemplate.buildTemplateCarrierMetered; import static android.net.NetworkTemplate.buildTemplateMobileAll; import static android.net.TrafficStats.MB_IN_BYTES; import static android.net.netstats.provider.NetworkStatsProvider.QUOTA_UNLIMITED; @@ -349,7 +353,8 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { private static final int VERSION_SWITCH_UID = 10; private static final int VERSION_ADDED_CYCLE = 11; private static final int VERSION_ADDED_NETWORK_TYPES = 12; - private static final int VERSION_LATEST = VERSION_ADDED_NETWORK_TYPES; + private static final int VERSION_SUPPORTED_CARRIER_USAGE = 13; + private static final int VERSION_LATEST = VERSION_SUPPORTED_CARRIER_USAGE; @VisibleForTesting public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING; @@ -374,7 +379,9 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground"; private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate"; private static final String ATTR_SUBSCRIBER_ID = "subscriberId"; + private static final String ATTR_SUBSCRIBER_ID_MATCH_RULE = "subscriberIdMatchRule"; private static final String ATTR_NETWORK_ID = "networkId"; + private static final String ATTR_TEMPLATE_METERED = "templateMetered"; @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay"; @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone"; private static final String ATTR_CYCLE_START = "cycleStart"; @@ -1451,7 +1458,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { */ @GuardedBy("mNetworkPoliciesSecondLock") private int findRelevantSubIdNL(NetworkTemplate template) { - // Mobile template is relevant when any active subscriber matches + // Carrier template is relevant when any active subscriber matches for (int i = 0; i < mSubIdToSubscriberId.size(); i++) { final int subId = mSubIdToSubscriberId.keyAt(i); final String subscriberId = mSubIdToSubscriberId.valueAt(i); @@ -1530,6 +1537,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } case TYPE_LIMIT: { switch (policy.template.getMatchRule()) { + case MATCH_CARRIER: case MATCH_MOBILE: title = res.getText(R.string.data_usage_mobile_limit_title); break; @@ -1558,6 +1566,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } case TYPE_LIMIT_SNOOZED: { switch (policy.template.getMatchRule()) { + case MATCH_CARRIER: case MATCH_MOBILE: title = res.getText(R.string.data_usage_mobile_limit_snoozed_title); break; @@ -1655,7 +1664,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { synchronized (mUidRulesFirstLock) { synchronized (mNetworkPoliciesSecondLock) { - ensureActiveMobilePolicyAL(); + ensureActiveCarrierPolicyAL(); normalizePoliciesNL(); updateNetworkEnabledNL(); updateNetworkRulesNL(); @@ -1680,17 +1689,17 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } /** - * Update mobile policies with data cycle information from {@link CarrierConfigManager} + * Update carrier policies with data cycle information from {@link CarrierConfigManager} * if necessary. * * @param subId that has its associated NetworkPolicy updated if necessary * @return if any policies were updated */ @GuardedBy("mNetworkPoliciesSecondLock") - private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) { - if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()"); + private boolean maybeUpdateCarrierPolicyCycleAL(int subId, String subscriberId) { + if (LOGV) Slog.v(TAG, "maybeUpdateCarrierPolicyCycleAL()"); - // find and update the mobile NetworkPolicy for this subscriber id + // find and update the carrier NetworkPolicy for this subscriber id boolean policyUpdated = false; final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true, @@ -1699,21 +1708,21 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { final NetworkTemplate template = mNetworkPolicy.keyAt(i); if (template.matches(probeIdent)) { final NetworkPolicy policy = mNetworkPolicy.valueAt(i); - policyUpdated |= updateDefaultMobilePolicyAL(subId, policy); + policyUpdated |= updateDefaultCarrierPolicyAL(subId, policy); } } return policyUpdated; } /** - * Returns the cycle day that should be used for a mobile NetworkPolicy. + * Returns the cycle day that should be used for a carrier NetworkPolicy. * * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable * to do so, it returns the fallback value. * * @param config The CarrierConfig to read the value from. * @param fallbackCycleDay to return if the CarrierConfig can't be read. - * @return cycleDay to use in the mobile NetworkPolicy. + * @return cycleDay to use in the carrier NetworkPolicy. */ @VisibleForTesting int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config, @@ -1738,14 +1747,14 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } /** - * Returns the warning bytes that should be used for a mobile NetworkPolicy. + * Returns the warning bytes that should be used for a carrier NetworkPolicy. * * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable * to do so, it returns the fallback value. * * @param config The CarrierConfig to read the value from. * @param fallbackWarningBytes to return if the CarrierConfig can't be read. - * @return warningBytes to use in the mobile NetworkPolicy. + * @return warningBytes to use in the carrier NetworkPolicy. */ @VisibleForTesting long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config, @@ -1771,14 +1780,14 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } /** - * Returns the limit bytes that should be used for a mobile NetworkPolicy. + * Returns the limit bytes that should be used for a carrier NetworkPolicy. * * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable * to do so, it returns the fallback value. * * @param config The CarrierConfig to read the value from. * @param fallbackLimitBytes to return if the CarrierConfig can't be read. - * @return limitBytes to use in the mobile NetworkPolicy. + * @return limitBytes to use in the carrier NetworkPolicy. */ @VisibleForTesting long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config, @@ -1824,8 +1833,8 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { synchronized (mNetworkPoliciesSecondLock) { final String subscriberId = mSubIdToSubscriberId.get(subId, null); if (subscriberId != null) { - ensureActiveMobilePolicyAL(subId, subscriberId); - maybeUpdateMobilePolicyCycleAL(subId, subscriberId); + ensureActiveCarrierPolicyAL(subId, subscriberId); + maybeUpdateCarrierPolicyCycleAL(subId, subscriberId); } else { Slog.wtf(TAG, "Missing subscriberId for subId " + subId); } @@ -1911,10 +1920,12 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { // TODO: reach into ConnectivityManager to proactively disable bringing // up this network, since we know that traffic will be blocked. - if (template.getMatchRule() == MATCH_MOBILE) { - // If mobile data usage hits the limit or if the user resumes the data, we need to + if (template.getMatchRule() == MATCH_MOBILE + || template.getMatchRule() == MATCH_CARRIER) { + // If carrier data usage hits the limit or if the user resumes the data, we need to // notify telephony. + // TODO: It needs to check if it matches the merged WIFI and notify to wifi module. final IntArray matchingSubIds = new IntArray(); synchronized (mNetworkPoliciesSecondLock) { for (int i = 0; i < mSubIdToSubscriberId.size(); i++) { @@ -2174,7 +2185,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { .truncatedTo(ChronoUnit.DAYS) .toInstant().toEpochMilli(); final long totalBytes = getTotalBytes( - NetworkTemplate.buildTemplateMobileAll(snapshot.getSubscriberId()), + buildTemplateCarrierMetered(snapshot.getSubscriberId()), start, startOfDay); final long remainingBytes = limitBytes - totalBytes; // Number of remaining days including current day @@ -2200,31 +2211,31 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { /** * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we - * have at least a default mobile policy defined. + * have at least a default carrier policy defined. */ @GuardedBy("mNetworkPoliciesSecondLock") - private void ensureActiveMobilePolicyAL() { - if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()"); + private void ensureActiveCarrierPolicyAL() { + if (LOGV) Slog.v(TAG, "ensureActiveCarrierPolicyAL()"); if (mSuppressDefaultPolicy) return; for (int i = 0; i < mSubIdToSubscriberId.size(); i++) { final int subId = mSubIdToSubscriberId.keyAt(i); final String subscriberId = mSubIdToSubscriberId.valueAt(i); - ensureActiveMobilePolicyAL(subId, subscriberId); + ensureActiveCarrierPolicyAL(subId, subscriberId); } } /** * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we - * have at least a default mobile policy defined. + * have at least a default carrier policy defined. * * @param subId to build a default policy for * @param subscriberId that we check for an existing policy - * @return true if a mobile network policy was added, or false one already existed. + * @return true if a carrier network policy was added, or false one already existed. */ @GuardedBy("mNetworkPoliciesSecondLock") - private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) { + private boolean ensureActiveCarrierPolicyAL(int subId, String subscriberId) { // Poke around to see if we already have a policy final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true, @@ -2243,7 +2254,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { Slog.i(TAG, "No policy for subscriber " + NetworkIdentityUtils.scrubSubscriberId(subscriberId) + "; generating default policy"); - final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId); + final NetworkPolicy policy = buildDefaultCarrierPolicy(subId, subscriberId); addNetworkPolicyAL(policy); return true; } @@ -2263,8 +2274,8 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } @VisibleForTesting - NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) { - final NetworkTemplate template = buildTemplateMobileAll(subscriberId); + NetworkPolicy buildDefaultCarrierPolicy(int subId, String subscriberId) { + final NetworkTemplate template = buildTemplateCarrierMetered(subscriberId); final RecurrenceRule cycleRule = NetworkPolicy .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault()); final NetworkPolicy policy = new NetworkPolicy(template, cycleRule, @@ -2272,7 +2283,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { SNOOZE_NEVER, SNOOZE_NEVER, true, true); synchronized (mUidRulesFirstLock) { synchronized (mNetworkPoliciesSecondLock) { - updateDefaultMobilePolicyAL(subId, policy); + updateDefaultCarrierPolicyAL(subId, policy); } } return policy; @@ -2286,7 +2297,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { * @return if the policy was modified */ @GuardedBy("mNetworkPoliciesSecondLock") - private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) { + private boolean updateDefaultCarrierPolicyAL(int subId, NetworkPolicy policy) { if (!policy.inferred) { if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy); return false; @@ -2372,14 +2383,33 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND) && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND); } else if (TAG_NETWORK_POLICY.equals(tag)) { - final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE); + int templateType = readIntAttribute(in, ATTR_NETWORK_TEMPLATE); final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID); final String networkId; + final int subscriberIdMatchRule; + final int templateMeteredness; if (version >= VERSION_ADDED_NETWORK_ID) { networkId = in.getAttributeValue(null, ATTR_NETWORK_ID); } else { networkId = null; } + + if (version >= VERSION_SUPPORTED_CARRIER_USAGE) { + subscriberIdMatchRule = readIntAttribute(in, + ATTR_SUBSCRIBER_ID_MATCH_RULE); + templateMeteredness = readIntAttribute(in, ATTR_TEMPLATE_METERED); + + } else { + subscriberIdMatchRule = NetworkTemplate.SUBSCRIBER_ID_MATCH_RULE_EXACT; + if (templateType == MATCH_MOBILE) { + Log.d(TAG, "Update template match rule from mobile to carrier and" + + " force to metered"); + templateType = MATCH_CARRIER; + templateMeteredness = METERED_YES; + } else { + templateMeteredness = METERED_ALL; + } + } final RecurrenceRule cycleRule; if (version >= VERSION_ADDED_CYCLE) { final String start = readStringAttribute(in, ATTR_CYCLE_START); @@ -2413,7 +2443,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { if (version >= VERSION_ADDED_METERED) { metered = readBooleanAttribute(in, ATTR_METERED); } else { - switch (networkTemplate) { + switch (templateType) { case MATCH_MOBILE: metered = true; break; @@ -2433,9 +2463,11 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } else { inferred = false; } - - final NetworkTemplate template = new NetworkTemplate(networkTemplate, - subscriberId, networkId); + final NetworkTemplate template = new NetworkTemplate(templateType, + subscriberId, new String[] { subscriberId }, + networkId, templateMeteredness, NetworkStats.ROAMING_ALL, + NetworkStats.DEFAULT_NETWORK_ALL, NetworkTemplate.NETWORK_TYPE_ALL, + NetworkTemplate.OEM_MANAGED_ALL, subscriberIdMatchRule); if (template.isPersistable()) { mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule, warningBytes, limitBytes, lastWarningSnooze, @@ -2642,10 +2674,14 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { if (subscriberId != null) { out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId); } + writeIntAttribute(out, ATTR_SUBSCRIBER_ID_MATCH_RULE, + template.getSubscriberIdMatchRule()); final String networkId = template.getNetworkId(); if (networkId != null) { out.attribute(null, ATTR_NETWORK_ID, networkId); } + writeIntAttribute(out, ATTR_TEMPLATE_METERED, + template.getMeteredness()); writeStringAttribute(out, ATTR_CYCLE_START, RecurrenceRule.convertZonedDateTime(policy.cycleRule.start)); writeStringAttribute(out, ATTR_CYCLE_END, @@ -3513,8 +3549,8 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { final String subscriberId = mSubIdToSubscriberId.get(subId, null); if (subscriberId != null) { - ensureActiveMobilePolicyAL(subId, subscriberId); - maybeUpdateMobilePolicyCycleAL(subId, subscriberId); + ensureActiveCarrierPolicyAL(subId, subscriberId); + maybeUpdateCarrierPolicyCycleAL(subId, subscriberId); } else { Slog.wtf(TAG, "Missing subscriberId for subId " + subId); } @@ -5575,11 +5611,15 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { return; } - // Turn mobile data limit off + // Turn carrier/mobile data limit off NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName()); - NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber); + NetworkTemplate templateCarrier = buildTemplateCarrierMetered(subscriber); + NetworkTemplate templateMobile = buildTemplateMobileAll(subscriber); for (NetworkPolicy policy : policies) { - if (policy.template.equals(template)) { + // All policies loaded from disk will be carrier templates, and setting will also only + // set carrier templates, but we clear mobile templates just in case one is set by + // some other caller + if (policy.template.equals(templateCarrier) || policy.template.equals(templateMobile)) { policy.limitBytes = NetworkPolicy.LIMIT_DISABLED; policy.inferred = false; policy.clearSnooze(); diff --git a/services/tests/servicestests/assets/NetworkPolicyManagerServiceTest/netpolicy/network-policy-mobile.xml b/services/tests/servicestests/assets/NetworkPolicyManagerServiceTest/netpolicy/network-policy-mobile.xml new file mode 100644 index 0000000000000..d1357e70ab32b --- /dev/null +++ b/services/tests/servicestests/assets/NetworkPolicyManagerServiceTest/netpolicy/network-policy-mobile.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/services/tests/servicestests/assets/NetworkPolicyManagerServiceTest/netpolicy/network-policy-wifi-with-subscriberId-match-rule-all-and-templateMetered-no.xml b/services/tests/servicestests/assets/NetworkPolicyManagerServiceTest/netpolicy/network-policy-wifi-with-subscriberId-match-rule-all-and-templateMetered-no.xml new file mode 100644 index 0000000000000..60d7d2555f049 --- /dev/null +++ b/services/tests/servicestests/assets/NetworkPolicyManagerServiceTest/netpolicy/network-policy-wifi-with-subscriberId-match-rule-all-and-templateMetered-no.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/services/tests/servicestests/src/com/android/server/net/NetworkPolicyManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/net/NetworkPolicyManagerServiceTest.java index da6c30e1cb0a2..23517a9b0458c 100644 --- a/services/tests/servicestests/src/com/android/server/net/NetworkPolicyManagerServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/net/NetworkPolicyManagerServiceTest.java @@ -50,10 +50,12 @@ import static android.net.NetworkPolicyManager.uidPoliciesToString; import static android.net.NetworkPolicyManager.uidRulesToString; import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK; import static android.net.NetworkStats.IFACE_ALL; +import static android.net.NetworkStats.METERED_NO; +import static android.net.NetworkStats.METERED_YES; import static android.net.NetworkStats.SET_ALL; import static android.net.NetworkStats.TAG_ALL; import static android.net.NetworkStats.TAG_NONE; -import static android.net.NetworkTemplate.buildTemplateMobileAll; +import static android.net.NetworkTemplate.buildTemplateCarrierMetered; import static android.net.NetworkTemplate.buildTemplateWifi; import static android.net.TrafficStats.MB_IN_BYTES; import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED; @@ -231,7 +233,8 @@ public class NetworkPolicyManagerServiceTest { private static NetworkTemplate sTemplateWifi = buildTemplateWifi(TEST_SSID); - private static NetworkTemplate sTemplateMobileAll = buildTemplateMobileAll(TEST_IMSI); + private static NetworkTemplate sTemplateCarrierMetered = + buildTemplateCarrierMetered(TEST_IMSI); /** * Path on assets where files used by {@link NetPolicyXml} are located. @@ -452,7 +455,7 @@ public class NetworkPolicyManagerServiceTest { verify(mNetworkManager).registerObserver(networkObserver.capture()); mNetworkObserver = networkObserver.getValue(); - NetworkPolicy defaultPolicy = mService.buildDefaultMobilePolicy(0, ""); + NetworkPolicy defaultPolicy = mService.buildDefaultCarrierPolicy(0, ""); mDefaultWarningBytes = defaultPolicy.warningBytes; mDefaultLimitBytes = defaultPolicy.limitBytes; } @@ -1231,7 +1234,7 @@ public class NetworkPolicyManagerServiceTest { reset(mTelephonyManager, mNetworkManager, mNotifManager); TelephonyManager tmSub = expectMobileDefaults(); - mService.snoozeLimit(NetworkTemplate.buildTemplateMobileAll(TEST_IMSI)); + mService.snoozeLimit(NetworkTemplate.buildTemplateCarrierMetered(TEST_IMSI)); mService.updateNetworks(); verify(tmSub, atLeastOnce()).setPolicyDataEnabled(true); @@ -1484,7 +1487,7 @@ public class NetworkPolicyManagerServiceTest { assertEquals(mDefaultLimitBytes, actualLimitBytes); } - private PersistableBundle setupUpdateMobilePolicyCycleTests() throws RemoteException { + private PersistableBundle setupUpdateCarrierPolicyCycleTests() throws RemoteException { when(mConnManager.getAllNetworkStateSnapshots()) .thenReturn(new ArrayList()); @@ -1492,19 +1495,19 @@ public class NetworkPolicyManagerServiceTest { PersistableBundle bundle = CarrierConfigManager.getDefaultConfig(); when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle); - setNetworkPolicies(buildDefaultFakeMobilePolicy()); + setNetworkPolicies(buildDefaultFakeCarrierPolicy()); return bundle; } @Test - public void testUpdateMobilePolicyCycleWithNullConfig() throws RemoteException { + public void testUpdateCarrierPolicyCycleWithNullConfig() throws RemoteException { when(mConnManager.getAllNetworkStateSnapshots()) .thenReturn(new ArrayList()); setupTelephonySubscriptionManagers(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID); when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null); - setNetworkPolicies(buildDefaultFakeMobilePolicy()); + setNetworkPolicies(buildDefaultFakeCarrierPolicy()); // smoke test to make sure no errors are raised mServiceContext.sendBroadcast( new Intent(ACTION_CARRIER_CONFIG_CHANGED) @@ -1515,8 +1518,8 @@ public class NetworkPolicyManagerServiceTest { } @Test - public void testUpdateMobilePolicyCycleWithInvalidConfig() throws RemoteException { - PersistableBundle bundle = setupUpdateMobilePolicyCycleTests(); + public void testUpdateCarrierPolicyCycleWithInvalidConfig() throws RemoteException { + PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests(); // Test with an invalid CarrierConfig, there should be no changes or crashes. bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, -100); bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, -100); @@ -1531,8 +1534,8 @@ public class NetworkPolicyManagerServiceTest { } @Test - public void testUpdateMobilePolicyCycleWithDefaultConfig() throws RemoteException { - PersistableBundle bundle = setupUpdateMobilePolicyCycleTests(); + public void testUpdateCarrierPolicyCycleWithDefaultConfig() throws RemoteException { + PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests(); // Test that we respect the platform values when told to bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, DATA_CYCLE_USE_PLATFORM_DEFAULT); @@ -1550,11 +1553,11 @@ public class NetworkPolicyManagerServiceTest { } @Test - public void testUpdateMobilePolicyCycleWithUserOverrides() throws RemoteException { - PersistableBundle bundle = setupUpdateMobilePolicyCycleTests(); + public void testUpdateCarrierPolicyCycleWithUserOverrides() throws RemoteException { + PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests(); // inferred = false implies that a user manually modified this policy. - NetworkPolicy policy = buildDefaultFakeMobilePolicy(); + NetworkPolicy policy = buildDefaultFakeCarrierPolicy(); policy.inferred = false; setNetworkPolicies(policy); @@ -1573,8 +1576,8 @@ public class NetworkPolicyManagerServiceTest { } @Test - public void testUpdateMobilePolicyCycleUpdatesDataCycle() throws RemoteException { - PersistableBundle bundle = setupUpdateMobilePolicyCycleTests(); + public void testUpdateCarrierPolicyCycleUpdatesDataCycle() throws RemoteException { + PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests(); bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31); bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999); @@ -1588,8 +1591,8 @@ public class NetworkPolicyManagerServiceTest { } @Test - public void testUpdateMobilePolicyCycleDisableThresholds() throws RemoteException { - PersistableBundle bundle = setupUpdateMobilePolicyCycleTests(); + public void testUpdateCarrierPolicyCycleDisableThresholds() throws RemoteException { + PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests(); bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31); bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, @@ -1605,8 +1608,8 @@ public class NetworkPolicyManagerServiceTest { } @Test - public void testUpdateMobilePolicyCycleRevertsToDefault() throws RemoteException { - PersistableBundle bundle = setupUpdateMobilePolicyCycleTests(); + public void testUpdateCarrierPolicyCycleRevertsToDefault() throws RemoteException { + PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests(); bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31); bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, @@ -1775,7 +1778,7 @@ public class NetworkPolicyManagerServiceTest { @Test public void testSetNetworkPolicies_withNullPolicies_doesNotThrow() { NetworkPolicy[] policies = new NetworkPolicy[3]; - policies[1] = buildDefaultFakeMobilePolicy(); + policies[1] = buildDefaultFakeCarrierPolicy(); setNetworkPolicies(policies); assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes, @@ -1821,7 +1824,8 @@ public class NetworkPolicyManagerServiceTest { // Set warning to 7KB and limit to 10KB. setNetworkPolicies(new NetworkPolicy( - sTemplateMobileAll, CYCLE_DAY, TIMEZONE_UTC, 7000L, 10000L, true)); + sTemplateCarrierMetered, CYCLE_DAY, TIMEZONE_UTC, 7000L, 10000L, + true)); postMsgAndWaitForCompletion(); // Verifies that remaining quotas are set to providers. @@ -1972,6 +1976,40 @@ public class NetworkPolicyManagerServiceTest { } } + @Test + @NetPolicyXml("network-policy-mobile.xml") + public void testStartToSupportCarrierUsagePolicy() throws Exception { + NetworkPolicy[] policies = mService.getNetworkPolicies( + mServiceContext.getOpPackageName()); + assertEquals("Unexpected number of network policies", 1, policies.length); + NetworkPolicy actualPolicy = policies[0]; + assertEquals("Unexpected template match rule in network policies", + NetworkTemplate.MATCH_CARRIER, + actualPolicy.template.getMatchRule()); + assertEquals("Unexpected subscriberId match rule in network policies", + NetworkTemplate.SUBSCRIBER_ID_MATCH_RULE_EXACT, + actualPolicy.template.getSubscriberIdMatchRule()); + assertEquals("Unexpected template meteredness in network policies", + METERED_YES, actualPolicy.template.getMeteredness()); + } + + @Test + @NetPolicyXml("network-policy-wifi-with-subscriberId-match-rule-all-and-templateMetered-no.xml") + public void testSupportedCarrierUsagePolicy() throws Exception { + NetworkPolicy[] policies = mService.getNetworkPolicies( + mServiceContext.getOpPackageName()); + assertEquals("Unexpected number of network policies", 1, policies.length); + NetworkPolicy actualPolicy = policies[0]; + assertEquals("Unexpected template match rule in network policies", + NetworkTemplate.MATCH_WIFI, + actualPolicy.template.getMatchRule()); + assertEquals("Unexpected subscriberId match rule in network policies", + NetworkTemplate.SUBSCRIBER_ID_MATCH_RULE_ALL, + actualPolicy.template.getSubscriberIdMatchRule()); + assertEquals("Unexpected template meteredness in network policies", + METERED_NO, actualPolicy.template.getMeteredness()); + } + private String formatBlockedStateError(int uid, int rule, boolean metered, boolean backgroundRestricted) { return String.format( @@ -2024,8 +2062,8 @@ public class NetworkPolicyManagerServiceTest { return builder.build(); } - private NetworkPolicy buildDefaultFakeMobilePolicy() { - NetworkPolicy p = mService.buildDefaultMobilePolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID); + private NetworkPolicy buildDefaultFakeCarrierPolicy() { + NetworkPolicy p = mService.buildDefaultCarrierPolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID); // set a deterministic cycle date p.cycleRule = new RecurrenceRule( p.cycleRule.start.withDayOfMonth(DEFAULT_CYCLE_DAY), @@ -2033,9 +2071,9 @@ public class NetworkPolicyManagerServiceTest { return p; } - private static NetworkPolicy buildFakeMobilePolicy(int cycleDay, long warningBytes, + private static NetworkPolicy buildFakeCarrierPolicy(int cycleDay, long warningBytes, long limitBytes, boolean inferred) { - final NetworkTemplate template = buildTemplateMobileAll(FAKE_SUBSCRIBER_ID); + final NetworkTemplate template = buildTemplateCarrierMetered(FAKE_SUBSCRIBER_ID); return new NetworkPolicy(template, cycleDay, TimeZone.getDefault().getID(), warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, inferred); } @@ -2046,8 +2084,8 @@ public class NetworkPolicyManagerServiceTest { mServiceContext.getOpPackageName()); assertEquals("Unexpected number of network policies", 1, policies.length); NetworkPolicy actualPolicy = policies[0]; - NetworkPolicy expectedPolicy = buildFakeMobilePolicy(expectedCycleDay, expectedWarningBytes, - expectedLimitBytes, expectedInferred); + NetworkPolicy expectedPolicy = buildFakeCarrierPolicy(expectedCycleDay, + expectedWarningBytes, expectedLimitBytes, expectedInferred); assertEquals(expectedPolicy, actualPolicy); } From 35c9bb8521e3bb03dd97f6249f1b6ffa5cf17ef6 Mon Sep 17 00:00:00 2001 From: lesl Date: Thu, 11 Mar 2021 22:41:51 +0800 Subject: [PATCH 2/2] wifi: Use new API for data usage function For mobile, a old API: buildTemplateMobileAll doesn't includes the merged wifi network, call the new API: buildTemplateCarrierMetered to replace the old one. PS: Not only usage functionality but also apply to network policy control since the default policy is changing to use new API: buildTemplateCarrier now. Test: atest -c DataUsageControllerTest Test: atest -c NetworkCycleDataForUidLoaderTest Test: atest -c NetworkPolicyEditorTest Test: Manual Test, modify the mobile usage warming and limit bytes and check the data via adb shell dumpsys netpolicy Bug: 176396812 Merged-In: I1c7da4a819e45009efe5ba2b80e1526ce6b04e27 Change-Id: I1c7da4a819e45009efe5ba2b80e1526ce6b04e27 --- .../src/com/android/settingslib/net/DataUsageUtils.java | 3 ++- .../android/settingslib/utils/NetworkPolicyEditorTest.java | 2 +- .../com/android/settingslib/net/DataUsageControllerTest.java | 4 ++-- .../settingslib/net/NetworkCycleDataForUidLoaderTest.java | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/SettingsLib/src/com/android/settingslib/net/DataUsageUtils.java b/packages/SettingsLib/src/com/android/settingslib/net/DataUsageUtils.java index b1234f291b74a..51e533abebd24 100644 --- a/packages/SettingsLib/src/com/android/settingslib/net/DataUsageUtils.java +++ b/packages/SettingsLib/src/com/android/settingslib/net/DataUsageUtils.java @@ -73,6 +73,7 @@ public class DataUsageUtils { private static NetworkTemplate getMobileTemplateForSubId( TelephonyManager telephonyManager, int subId) { - return NetworkTemplate.buildTemplateMobileAll(telephonyManager.getSubscriberId(subId)); + return NetworkTemplate.buildTemplateCarrierMetered( + telephonyManager.getSubscriberId(subId)); } } diff --git a/packages/SettingsLib/tests/integ/src/com/android/settingslib/utils/NetworkPolicyEditorTest.java b/packages/SettingsLib/tests/integ/src/com/android/settingslib/utils/NetworkPolicyEditorTest.java index 37f2600e9812c..7e389a19e4030 100644 --- a/packages/SettingsLib/tests/integ/src/com/android/settingslib/utils/NetworkPolicyEditorTest.java +++ b/packages/SettingsLib/tests/integ/src/com/android/settingslib/utils/NetworkPolicyEditorTest.java @@ -44,7 +44,7 @@ public class NetworkPolicyEditorTest { @Before public void setUp() { - mNetworkTemplate = NetworkTemplate.buildTemplateMobileAll("123456789123456"); + mNetworkTemplate = NetworkTemplate.buildTemplateCarrierMetered("123456789123456"); NetworkPolicyManager policyManager = NetworkPolicyManager.from(InstrumentationRegistry .getContext()); mNetworkPolicyEditor = new NetworkPolicyEditor(policyManager); diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/DataUsageControllerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/DataUsageControllerTest.java index 27d877db49524..9be783d61ea8d 100644 --- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/DataUsageControllerTest.java +++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/DataUsageControllerTest.java @@ -87,8 +87,8 @@ public class DataUsageControllerTest { ShadowSubscriptionManager.setDefaultDataSubscriptionId(mDefaultSubscriptionId); doReturn(SUB_ID).when(mTelephonyManager).getSubscriberId(); - mNetworkTemplate = NetworkTemplate.buildTemplateMobileAll(SUB_ID); - mNetworkTemplate2 = NetworkTemplate.buildTemplateMobileAll(SUB_ID_2); + mNetworkTemplate = NetworkTemplate.buildTemplateCarrierMetered(SUB_ID); + mNetworkTemplate2 = NetworkTemplate.buildTemplateCarrierMetered(SUB_ID_2); mWifiNetworkTemplate = NetworkTemplate.buildTemplateWifi( NetworkTemplate.WIFI_NETWORKID_ALL, null); } diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataForUidLoaderTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataForUidLoaderTest.java index 877eb615b196c..e8d5844867463 100644 --- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataForUidLoaderTest.java +++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataForUidLoaderTest.java @@ -62,7 +62,7 @@ public class NetworkCycleDataForUidLoaderTest { when(mContext.getSystemService(Context.NETWORK_POLICY_SERVICE)) .thenReturn(mNetworkPolicyManager); when(mNetworkPolicyManager.getNetworkPolicies()).thenReturn(new NetworkPolicy[0]); - mNetworkTemplate = NetworkTemplate.buildTemplateMobileAll(SUB_ID); + mNetworkTemplate = NetworkTemplate.buildTemplateCarrierMetered(SUB_ID); } @Test