[MS57.1] Prepare APIs for data migration utility

This includes:
1. Move PREFIX_* constants to NetworkStatsManager to expose
   in later changes.
2. Rename networkId to wifiNetworkKey.
3. Rename subType to ratType.
4. Replace SUBTYPE_COMBINED with NETWORK_TYPE_ALL
5. Fix lint errors when exposing system api.

Test: TH
Bug: 204830222
Change-Id: I2b7c34958bc59c3225c96f12abba008b83101585
This commit is contained in:
Junyu Lai
2022-01-16 11:04:16 +00:00
parent 84316eb4b6
commit a8dc50de05
7 changed files with 245 additions and 85 deletions

View File

@@ -125,6 +125,19 @@ public class NetworkStatsManager {
private final Context mContext; private final Context mContext;
private final INetworkStatsService mService; private final INetworkStatsService mService;
/**
* Type constants for reading different types of Data Usage.
* @hide
*/
// @SystemApi(client = MODULE_LIBRARIES)
public static final String PREFIX_DEV = "dev";
/** @hide */
public static final String PREFIX_XT = "xt";
/** @hide */
public static final String PREFIX_UID = "uid";
/** @hide */
public static final String PREFIX_UID_TAG = "uid_tag";
/** @hide */ /** @hide */
public static final int FLAG_POLL_ON_OPEN = 1 << 0; public static final int FLAG_POLL_ON_OPEN = 1 << 0;
/** @hide */ /** @hide */

View File

@@ -17,12 +17,15 @@
package android.net; package android.net;
import static android.net.ConnectivityManager.TYPE_WIFI; import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.NetworkTemplate.NETWORK_TYPE_ALL;
import android.annotation.NonNull;
import android.annotation.Nullable; import android.annotation.Nullable;
import android.content.Context; import android.content.Context;
import android.net.wifi.WifiInfo; import android.net.wifi.WifiInfo;
import android.service.NetworkIdentityProto; import android.service.NetworkIdentityProto;
import android.telephony.Annotation.NetworkType; import android.telephony.Annotation;
import android.telephony.TelephonyManager;
import android.util.proto.ProtoOutputStream; import android.util.proto.ProtoOutputStream;
import com.android.net.module.util.NetworkCapabilitiesUtils; import com.android.net.module.util.NetworkCapabilitiesUtils;
@@ -37,9 +40,13 @@ import java.util.Objects;
* *
* @hide * @hide
*/ */
// @SystemApi(client = MODULE_LIBRARIES)
public class NetworkIdentity implements Comparable<NetworkIdentity> { public class NetworkIdentity implements Comparable<NetworkIdentity> {
private static final String TAG = "NetworkIdentity"; private static final String TAG = "NetworkIdentity";
/** @hide */
// TODO: Remove this after migrating all callers to use
// {@link NetworkTemplate#NETWORK_TYPE_ALL} instead.
public static final int SUBTYPE_COMBINED = -1; public static final int SUBTYPE_COMBINED = -1;
/** /**
@@ -59,21 +66,22 @@ public class NetworkIdentity implements Comparable<NetworkIdentity> {
public static final int OEM_PRIVATE = 0x2; public static final int OEM_PRIVATE = 0x2;
final int mType; final int mType;
final int mSubType; final int mRatType;
final String mSubscriberId; final String mSubscriberId;
final String mNetworkId; final String mWifiNetworkKey;
final boolean mRoaming; final boolean mRoaming;
final boolean mMetered; final boolean mMetered;
final boolean mDefaultNetwork; final boolean mDefaultNetwork;
final int mOemManaged; final int mOemManaged;
/** @hide */
public NetworkIdentity( public NetworkIdentity(
int type, int subType, String subscriberId, String networkId, boolean roaming, int type, int ratType, @Nullable String subscriberId, @Nullable String wifiNetworkKey,
boolean metered, boolean defaultNetwork, int oemManaged) { boolean roaming, boolean metered, boolean defaultNetwork, int oemManaged) {
mType = type; mType = type;
mSubType = subType; mRatType = ratType;
mSubscriberId = subscriberId; mSubscriberId = subscriberId;
mNetworkId = networkId; mWifiNetworkKey = wifiNetworkKey;
mRoaming = roaming; mRoaming = roaming;
mMetered = metered; mMetered = metered;
mDefaultNetwork = defaultNetwork; mDefaultNetwork = defaultNetwork;
@@ -82,7 +90,7 @@ public class NetworkIdentity implements Comparable<NetworkIdentity> {
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(mType, mSubType, mSubscriberId, mNetworkId, mRoaming, mMetered, return Objects.hash(mType, mRatType, mSubscriberId, mWifiNetworkKey, mRoaming, mMetered,
mDefaultNetwork, mOemManaged); mDefaultNetwork, mOemManaged);
} }
@@ -90,9 +98,9 @@ public class NetworkIdentity implements Comparable<NetworkIdentity> {
public boolean equals(@Nullable Object obj) { public boolean equals(@Nullable Object obj) {
if (obj instanceof NetworkIdentity) { if (obj instanceof NetworkIdentity) {
final NetworkIdentity ident = (NetworkIdentity) obj; final NetworkIdentity ident = (NetworkIdentity) obj;
return mType == ident.mType && mSubType == ident.mSubType && mRoaming == ident.mRoaming return mType == ident.mType && mRatType == ident.mRatType && mRoaming == ident.mRoaming
&& Objects.equals(mSubscriberId, ident.mSubscriberId) && Objects.equals(mSubscriberId, ident.mSubscriberId)
&& Objects.equals(mNetworkId, ident.mNetworkId) && Objects.equals(mWifiNetworkKey, ident.mWifiNetworkKey)
&& mMetered == ident.mMetered && mMetered == ident.mMetered
&& mDefaultNetwork == ident.mDefaultNetwork && mDefaultNetwork == ident.mDefaultNetwork
&& mOemManaged == ident.mOemManaged; && mOemManaged == ident.mOemManaged;
@@ -104,18 +112,18 @@ public class NetworkIdentity implements Comparable<NetworkIdentity> {
public String toString() { public String toString() {
final StringBuilder builder = new StringBuilder("{"); final StringBuilder builder = new StringBuilder("{");
builder.append("type=").append(mType); builder.append("type=").append(mType);
builder.append(", subType="); builder.append(", ratType=");
if (mSubType == SUBTYPE_COMBINED) { if (mRatType == NETWORK_TYPE_ALL) {
builder.append("COMBINED"); builder.append("COMBINED");
} else { } else {
builder.append(mSubType); builder.append(mRatType);
} }
if (mSubscriberId != null) { if (mSubscriberId != null) {
builder.append(", subscriberId=") builder.append(", subscriberId=")
.append(NetworkIdentityUtils.scrubSubscriberId(mSubscriberId)); .append(NetworkIdentityUtils.scrubSubscriberId(mSubscriberId));
} }
if (mNetworkId != null) { if (mWifiNetworkKey != null) {
builder.append(", networkId=").append(mNetworkId); builder.append(", wifiNetworkKey=").append(mWifiNetworkKey);
} }
if (mRoaming) { if (mRoaming) {
builder.append(", ROAMING"); builder.append(", ROAMING");
@@ -153,12 +161,13 @@ public class NetworkIdentity implements Comparable<NetworkIdentity> {
} }
} }
/** @hide */
public void dumpDebug(ProtoOutputStream proto, long tag) { public void dumpDebug(ProtoOutputStream proto, long tag) {
final long start = proto.start(tag); final long start = proto.start(tag);
proto.write(NetworkIdentityProto.TYPE, mType); proto.write(NetworkIdentityProto.TYPE, mType);
// Not dumping mSubType, subtypes are no longer supported. // TODO: dump mRatType as well.
proto.write(NetworkIdentityProto.ROAMING, mRoaming); proto.write(NetworkIdentityProto.ROAMING, mRoaming);
proto.write(NetworkIdentityProto.METERED, mMetered); proto.write(NetworkIdentityProto.METERED, mMetered);
@@ -168,50 +177,68 @@ public class NetworkIdentity implements Comparable<NetworkIdentity> {
proto.end(start); proto.end(start);
} }
/** @hide */
public int getType() { public int getType() {
return mType; return mType;
} }
public int getSubType() { /** @hide */
return mSubType; public int getRatType() {
return mRatType;
} }
/** @hide */
public String getSubscriberId() { public String getSubscriberId() {
return mSubscriberId; return mSubscriberId;
} }
public String getNetworkId() { /** @hide */
return mNetworkId; public String getWifiNetworkKey() {
return mWifiNetworkKey;
} }
/** @hide */
public boolean getRoaming() { public boolean getRoaming() {
return mRoaming; return mRoaming;
} }
/** @hide */
public boolean getMetered() { public boolean getMetered() {
return mMetered; return mMetered;
} }
/** @hide */
public boolean getDefaultNetwork() { public boolean getDefaultNetwork() {
return mDefaultNetwork; return mDefaultNetwork;
} }
/** @hide */
public int getOemManaged() { public int getOemManaged() {
return mOemManaged; return mOemManaged;
} }
/** /**
* Build a {@link NetworkIdentity} from the given {@link NetworkStateSnapshot} and * Assemble a {@link NetworkIdentity} from the passed arguments.
* {@code subType}, assuming that any mobile networks are using the current IMSI. *
* The subType if applicable, should be set as one of the TelephonyManager.NETWORK_TYPE_* * This methods builds an identity based on the capabilities of the network in the
* constants, or {@link android.telephony.TelephonyManager#NETWORK_TYPE_UNKNOWN} if not. * snapshot and other passed arguments. The identity is used as a key to record data usage.
*
* @param snapshot the snapshot of network state. See {@link NetworkStateSnapshot}.
* @param defaultNetwork whether the network is a default network.
* @param ratType the Radio Access Technology(RAT) type of the network. Or
* {@link TelephonyManager#NETWORK_TYPE_UNKNOWN} if not applicable.
* See {@code TelephonyManager.NETWORK_TYPE_*}.
* @hide
*/ */
// TODO: Remove this after all callers are migrated to use new Api.
@NonNull
public static NetworkIdentity buildNetworkIdentity(Context context, public static NetworkIdentity buildNetworkIdentity(Context context,
NetworkStateSnapshot snapshot, boolean defaultNetwork, @NetworkType int subType) { @NonNull NetworkStateSnapshot snapshot,
boolean defaultNetwork, @Annotation.NetworkType int ratType) {
final int legacyType = snapshot.getLegacyType(); final int legacyType = snapshot.getLegacyType();
final String subscriberId = snapshot.getSubscriberId(); final String subscriberId = snapshot.getSubscriberId();
String networkId = null; String wifiNetworkKey = null;
boolean roaming = !snapshot.getNetworkCapabilities().hasCapability( boolean roaming = !snapshot.getNetworkCapabilities().hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING); NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
boolean metered = !(snapshot.getNetworkCapabilities().hasCapability( boolean metered = !(snapshot.getNetworkCapabilities().hasCapability(
@@ -226,19 +253,19 @@ public class NetworkIdentity implements Comparable<NetworkIdentity> {
.getTransportInfo(); .getTransportInfo();
if (transportInfo instanceof WifiInfo) { if (transportInfo instanceof WifiInfo) {
final WifiInfo info = (WifiInfo) transportInfo; final WifiInfo info = (WifiInfo) transportInfo;
networkId = info != null ? info.getCurrentNetworkKey() : null; wifiNetworkKey = info != null ? info.getCurrentNetworkKey() : null;
} }
} }
return new NetworkIdentity(legacyType, subType, subscriberId, networkId, roaming, metered, return new NetworkIdentity(legacyType, ratType, subscriberId, wifiNetworkKey, roaming,
defaultNetwork, oemManaged); metered, defaultNetwork, oemManaged);
} }
/** /**
* Builds a bitfield of {@code NetworkIdentity.OEM_*} based on {@link NetworkCapabilities}. * Builds a bitfield of {@code NetworkIdentity.OEM_*} based on {@link NetworkCapabilities}.
* @hide * @hide
*/ */
public static int getOemBitfield(NetworkCapabilities nc) { public static int getOemBitfield(@NonNull NetworkCapabilities nc) {
int oemManaged = OEM_NONE; int oemManaged = OEM_NONE;
if (nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_OEM_PAID)) { if (nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_OEM_PAID)) {
@@ -252,16 +279,17 @@ public class NetworkIdentity implements Comparable<NetworkIdentity> {
} }
@Override @Override
public int compareTo(NetworkIdentity another) { public int compareTo(@NonNull NetworkIdentity another) {
Objects.requireNonNull(another);
int res = Integer.compare(mType, another.mType); int res = Integer.compare(mType, another.mType);
if (res == 0) { if (res == 0) {
res = Integer.compare(mSubType, another.mSubType); res = Integer.compare(mRatType, another.mRatType);
} }
if (res == 0 && mSubscriberId != null && another.mSubscriberId != null) { if (res == 0 && mSubscriberId != null && another.mSubscriberId != null) {
res = mSubscriberId.compareTo(another.mSubscriberId); res = mSubscriberId.compareTo(another.mSubscriberId);
} }
if (res == 0 && mNetworkId != null && another.mNetworkId != null) { if (res == 0 && mWifiNetworkKey != null && another.mWifiNetworkKey != null) {
res = mNetworkId.compareTo(another.mNetworkId); res = mWifiNetworkKey.compareTo(another.mWifiNetworkKey);
} }
if (res == 0) { if (res == 0) {
res = Boolean.compare(mRoaming, another.mRoaming); res = Boolean.compare(mRoaming, another.mRoaming);

View File

@@ -18,6 +18,7 @@ package android.net;
import static android.net.ConnectivityManager.TYPE_MOBILE; import static android.net.ConnectivityManager.TYPE_MOBILE;
import android.annotation.NonNull;
import android.service.NetworkIdentitySetProto; import android.service.NetworkIdentitySetProto;
import android.util.proto.ProtoOutputStream; import android.util.proto.ProtoOutputStream;
@@ -25,6 +26,7 @@ import java.io.DataInput;
import java.io.DataOutput; import java.io.DataOutput;
import java.io.IOException; import java.io.IOException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Objects;
/** /**
* Identity of a {@code iface}, defined by the set of {@link NetworkIdentity} * Identity of a {@code iface}, defined by the set of {@link NetworkIdentity}
@@ -32,6 +34,7 @@ import java.util.HashSet;
* *
* @hide * @hide
*/ */
// @SystemApi(client = MODULE_LIBRARIES)
public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
Comparable<NetworkIdentitySet> { Comparable<NetworkIdentitySet> {
private static final int VERSION_INIT = 1; private static final int VERSION_INIT = 1;
@@ -41,9 +44,14 @@ public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
private static final int VERSION_ADD_DEFAULT_NETWORK = 5; private static final int VERSION_ADD_DEFAULT_NETWORK = 5;
private static final int VERSION_ADD_OEM_MANAGED_NETWORK = 6; private static final int VERSION_ADD_OEM_MANAGED_NETWORK = 6;
/**
* Construct a {@link NetworkIdentitySet} object.
*/
public NetworkIdentitySet() { public NetworkIdentitySet() {
super();
} }
/** @hide */
public NetworkIdentitySet(DataInput in) throws IOException { public NetworkIdentitySet(DataInput in) throws IOException {
final int version = in.readInt(); final int version = in.readInt();
final int size = in.readInt(); final int size = in.readInt();
@@ -52,7 +60,7 @@ public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
final int ignored = in.readInt(); final int ignored = in.readInt();
} }
final int type = in.readInt(); final int type = in.readInt();
final int subType = in.readInt(); final int ratType = in.readInt();
final String subscriberId = readOptionalString(in); final String subscriberId = readOptionalString(in);
final String networkId; final String networkId;
if (version >= VERSION_ADD_NETWORK_ID) { if (version >= VERSION_ADD_NETWORK_ID) {
@@ -91,22 +99,23 @@ public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
oemNetCapabilities = NetworkIdentity.OEM_NONE; oemNetCapabilities = NetworkIdentity.OEM_NONE;
} }
add(new NetworkIdentity(type, subType, subscriberId, networkId, roaming, metered, add(new NetworkIdentity(type, ratType, subscriberId, networkId, roaming, metered,
defaultNetwork, oemNetCapabilities)); defaultNetwork, oemNetCapabilities));
} }
} }
/** /**
* Method to serialize this object into a {@code DataOutput}. * Method to serialize this object into a {@code DataOutput}.
* @hide
*/ */
public void writeToStream(DataOutput out) throws IOException { public void writeToStream(DataOutput out) throws IOException {
out.writeInt(VERSION_ADD_OEM_MANAGED_NETWORK); out.writeInt(VERSION_ADD_OEM_MANAGED_NETWORK);
out.writeInt(size()); out.writeInt(size());
for (NetworkIdentity ident : this) { for (NetworkIdentity ident : this) {
out.writeInt(ident.getType()); out.writeInt(ident.getType());
out.writeInt(ident.getSubType()); out.writeInt(ident.getRatType());
writeOptionalString(out, ident.getSubscriberId()); writeOptionalString(out, ident.getSubscriberId());
writeOptionalString(out, ident.getNetworkId()); writeOptionalString(out, ident.getWifiNetworkKey());
out.writeBoolean(ident.getRoaming()); out.writeBoolean(ident.getRoaming());
out.writeBoolean(ident.getMetered()); out.writeBoolean(ident.getMetered());
out.writeBoolean(ident.getDefaultNetwork()); out.writeBoolean(ident.getDefaultNetwork());
@@ -114,7 +123,10 @@ public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
} }
} }
/** @return whether any {@link NetworkIdentity} in this set is considered metered. */ /**
* @return whether any {@link NetworkIdentity} in this set is considered metered.
* @hide
*/
public boolean isAnyMemberMetered() { public boolean isAnyMemberMetered() {
if (isEmpty()) { if (isEmpty()) {
return false; return false;
@@ -127,7 +139,10 @@ public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
return false; return false;
} }
/** @return whether any {@link NetworkIdentity} in this set is considered roaming. */ /**
* @return whether any {@link NetworkIdentity} in this set is considered roaming.
* @hide
*/
public boolean isAnyMemberRoaming() { public boolean isAnyMemberRoaming() {
if (isEmpty()) { if (isEmpty()) {
return false; return false;
@@ -140,8 +155,11 @@ public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
return false; return false;
} }
/** @return whether any {@link NetworkIdentity} in this set is considered on the default /**
network. */ * @return whether any {@link NetworkIdentity} in this set is considered on the default
* network.
* @hide
*/
public boolean areAllMembersOnDefaultNetwork() { public boolean areAllMembersOnDefaultNetwork() {
if (isEmpty()) { if (isEmpty()) {
return true; return true;
@@ -172,7 +190,8 @@ public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
} }
@Override @Override
public int compareTo(NetworkIdentitySet another) { public int compareTo(@NonNull NetworkIdentitySet another) {
Objects.requireNonNull(another);
if (isEmpty()) return -1; if (isEmpty()) return -1;
if (another.isEmpty()) return 1; if (another.isEmpty()) return 1;
@@ -183,6 +202,7 @@ public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
/** /**
* Method to dump this object into proto debug file. * Method to dump this object into proto debug file.
* @hide
*/ */
public void dumpDebug(ProtoOutputStream proto, long tag) { public void dumpDebug(ProtoOutputStream proto, long tag) {
final long start = proto.start(tag); final long start = proto.start(tag);

View File

@@ -32,6 +32,8 @@ import static android.text.format.DateUtils.WEEK_IN_MILLIS;
import static com.android.net.module.util.NetworkStatsUtils.multiplySafeByRational; import static com.android.net.module.util.NetworkStatsUtils.multiplySafeByRational;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Binder; import android.os.Binder;
import android.service.NetworkStatsCollectionKeyProto; import android.service.NetworkStatsCollectionKeyProto;
import android.service.NetworkStatsCollectionProto; import android.service.NetworkStatsCollectionProto;
@@ -77,6 +79,7 @@ import java.util.Objects;
* *
* @hide * @hide
*/ */
// @SystemApi(client = MODULE_LIBRARIES)
public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.Writer { public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.Writer {
private static final String TAG = NetworkStatsCollection.class.getSimpleName(); private static final String TAG = NetworkStatsCollection.class.getSimpleName();
/** File header magic number: "ANET" */ /** File header magic number: "ANET" */
@@ -100,15 +103,23 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
private long mTotalBytes; private long mTotalBytes;
private boolean mDirty; private boolean mDirty;
/**
* Construct a {@link NetworkStatsCollection} object.
*
* @param bucketDuration duration of the buckets in this object, in milliseconds.
* @hide
*/
public NetworkStatsCollection(long bucketDuration) { public NetworkStatsCollection(long bucketDuration) {
mBucketDuration = bucketDuration; mBucketDuration = bucketDuration;
reset(); reset();
} }
/** @hide */
public void clear() { public void clear() {
reset(); reset();
} }
/** @hide */
public void reset() { public void reset() {
mStats.clear(); mStats.clear();
mStartMillis = Long.MAX_VALUE; mStartMillis = Long.MAX_VALUE;
@@ -117,6 +128,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
mDirty = false; mDirty = false;
} }
/** @hide */
public long getStartMillis() { public long getStartMillis() {
return mStartMillis; return mStartMillis;
} }
@@ -124,6 +136,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
/** /**
* Return first atomic bucket in this collection, which is more conservative * Return first atomic bucket in this collection, which is more conservative
* than {@link #mStartMillis}. * than {@link #mStartMillis}.
* @hide
*/ */
public long getFirstAtomicBucketMillis() { public long getFirstAtomicBucketMillis() {
if (mStartMillis == Long.MAX_VALUE) { if (mStartMillis == Long.MAX_VALUE) {
@@ -133,26 +146,32 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
} }
} }
/** @hide */
public long getEndMillis() { public long getEndMillis() {
return mEndMillis; return mEndMillis;
} }
/** @hide */
public long getTotalBytes() { public long getTotalBytes() {
return mTotalBytes; return mTotalBytes;
} }
/** @hide */
public boolean isDirty() { public boolean isDirty() {
return mDirty; return mDirty;
} }
/** @hide */
public void clearDirty() { public void clearDirty() {
mDirty = false; mDirty = false;
} }
/** @hide */
public boolean isEmpty() { public boolean isEmpty() {
return mStartMillis == Long.MAX_VALUE && mEndMillis == Long.MIN_VALUE; return mStartMillis == Long.MAX_VALUE && mEndMillis == Long.MIN_VALUE;
} }
/** @hide */
@VisibleForTesting @VisibleForTesting
public long roundUp(long time) { public long roundUp(long time) {
if (time == Long.MIN_VALUE || time == Long.MAX_VALUE if (time == Long.MIN_VALUE || time == Long.MAX_VALUE
@@ -168,6 +187,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
} }
} }
/** @hide */
@VisibleForTesting @VisibleForTesting
public long roundDown(long time) { public long roundDown(long time) {
if (time == Long.MIN_VALUE || time == Long.MAX_VALUE if (time == Long.MIN_VALUE || time == Long.MAX_VALUE
@@ -182,10 +202,12 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
} }
} }
/** @hide */
public int[] getRelevantUids(@NetworkStatsAccess.Level int accessLevel) { public int[] getRelevantUids(@NetworkStatsAccess.Level int accessLevel) {
return getRelevantUids(accessLevel, Binder.getCallingUid()); return getRelevantUids(accessLevel, Binder.getCallingUid());
} }
/** @hide */
public int[] getRelevantUids(@NetworkStatsAccess.Level int accessLevel, public int[] getRelevantUids(@NetworkStatsAccess.Level int accessLevel,
final int callerUid) { final int callerUid) {
final ArrayList<Integer> uids = new ArrayList<>(); final ArrayList<Integer> uids = new ArrayList<>();
@@ -206,6 +228,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
/** /**
* Combine all {@link NetworkStatsHistory} in this collection which match * Combine all {@link NetworkStatsHistory} in this collection which match
* the requested parameters. * the requested parameters.
* @hide
*/ */
public NetworkStatsHistory getHistory(NetworkTemplate template, SubscriptionPlan augmentPlan, public NetworkStatsHistory getHistory(NetworkTemplate template, SubscriptionPlan augmentPlan,
int uid, int set, int tag, int fields, long start, long end, int uid, int set, int tag, int fields, long start, long end,
@@ -331,6 +354,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
* @param end - end of the range, timestamp in milliseconds since the epoch. * @param end - end of the range, timestamp in milliseconds since the epoch.
* @param accessLevel - caller access level. * @param accessLevel - caller access level.
* @param callerUid - caller UID. * @param callerUid - caller UID.
* @hide
*/ */
public NetworkStats getSummary(NetworkTemplate template, long start, long end, public NetworkStats getSummary(NetworkTemplate template, long start, long end,
@NetworkStatsAccess.Level int accessLevel, int callerUid) { @NetworkStatsAccess.Level int accessLevel, int callerUid) {
@@ -377,6 +401,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
/** /**
* Record given {@link android.net.NetworkStats.Entry} into this collection. * Record given {@link android.net.NetworkStats.Entry} into this collection.
* @hide
*/ */
public void recordData(NetworkIdentitySet ident, int uid, int set, int tag, long start, public void recordData(NetworkIdentitySet ident, int uid, int set, int tag, long start,
long end, NetworkStats.Entry entry) { long end, NetworkStats.Entry entry) {
@@ -387,8 +412,12 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
/** /**
* Record given {@link NetworkStatsHistory} into this collection. * Record given {@link NetworkStatsHistory} into this collection.
*
* @hide
*/ */
private void recordHistory(Key key, NetworkStatsHistory history) { public void recordHistory(@NonNull Key key, @NonNull NetworkStatsHistory history) {
Objects.requireNonNull(key);
Objects.requireNonNull(history);
if (history.size() == 0) return; if (history.size() == 0) return;
noteRecordedHistory(history.getStart(), history.getEnd(), history.getTotalBytes()); noteRecordedHistory(history.getStart(), history.getEnd(), history.getTotalBytes());
@@ -403,8 +432,11 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
/** /**
* Record all {@link NetworkStatsHistory} contained in the given collection * Record all {@link NetworkStatsHistory} contained in the given collection
* into this collection. * into this collection.
*
* @hide
*/ */
public void recordCollection(NetworkStatsCollection another) { public void recordCollection(@NonNull NetworkStatsCollection another) {
Objects.requireNonNull(another);
for (int i = 0; i < another.mStats.size(); i++) { for (int i = 0; i < another.mStats.size(); i++) {
final Key key = another.mStats.keyAt(i); final Key key = another.mStats.keyAt(i);
final NetworkStatsHistory value = another.mStats.valueAt(i); final NetworkStatsHistory value = another.mStats.valueAt(i);
@@ -433,6 +465,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
} }
} }
/** @hide */
@Override @Override
public void read(InputStream in) throws IOException { public void read(InputStream in) throws IOException {
read((DataInput) new DataInputStream(in)); read((DataInput) new DataInputStream(in));
@@ -472,6 +505,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
} }
} }
/** @hide */
@Override @Override
public void write(OutputStream out) throws IOException { public void write(OutputStream out) throws IOException {
write((DataOutput) new DataOutputStream(out)); write((DataOutput) new DataOutputStream(out));
@@ -514,6 +548,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
* See {@code NetworkStatsService#maybeUpgradeLegacyStatsLocked}. * See {@code NetworkStatsService#maybeUpgradeLegacyStatsLocked}.
* *
* @deprecated * @deprecated
* @hide
*/ */
@Deprecated @Deprecated
public void readLegacyNetwork(File file) throws IOException { public void readLegacyNetwork(File file) throws IOException {
@@ -559,6 +594,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
* See {@code NetworkStatsService#maybeUpgradeLegacyStatsLocked}. * See {@code NetworkStatsService#maybeUpgradeLegacyStatsLocked}.
* *
* @deprecated * @deprecated
* @hide
*/ */
@Deprecated @Deprecated
public void readLegacyUid(File file, boolean onlyTags) throws IOException { public void readLegacyUid(File file, boolean onlyTags) throws IOException {
@@ -629,6 +665,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
* Remove any {@link NetworkStatsHistory} attributed to the requested UID, * Remove any {@link NetworkStatsHistory} attributed to the requested UID,
* moving any {@link NetworkStats#TAG_NONE} series to * moving any {@link NetworkStats#TAG_NONE} series to
* {@link TrafficStats#UID_REMOVED}. * {@link TrafficStats#UID_REMOVED}.
* @hide
*/ */
public void removeUids(int[] uids) { public void removeUids(int[] uids) {
final ArrayList<Key> knownKeys = new ArrayList<>(); final ArrayList<Key> knownKeys = new ArrayList<>();
@@ -669,6 +706,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
return keys; return keys;
} }
/** @hide */
public void dump(IndentingPrintWriter pw) { public void dump(IndentingPrintWriter pw) {
for (Key key : getSortedKeys()) { for (Key key : getSortedKeys()) {
pw.print("ident="); pw.print(key.ident.toString()); pw.print("ident="); pw.print(key.ident.toString());
@@ -683,6 +721,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
} }
} }
/** @hide */
public void dumpDebug(ProtoOutputStream proto, long tag) { public void dumpDebug(ProtoOutputStream proto, long tag) {
final long start = proto.start(tag); final long start = proto.start(tag);
@@ -706,6 +745,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
proto.end(start); proto.end(start);
} }
/** @hide */
public void dumpCheckin(PrintWriter pw, long start, long end) { public void dumpCheckin(PrintWriter pw, long start, long end) {
dumpCheckin(pw, start, end, NetworkTemplate.buildTemplateMobileWildcard(), "cell"); dumpCheckin(pw, start, end, NetworkTemplate.buildTemplateMobileWildcard(), "cell");
dumpCheckin(pw, start, end, NetworkTemplate.buildTemplateWifiWildcard(), "wifi"); dumpCheckin(pw, start, end, NetworkTemplate.buildTemplateWifiWildcard(), "wifi");
@@ -768,16 +808,32 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
return false; return false;
} }
private static class Key implements Comparable<Key> { /**
* the identifier that associate with the {@link NetworkStatsHistory} object to identify
* a certain record in the {@link NetworkStatsCollection} object.
*/
public static class Key implements Comparable<Key> {
/** @hide */
public final NetworkIdentitySet ident; public final NetworkIdentitySet ident;
/** @hide */
public final int uid; public final int uid;
/** @hide */
public final int set; public final int set;
/** @hide */
public final int tag; public final int tag;
private final int mHashCode; private final int mHashCode;
Key(NetworkIdentitySet ident, int uid, int set, int tag) { /**
this.ident = ident; * Construct a {@link Key} object.
*
* @param ident a Set of {@link NetworkIdentity} that associated with the record.
* @param uid Uid of the record.
* @param set Set of the record, see {@code NetworkStats#SET_*}.
* @param tag Tag of the record, see {@link TrafficStats#setThreadStatsTag(int)}.
*/
public Key(@NonNull NetworkIdentitySet ident, int uid, int set, int tag) {
this.ident = Objects.requireNonNull(ident);
this.uid = uid; this.uid = uid;
this.set = set; this.set = set;
this.tag = tag; this.tag = tag;
@@ -790,7 +846,7 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(@Nullable Object obj) {
if (obj instanceof Key) { if (obj instanceof Key) {
final Key key = (Key) obj; final Key key = (Key) obj;
return uid == key.uid && set == key.set && tag == key.tag return uid == key.uid && set == key.set && tag == key.tag
@@ -800,7 +856,8 @@ public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.W
} }
@Override @Override
public int compareTo(Key another) { public int compareTo(@NonNull Key another) {
Objects.requireNonNull(another);
int res = 0; int res = 0;
if (ident != null && another.ident != null) { if (ident != null && another.ident != null) {
res = ident.compareTo(another.ident); res = ident.compareTo(another.ident);

View File

@@ -30,6 +30,7 @@ import static android.text.format.DateUtils.SECOND_IN_MILLIS;
import static com.android.net.module.util.NetworkStatsUtils.multiplySafeByRational; import static com.android.net.module.util.NetworkStatsUtils.multiplySafeByRational;
import android.annotation.NonNull;
import android.compat.annotation.UnsupportedAppUsage; import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build; import android.os.Build;
import android.os.Parcel; import android.os.Parcel;
@@ -64,18 +65,25 @@ import java.util.Random;
* *
* @hide * @hide
*/ */
public class NetworkStatsHistory implements Parcelable { // @SystemApi(client = MODULE_LIBRARIES)
public final class NetworkStatsHistory implements Parcelable {
private static final int VERSION_INIT = 1; private static final int VERSION_INIT = 1;
private static final int VERSION_ADD_PACKETS = 2; private static final int VERSION_ADD_PACKETS = 2;
private static final int VERSION_ADD_ACTIVE = 3; private static final int VERSION_ADD_ACTIVE = 3;
/** @hide */
public static final int FIELD_ACTIVE_TIME = 0x01; public static final int FIELD_ACTIVE_TIME = 0x01;
/** @hide */
public static final int FIELD_RX_BYTES = 0x02; public static final int FIELD_RX_BYTES = 0x02;
/** @hide */
public static final int FIELD_RX_PACKETS = 0x04; public static final int FIELD_RX_PACKETS = 0x04;
/** @hide */
public static final int FIELD_TX_BYTES = 0x08; public static final int FIELD_TX_BYTES = 0x08;
/** @hide */
public static final int FIELD_TX_PACKETS = 0x10; public static final int FIELD_TX_PACKETS = 0x10;
/** @hide */
public static final int FIELD_OPERATIONS = 0x20; public static final int FIELD_OPERATIONS = 0x20;
/** @hide */
public static final int FIELD_ALL = 0xFFFFFFFF; public static final int FIELD_ALL = 0xFFFFFFFF;
private long bucketDuration; private long bucketDuration;
@@ -108,15 +116,18 @@ public class NetworkStatsHistory implements Parcelable {
public long operations; public long operations;
} }
/** @hide */
@UnsupportedAppUsage @UnsupportedAppUsage
public NetworkStatsHistory(long bucketDuration) { public NetworkStatsHistory(long bucketDuration) {
this(bucketDuration, 10, FIELD_ALL); this(bucketDuration, 10, FIELD_ALL);
} }
/** @hide */
public NetworkStatsHistory(long bucketDuration, int initialSize) { public NetworkStatsHistory(long bucketDuration, int initialSize) {
this(bucketDuration, initialSize, FIELD_ALL); this(bucketDuration, initialSize, FIELD_ALL);
} }
/** @hide */
public NetworkStatsHistory(long bucketDuration, int initialSize, int fields) { public NetworkStatsHistory(long bucketDuration, int initialSize, int fields) {
this.bucketDuration = bucketDuration; this.bucketDuration = bucketDuration;
bucketStart = new long[initialSize]; bucketStart = new long[initialSize];
@@ -130,11 +141,13 @@ public class NetworkStatsHistory implements Parcelable {
totalBytes = 0; totalBytes = 0;
} }
/** @hide */
public NetworkStatsHistory(NetworkStatsHistory existing, long bucketDuration) { public NetworkStatsHistory(NetworkStatsHistory existing, long bucketDuration) {
this(bucketDuration, existing.estimateResizeBuckets(bucketDuration)); this(bucketDuration, existing.estimateResizeBuckets(bucketDuration));
recordEntireHistory(existing); recordEntireHistory(existing);
} }
/** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public NetworkStatsHistory(Parcel in) { public NetworkStatsHistory(Parcel in) {
bucketDuration = in.readLong(); bucketDuration = in.readLong();
@@ -150,7 +163,7 @@ public class NetworkStatsHistory implements Parcelable {
} }
@Override @Override
public void writeToParcel(Parcel out, int flags) { public void writeToParcel(@NonNull Parcel out, int flags) {
out.writeLong(bucketDuration); out.writeLong(bucketDuration);
writeLongArray(out, bucketStart, bucketCount); writeLongArray(out, bucketStart, bucketCount);
writeLongArray(out, activeTime, bucketCount); writeLongArray(out, activeTime, bucketCount);
@@ -162,6 +175,7 @@ public class NetworkStatsHistory implements Parcelable {
out.writeLong(totalBytes); out.writeLong(totalBytes);
} }
/** @hide */
public NetworkStatsHistory(DataInput in) throws IOException { public NetworkStatsHistory(DataInput in) throws IOException {
final int version = in.readInt(); final int version = in.readInt();
switch (version) { switch (version) {
@@ -204,6 +218,7 @@ public class NetworkStatsHistory implements Parcelable {
} }
} }
/** @hide */
public void writeToStream(DataOutput out) throws IOException { public void writeToStream(DataOutput out) throws IOException {
out.writeInt(VERSION_ADD_ACTIVE); out.writeInt(VERSION_ADD_ACTIVE);
out.writeLong(bucketDuration); out.writeLong(bucketDuration);
@@ -221,15 +236,18 @@ public class NetworkStatsHistory implements Parcelable {
return 0; return 0;
} }
/** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public int size() { public int size() {
return bucketCount; return bucketCount;
} }
/** @hide */
public long getBucketDuration() { public long getBucketDuration() {
return bucketDuration; return bucketDuration;
} }
/** @hide */
@UnsupportedAppUsage @UnsupportedAppUsage
public long getStart() { public long getStart() {
if (bucketCount > 0) { if (bucketCount > 0) {
@@ -239,6 +257,7 @@ public class NetworkStatsHistory implements Parcelable {
} }
} }
/** @hide */
@UnsupportedAppUsage @UnsupportedAppUsage
public long getEnd() { public long getEnd() {
if (bucketCount > 0) { if (bucketCount > 0) {
@@ -250,6 +269,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Return total bytes represented by this history. * Return total bytes represented by this history.
* @hide
*/ */
public long getTotalBytes() { public long getTotalBytes() {
return totalBytes; return totalBytes;
@@ -258,6 +278,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Return index of bucket that contains or is immediately before the * Return index of bucket that contains or is immediately before the
* requested time. * requested time.
* @hide
*/ */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public int getIndexBefore(long time) { public int getIndexBefore(long time) {
@@ -273,6 +294,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Return index of bucket that contains or is immediately after the * Return index of bucket that contains or is immediately after the
* requested time. * requested time.
* @hide
*/ */
public int getIndexAfter(long time) { public int getIndexAfter(long time) {
int index = Arrays.binarySearch(bucketStart, 0, bucketCount, time); int index = Arrays.binarySearch(bucketStart, 0, bucketCount, time);
@@ -286,6 +308,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Return specific stats entry. * Return specific stats entry.
* @hide
*/ */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public Entry getValues(int i, Entry recycle) { public Entry getValues(int i, Entry recycle) {
@@ -301,6 +324,7 @@ public class NetworkStatsHistory implements Parcelable {
return entry; return entry;
} }
/** @hide */
public void setValues(int i, Entry entry) { public void setValues(int i, Entry entry) {
// Unwind old values // Unwind old values
if (rxBytes != null) totalBytes -= rxBytes[i]; if (rxBytes != null) totalBytes -= rxBytes[i];
@@ -322,6 +346,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Record that data traffic occurred in the given time range. Will * Record that data traffic occurred in the given time range. Will
* distribute across internal buckets, creating new buckets as needed. * distribute across internal buckets, creating new buckets as needed.
* @hide
*/ */
@Deprecated @Deprecated
public void recordData(long start, long end, long rxBytes, long txBytes) { public void recordData(long start, long end, long rxBytes, long txBytes) {
@@ -332,6 +357,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Record that data traffic occurred in the given time range. Will * Record that data traffic occurred in the given time range. Will
* distribute across internal buckets, creating new buckets as needed. * distribute across internal buckets, creating new buckets as needed.
* @hide
*/ */
public void recordData(long start, long end, NetworkStats.Entry entry) { public void recordData(long start, long end, NetworkStats.Entry entry) {
long rxBytes = entry.rxBytes; long rxBytes = entry.rxBytes;
@@ -392,6 +418,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Record an entire {@link NetworkStatsHistory} into this history. Usually * Record an entire {@link NetworkStatsHistory} into this history. Usually
* for combining together stats for external reporting. * for combining together stats for external reporting.
* @hide
*/ */
@UnsupportedAppUsage @UnsupportedAppUsage
public void recordEntireHistory(NetworkStatsHistory input) { public void recordEntireHistory(NetworkStatsHistory input) {
@@ -402,6 +429,7 @@ public class NetworkStatsHistory implements Parcelable {
* Record given {@link NetworkStatsHistory} into this history, copying only * Record given {@link NetworkStatsHistory} into this history, copying only
* buckets that atomically occur in the inclusive time range. Doesn't * buckets that atomically occur in the inclusive time range. Doesn't
* interpolate across partial buckets. * interpolate across partial buckets.
* @hide
*/ */
public void recordHistory(NetworkStatsHistory input, long start, long end) { public void recordHistory(NetworkStatsHistory input, long start, long end) {
final NetworkStats.Entry entry = new NetworkStats.Entry( final NetworkStats.Entry entry = new NetworkStats.Entry(
@@ -483,6 +511,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Clear all data stored in this object. * Clear all data stored in this object.
* @hide
*/ */
public void clear() { public void clear() {
bucketStart = EmptyArray.LONG; bucketStart = EmptyArray.LONG;
@@ -498,9 +527,10 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Remove buckets older than requested cutoff. * Remove buckets older than requested cutoff.
* @hide
*/ */
@Deprecated
public void removeBucketsBefore(long cutoff) { public void removeBucketsBefore(long cutoff) {
// TODO: Consider use getIndexBefore.
int i; int i;
for (i = 0; i < bucketCount; i++) { for (i = 0; i < bucketCount; i++) {
final long curStart = bucketStart[i]; final long curStart = bucketStart[i];
@@ -522,7 +552,9 @@ public class NetworkStatsHistory implements Parcelable {
if (operations != null) operations = Arrays.copyOfRange(operations, i, length); if (operations != null) operations = Arrays.copyOfRange(operations, i, length);
bucketCount -= i; bucketCount -= i;
// TODO: subtract removed values from totalBytes totalBytes = 0;
if (rxBytes != null) totalBytes += CollectionUtils.total(rxBytes);
if (txBytes != null) totalBytes += CollectionUtils.total(txBytes);
} }
} }
@@ -536,6 +568,7 @@ public class NetworkStatsHistory implements Parcelable {
* @param start - start of the range, timestamp in milliseconds since the epoch. * @param start - start of the range, timestamp in milliseconds since the epoch.
* @param end - end of the range, timestamp in milliseconds since the epoch. * @param end - end of the range, timestamp in milliseconds since the epoch.
* @param recycle - entry instance for performance, could be null. * @param recycle - entry instance for performance, could be null.
* @hide
*/ */
@UnsupportedAppUsage @UnsupportedAppUsage
public Entry getValues(long start, long end, Entry recycle) { public Entry getValues(long start, long end, Entry recycle) {
@@ -550,6 +583,7 @@ public class NetworkStatsHistory implements Parcelable {
* @param end - end of the range, timestamp in milliseconds since the epoch. * @param end - end of the range, timestamp in milliseconds since the epoch.
* @param now - current timestamp in milliseconds since the epoch (wall clock). * @param now - current timestamp in milliseconds since the epoch (wall clock).
* @param recycle - entry instance for performance, could be null. * @param recycle - entry instance for performance, could be null.
* @hide
*/ */
@UnsupportedAppUsage @UnsupportedAppUsage
public Entry getValues(long start, long end, long now, Entry recycle) { public Entry getValues(long start, long end, long now, Entry recycle) {
@@ -613,6 +647,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* @deprecated only for temporary testing * @deprecated only for temporary testing
* @hide
*/ */
@Deprecated @Deprecated
public void generateRandom(long start, long end, long bytes) { public void generateRandom(long start, long end, long bytes) {
@@ -631,6 +666,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* @deprecated only for temporary testing * @deprecated only for temporary testing
* @hide
*/ */
@Deprecated @Deprecated
public void generateRandom(long start, long end, long rxBytes, long rxPackets, long txBytes, public void generateRandom(long start, long end, long rxBytes, long rxPackets, long txBytes,
@@ -660,12 +696,14 @@ public class NetworkStatsHistory implements Parcelable {
} }
} }
/** @hide */
public static long randomLong(Random r, long start, long end) { public static long randomLong(Random r, long start, long end) {
return (long) (start + (r.nextFloat() * (end - start))); return (long) (start + (r.nextFloat() * (end - start)));
} }
/** /**
* Quickly determine if this history intersects with given window. * Quickly determine if this history intersects with given window.
* @hide
*/ */
public boolean intersects(long start, long end) { public boolean intersects(long start, long end) {
final long dataStart = getStart(); final long dataStart = getStart();
@@ -677,6 +715,7 @@ public class NetworkStatsHistory implements Parcelable {
return false; return false;
} }
/** @hide */
public void dump(IndentingPrintWriter pw, boolean fullHistory) { public void dump(IndentingPrintWriter pw, boolean fullHistory) {
pw.print("NetworkStatsHistory: bucketDuration="); pw.print("NetworkStatsHistory: bucketDuration=");
pw.println(bucketDuration / SECOND_IN_MILLIS); pw.println(bucketDuration / SECOND_IN_MILLIS);
@@ -700,6 +739,7 @@ public class NetworkStatsHistory implements Parcelable {
pw.decreaseIndent(); pw.decreaseIndent();
} }
/** @hide */
public void dumpCheckin(PrintWriter pw) { public void dumpCheckin(PrintWriter pw) {
pw.print("d,"); pw.print("d,");
pw.print(bucketDuration / SECOND_IN_MILLIS); pw.print(bucketDuration / SECOND_IN_MILLIS);
@@ -717,6 +757,7 @@ public class NetworkStatsHistory implements Parcelable {
} }
} }
/** @hide */
public void dumpDebug(ProtoOutputStream proto, long tag) { public void dumpDebug(ProtoOutputStream proto, long tag) {
final long start = proto.start(tag); final long start = proto.start(tag);
@@ -776,6 +817,7 @@ public class NetworkStatsHistory implements Parcelable {
if (array != null) array[i] += value; if (array != null) array[i] += value;
} }
/** @hide */
public int estimateResizeBuckets(long newBucketDuration) { public int estimateResizeBuckets(long newBucketDuration) {
return (int) (size() * getBucketDuration() / newBucketDuration); return (int) (size() * getBucketDuration() / newBucketDuration);
} }
@@ -783,6 +825,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Utility methods for interacting with {@link DataInputStream} and * Utility methods for interacting with {@link DataInputStream} and
* {@link DataOutputStream}, mostly dealing with writing partial arrays. * {@link DataOutputStream}, mostly dealing with writing partial arrays.
* @hide
*/ */
public static class DataStreamUtils { public static class DataStreamUtils {
@Deprecated @Deprecated
@@ -857,6 +900,7 @@ public class NetworkStatsHistory implements Parcelable {
/** /**
* Utility methods for interacting with {@link Parcel} structures, mostly * Utility methods for interacting with {@link Parcel} structures, mostly
* dealing with writing partial arrays. * dealing with writing partial arrays.
* @hide
*/ */
public static class ParcelUtils { public static class ParcelUtils {
public static long[] readLongArray(Parcel in) { public static long[] readLongArray(Parcel in) {

View File

@@ -364,7 +364,7 @@ public final class NetworkTemplate implements Parcelable {
private final int mMetered; private final int mMetered;
private final int mRoaming; private final int mRoaming;
private final int mDefaultNetwork; private final int mDefaultNetwork;
private final int mSubType; private final int mRatType;
/** /**
* The subscriber Id match rule defines how the template should match networks with * The subscriber Id match rule defines how the template should match networks with
* specific subscriberId(s). See NetworkTemplate#SUBSCRIBER_ID_MATCH_RULE_* for more detail. * specific subscriberId(s). See NetworkTemplate#SUBSCRIBER_ID_MATCH_RULE_* for more detail.
@@ -413,18 +413,18 @@ public final class NetworkTemplate implements Parcelable {
/** @hide */ /** @hide */
// TODO: Remove it after updating all of the caller. // TODO: Remove it after updating all of the caller.
public NetworkTemplate(int matchRule, String subscriberId, String[] matchSubscriberIds, public NetworkTemplate(int matchRule, String subscriberId, String[] matchSubscriberIds,
String wifiNetworkKey, int metered, int roaming, int defaultNetwork, int subType, String wifiNetworkKey, int metered, int roaming, int defaultNetwork, int ratType,
int oemManaged) { int oemManaged) {
this(matchRule, subscriberId, matchSubscriberIds, this(matchRule, subscriberId, matchSubscriberIds,
wifiNetworkKey != null ? new String[] { wifiNetworkKey } : new String[0], wifiNetworkKey != null ? new String[] { wifiNetworkKey } : new String[0],
metered, roaming, defaultNetwork, subType, oemManaged, metered, roaming, defaultNetwork, ratType, oemManaged,
NetworkStatsUtils.SUBSCRIBER_ID_MATCH_RULE_EXACT); NetworkStatsUtils.SUBSCRIBER_ID_MATCH_RULE_EXACT);
} }
/** @hide */ /** @hide */
public NetworkTemplate(int matchRule, String subscriberId, String[] matchSubscriberIds, public NetworkTemplate(int matchRule, String subscriberId, String[] matchSubscriberIds,
String[] matchWifiNetworkKeys, int metered, int roaming, String[] matchWifiNetworkKeys, int metered, int roaming,
int defaultNetwork, int subType, int oemManaged, int subscriberIdMatchRule) { int defaultNetwork, int ratType, int oemManaged, int subscriberIdMatchRule) {
Objects.requireNonNull(matchWifiNetworkKeys); Objects.requireNonNull(matchWifiNetworkKeys);
mMatchRule = matchRule; mMatchRule = matchRule;
mSubscriberId = subscriberId; mSubscriberId = subscriberId;
@@ -435,7 +435,7 @@ public final class NetworkTemplate implements Parcelable {
mMetered = metered; mMetered = metered;
mRoaming = roaming; mRoaming = roaming;
mDefaultNetwork = defaultNetwork; mDefaultNetwork = defaultNetwork;
mSubType = subType; mRatType = ratType;
mOemManaged = oemManaged; mOemManaged = oemManaged;
mSubscriberIdMatchRule = subscriberIdMatchRule; mSubscriberIdMatchRule = subscriberIdMatchRule;
checkValidSubscriberIdMatchRule(matchRule, subscriberIdMatchRule); checkValidSubscriberIdMatchRule(matchRule, subscriberIdMatchRule);
@@ -453,7 +453,7 @@ public final class NetworkTemplate implements Parcelable {
mMetered = in.readInt(); mMetered = in.readInt();
mRoaming = in.readInt(); mRoaming = in.readInt();
mDefaultNetwork = in.readInt(); mDefaultNetwork = in.readInt();
mSubType = in.readInt(); mRatType = in.readInt();
mOemManaged = in.readInt(); mOemManaged = in.readInt();
mSubscriberIdMatchRule = in.readInt(); mSubscriberIdMatchRule = in.readInt();
} }
@@ -467,7 +467,7 @@ public final class NetworkTemplate implements Parcelable {
dest.writeInt(mMetered); dest.writeInt(mMetered);
dest.writeInt(mRoaming); dest.writeInt(mRoaming);
dest.writeInt(mDefaultNetwork); dest.writeInt(mDefaultNetwork);
dest.writeInt(mSubType); dest.writeInt(mRatType);
dest.writeInt(mOemManaged); dest.writeInt(mOemManaged);
dest.writeInt(mSubscriberIdMatchRule); dest.writeInt(mSubscriberIdMatchRule);
} }
@@ -500,8 +500,8 @@ public final class NetworkTemplate implements Parcelable {
builder.append(", defaultNetwork=").append(NetworkStats.defaultNetworkToString( builder.append(", defaultNetwork=").append(NetworkStats.defaultNetworkToString(
mDefaultNetwork)); mDefaultNetwork));
} }
if (mSubType != NETWORK_TYPE_ALL) { if (mRatType != NETWORK_TYPE_ALL) {
builder.append(", subType=").append(mSubType); builder.append(", ratType=").append(mRatType);
} }
if (mOemManaged != OEM_MANAGED_ALL) { if (mOemManaged != OEM_MANAGED_ALL) {
builder.append(", oemManaged=").append(getOemManagedNames(mOemManaged)); builder.append(", oemManaged=").append(getOemManagedNames(mOemManaged));
@@ -514,7 +514,7 @@ public final class NetworkTemplate implements Parcelable {
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(mMatchRule, mSubscriberId, Arrays.hashCode(mMatchWifiNetworkKeys), return Objects.hash(mMatchRule, mSubscriberId, Arrays.hashCode(mMatchWifiNetworkKeys),
mMetered, mRoaming, mDefaultNetwork, mSubType, mOemManaged, mSubscriberIdMatchRule); mMetered, mRoaming, mDefaultNetwork, mRatType, mOemManaged, mSubscriberIdMatchRule);
} }
@Override @Override
@@ -526,7 +526,7 @@ public final class NetworkTemplate implements Parcelable {
&& mMetered == other.mMetered && mMetered == other.mMetered
&& mRoaming == other.mRoaming && mRoaming == other.mRoaming
&& mDefaultNetwork == other.mDefaultNetwork && mDefaultNetwork == other.mDefaultNetwork
&& mSubType == other.mSubType && mRatType == other.mRatType
&& mOemManaged == other.mOemManaged && mOemManaged == other.mOemManaged
&& mSubscriberIdMatchRule == other.mSubscriberIdMatchRule && mSubscriberIdMatchRule == other.mSubscriberIdMatchRule
&& Arrays.equals(mMatchWifiNetworkKeys, other.mMatchWifiNetworkKeys); && Arrays.equals(mMatchWifiNetworkKeys, other.mMatchWifiNetworkKeys);
@@ -635,7 +635,7 @@ public final class NetworkTemplate implements Parcelable {
* Get the Radio Access Technology(RAT) type filter of the template. * Get the Radio Access Technology(RAT) type filter of the template.
*/ */
public int getRatType() { public int getRatType() {
return mSubType; return mRatType;
} }
/** /**
@@ -708,8 +708,8 @@ public final class NetworkTemplate implements Parcelable {
} }
private boolean matchesCollapsedRatType(NetworkIdentity ident) { private boolean matchesCollapsedRatType(NetworkIdentity ident) {
return mSubType == NETWORK_TYPE_ALL return mRatType == NETWORK_TYPE_ALL
|| getCollapsedRatType(mSubType) == getCollapsedRatType(ident.mSubType); || getCollapsedRatType(mRatType) == getCollapsedRatType(ident.mRatType);
} }
/** /**
@@ -837,7 +837,7 @@ public final class NetworkTemplate implements Parcelable {
switch (ident.mType) { switch (ident.mType) {
case TYPE_WIFI: case TYPE_WIFI:
return matchesSubscriberId(ident.mSubscriberId) return matchesSubscriberId(ident.mSubscriberId)
&& matchesWifiNetworkKey(ident.mNetworkId); && matchesWifiNetworkKey(ident.mWifiNetworkKey);
default: default:
return false; return false;
} }

View File

@@ -19,12 +19,15 @@ package com.android.server.net;
import static android.Manifest.permission.NETWORK_STATS_PROVIDER; import static android.Manifest.permission.NETWORK_STATS_PROVIDER;
import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY; import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
import static android.Manifest.permission.UPDATE_DEVICE_STATS; import static android.Manifest.permission.UPDATE_DEVICE_STATS;
import static android.app.usage.NetworkStatsManager.PREFIX_DEV;
import static android.app.usage.NetworkStatsManager.PREFIX_UID;
import static android.app.usage.NetworkStatsManager.PREFIX_UID_TAG;
import static android.app.usage.NetworkStatsManager.PREFIX_XT;
import static android.content.Intent.ACTION_SHUTDOWN; import static android.content.Intent.ACTION_SHUTDOWN;
import static android.content.Intent.ACTION_UID_REMOVED; import static android.content.Intent.ACTION_UID_REMOVED;
import static android.content.Intent.ACTION_USER_REMOVED; import static android.content.Intent.ACTION_USER_REMOVED;
import static android.content.Intent.EXTRA_UID; import static android.content.Intent.EXTRA_UID;
import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.net.NetworkIdentity.SUBTYPE_COMBINED;
import static android.net.NetworkStats.DEFAULT_NETWORK_ALL; import static android.net.NetworkStats.DEFAULT_NETWORK_ALL;
import static android.net.NetworkStats.IFACE_ALL; import static android.net.NetworkStats.IFACE_ALL;
import static android.net.NetworkStats.IFACE_VT; import static android.net.NetworkStats.IFACE_VT;
@@ -243,11 +246,6 @@ public class NetworkStatsService extends INetworkStatsService.Stub {
private PendingIntent mPollIntent; private PendingIntent mPollIntent;
private static final String PREFIX_DEV = "dev";
private static final String PREFIX_XT = "xt";
private static final String PREFIX_UID = "uid";
private static final String PREFIX_UID_TAG = "uid_tag";
/** /**
* Settings that can be changed externally. * Settings that can be changed externally.
*/ */
@@ -257,9 +255,9 @@ public class NetworkStatsService extends INetworkStatsService.Stub {
boolean getSampleEnabled(); boolean getSampleEnabled();
boolean getAugmentEnabled(); boolean getAugmentEnabled();
/** /**
* When enabled, all mobile data is reported under {@link NetworkIdentity#SUBTYPE_COMBINED}. * When enabled, all mobile data is reported under {@link NetworkTemplate#NETWORK_TYPE_ALL}.
* When disabled, mobile data is broken down by a granular subtype representative of the * When disabled, mobile data is broken down by a granular ratType representative of the
* actual subtype. {@see NetworkTemplate#getCollapsedRatType}. * actual ratType. {@see NetworkTemplate#getCollapsedRatType}.
* Enabling this decreases the level of detail but saves performance, disk space and * Enabling this decreases the level of detail but saves performance, disk space and
* amount of data logged. * amount of data logged.
*/ */
@@ -1389,10 +1387,10 @@ public class NetworkStatsService extends INetworkStatsService.Stub {
final boolean isMobile = (NetworkCapabilities.TRANSPORT_CELLULAR == displayTransport); final boolean isMobile = (NetworkCapabilities.TRANSPORT_CELLULAR == displayTransport);
final boolean isDefault = CollectionUtils.contains( final boolean isDefault = CollectionUtils.contains(
mDefaultNetworks, snapshot.getNetwork()); mDefaultNetworks, snapshot.getNetwork());
final int subType = combineSubtypeEnabled ? SUBTYPE_COMBINED final int ratType = combineSubtypeEnabled ? NetworkTemplate.NETWORK_TYPE_ALL
: getSubTypeForStateSnapshot(snapshot); : getRatTypeForStateSnapshot(snapshot);
final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, snapshot, final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, snapshot,
isDefault, subType); isDefault, ratType);
// Traffic occurring on the base interface is always counted for // Traffic occurring on the base interface is always counted for
// both total usage and UID details. // both total usage and UID details.
@@ -1411,7 +1409,7 @@ public class NetworkStatsService extends INetworkStatsService.Stub {
// Copy the identify from IMS one but mark it as metered. // Copy the identify from IMS one but mark it as metered.
NetworkIdentity vtIdent = new NetworkIdentity(ident.getType(), NetworkIdentity vtIdent = new NetworkIdentity(ident.getType(),
ident.getSubType(), ident.getSubscriberId(), ident.getNetworkId(), ident.getRatType(), ident.getSubscriberId(), ident.getWifiNetworkKey(),
ident.getRoaming(), true /* metered */, ident.getRoaming(), true /* metered */,
true /* onDefaultNetwork */, ident.getOemManaged()); true /* onDefaultNetwork */, ident.getOemManaged());
final String ifaceVt = IFACE_VT + getSubIdForMobile(snapshot); final String ifaceVt = IFACE_VT + getSubIdForMobile(snapshot);
@@ -1492,11 +1490,11 @@ public class NetworkStatsService extends INetworkStatsService.Stub {
} }
/** /**
* For networks with {@code TRANSPORT_CELLULAR}, get subType that was obtained through * For networks with {@code TRANSPORT_CELLULAR}, get ratType that was obtained through
* {@link PhoneStateListener}. Otherwise, return 0 given that other networks with different * {@link PhoneStateListener}. Otherwise, return 0 given that other networks with different
* transport types do not actually fill this value. * transport types do not actually fill this value.
*/ */
private int getSubTypeForStateSnapshot(@NonNull NetworkStateSnapshot state) { private int getRatTypeForStateSnapshot(@NonNull NetworkStateSnapshot state) {
if (!state.getNetworkCapabilities().hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { if (!state.getNetworkCapabilities().hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return 0; return 0;
} }