2 * Copyright (C) 2011 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 import android.os.Parcel;
20 import android.os.Parcelable;
21 import android.os.SystemClock;
22 import android.util.Slog;
23 import android.util.SparseBooleanArray;
25 import com.android.internal.annotations.VisibleForTesting;
26 import com.android.internal.util.ArrayUtils;
28 import libcore.util.EmptyArray;
30 import java.io.CharArrayWriter;
31 import java.io.PrintWriter;
32 import java.util.Arrays;
33 import java.util.HashSet;
34 import java.util.Objects;
37 * Collection of active network statistics. Can contain summary details across
38 * all interfaces, or details with per-UID granularity. Internally stores data
39 * as a large table, closely matching {@code /proc/} data format. This structure
40 * optimizes for rapid in-memory comparison, but consider using
41 * {@link NetworkStatsHistory} when persisting.
45 public class NetworkStats implements Parcelable {
46 private static final String TAG = "NetworkStats";
47 /** {@link #iface} value when interface details unavailable. */
48 public static final String IFACE_ALL = null;
49 /** {@link #uid} value when UID details unavailable. */
50 public static final int UID_ALL = -1;
51 /** {@link #tag} value matching any tag. */
52 // TODO: Rename TAG_ALL to TAG_ANY.
53 public static final int TAG_ALL = -1;
54 /** {@link #set} value for all sets combined, not including debug sets. */
55 public static final int SET_ALL = -1;
56 /** {@link #set} value where background data is accounted. */
57 public static final int SET_DEFAULT = 0;
58 /** {@link #set} value where foreground data is accounted. */
59 public static final int SET_FOREGROUND = 1;
60 /** All {@link #set} value greater than SET_DEBUG_START are debug {@link #set} values. */
61 public static final int SET_DEBUG_START = 1000;
62 /** Debug {@link #set} value when the VPN stats are moved in. */
63 public static final int SET_DBG_VPN_IN = 1001;
64 /** Debug {@link #set} value when the VPN stats are moved out of a vpn UID. */
65 public static final int SET_DBG_VPN_OUT = 1002;
67 /** {@link #tag} value for total data across all tags. */
68 // TODO: Rename TAG_NONE to TAG_ALL.
69 public static final int TAG_NONE = 0;
71 /** {@link #set} value for all roaming values. */
72 public static final int ROAMING_ALL = -1;
73 /** {@link #set} value where native, non-roaming data is accounted. */
74 public static final int ROAMING_NO = 0;
75 /** {@link #set} value where roaming data is accounted. */
76 public static final int ROAMING_YES = 1;
78 // TODO: move fields to "mVariable" notation
81 * {@link SystemClock#elapsedRealtime()} timestamp when this data was
84 private long elapsedRealtime;
87 private String[] iface;
91 private int[] roaming;
92 private long[] rxBytes;
93 private long[] rxPackets;
94 private long[] txBytes;
95 private long[] txPackets;
96 private long[] operations;
98 public static class Entry {
104 * Note that this is only populated w/ the default value when read from /proc or written
105 * to disk. We merge in the correct value when reporting this value to clients of
110 public long rxPackets;
112 public long txPackets;
113 public long operations;
116 this(IFACE_ALL, UID_ALL, SET_DEFAULT, TAG_NONE, 0L, 0L, 0L, 0L, 0L);
119 public Entry(long rxBytes, long rxPackets, long txBytes, long txPackets, long operations) {
120 this(IFACE_ALL, UID_ALL, SET_DEFAULT, TAG_NONE, rxBytes, rxPackets, txBytes, txPackets,
124 public Entry(String iface, int uid, int set, int tag, long rxBytes, long rxPackets,
125 long txBytes, long txPackets, long operations) {
126 this(iface, uid, set, tag, ROAMING_NO, rxBytes, rxPackets, txBytes, txPackets,
130 public Entry(String iface, int uid, int set, int tag, int roaming, long rxBytes,
131 long rxPackets, long txBytes, long txPackets, long operations) {
136 this.roaming = roaming;
137 this.rxBytes = rxBytes;
138 this.rxPackets = rxPackets;
139 this.txBytes = txBytes;
140 this.txPackets = txPackets;
141 this.operations = operations;
144 public boolean isNegative() {
145 return rxBytes < 0 || rxPackets < 0 || txBytes < 0 || txPackets < 0 || operations < 0;
148 public boolean isEmpty() {
149 return rxBytes == 0 && rxPackets == 0 && txBytes == 0 && txPackets == 0
153 public void add(Entry another) {
154 this.rxBytes += another.rxBytes;
155 this.rxPackets += another.rxPackets;
156 this.txBytes += another.txBytes;
157 this.txPackets += another.txPackets;
158 this.operations += another.operations;
162 public String toString() {
163 final StringBuilder builder = new StringBuilder();
164 builder.append("iface=").append(iface);
165 builder.append(" uid=").append(uid);
166 builder.append(" set=").append(setToString(set));
167 builder.append(" tag=").append(tagToString(tag));
168 builder.append(" roaming=").append(roamingToString(roaming));
169 builder.append(" rxBytes=").append(rxBytes);
170 builder.append(" rxPackets=").append(rxPackets);
171 builder.append(" txBytes=").append(txBytes);
172 builder.append(" txPackets=").append(txPackets);
173 builder.append(" operations=").append(operations);
174 return builder.toString();
178 public boolean equals(Object o) {
179 if (o instanceof Entry) {
180 final Entry e = (Entry) o;
181 return uid == e.uid && set == e.set && tag == e.tag && roaming == e.roaming
182 && rxBytes == e.rxBytes && rxPackets == e.rxPackets && txBytes == e.txBytes
183 && txPackets == e.txPackets && operations == e.operations
184 && iface.equals(e.iface);
190 public NetworkStats(long elapsedRealtime, int initialSize) {
191 this.elapsedRealtime = elapsedRealtime;
193 if (initialSize >= 0) {
194 this.capacity = initialSize;
195 this.iface = new String[initialSize];
196 this.uid = new int[initialSize];
197 this.set = new int[initialSize];
198 this.tag = new int[initialSize];
199 this.roaming = new int[initialSize];
200 this.rxBytes = new long[initialSize];
201 this.rxPackets = new long[initialSize];
202 this.txBytes = new long[initialSize];
203 this.txPackets = new long[initialSize];
204 this.operations = new long[initialSize];
206 // Special case for use by NetworkStatsFactory to start out *really* empty.
208 this.iface = EmptyArray.STRING;
209 this.uid = EmptyArray.INT;
210 this.set = EmptyArray.INT;
211 this.tag = EmptyArray.INT;
212 this.roaming = EmptyArray.INT;
213 this.rxBytes = EmptyArray.LONG;
214 this.rxPackets = EmptyArray.LONG;
215 this.txBytes = EmptyArray.LONG;
216 this.txPackets = EmptyArray.LONG;
217 this.operations = EmptyArray.LONG;
221 public NetworkStats(Parcel parcel) {
222 elapsedRealtime = parcel.readLong();
223 size = parcel.readInt();
224 capacity = parcel.readInt();
225 iface = parcel.createStringArray();
226 uid = parcel.createIntArray();
227 set = parcel.createIntArray();
228 tag = parcel.createIntArray();
229 roaming = parcel.createIntArray();
230 rxBytes = parcel.createLongArray();
231 rxPackets = parcel.createLongArray();
232 txBytes = parcel.createLongArray();
233 txPackets = parcel.createLongArray();
234 operations = parcel.createLongArray();
238 public void writeToParcel(Parcel dest, int flags) {
239 dest.writeLong(elapsedRealtime);
241 dest.writeInt(capacity);
242 dest.writeStringArray(iface);
243 dest.writeIntArray(uid);
244 dest.writeIntArray(set);
245 dest.writeIntArray(tag);
246 dest.writeIntArray(roaming);
247 dest.writeLongArray(rxBytes);
248 dest.writeLongArray(rxPackets);
249 dest.writeLongArray(txBytes);
250 dest.writeLongArray(txPackets);
251 dest.writeLongArray(operations);
255 public NetworkStats clone() {
256 final NetworkStats clone = new NetworkStats(elapsedRealtime, size);
257 NetworkStats.Entry entry = null;
258 for (int i = 0; i < size; i++) {
259 entry = getValues(i, entry);
260 clone.addValues(entry);
266 public NetworkStats addIfaceValues(
267 String iface, long rxBytes, long rxPackets, long txBytes, long txPackets) {
269 iface, UID_ALL, SET_DEFAULT, TAG_NONE, rxBytes, rxPackets, txBytes, txPackets, 0L);
273 public NetworkStats addValues(String iface, int uid, int set, int tag, long rxBytes,
274 long rxPackets, long txBytes, long txPackets, long operations) {
275 return addValues(new Entry(
276 iface, uid, set, tag, rxBytes, rxPackets, txBytes, txPackets, operations));
280 public NetworkStats addValues(String iface, int uid, int set, int tag, int roaming,
281 long rxBytes, long rxPackets, long txBytes, long txPackets, long operations) {
282 return addValues(new Entry(
283 iface, uid, set, tag, roaming, rxBytes, rxPackets, txBytes, txPackets, operations));
287 * Add new stats entry, copying from given {@link Entry}. The {@link Entry}
288 * object can be recycled across multiple calls.
290 public NetworkStats addValues(Entry entry) {
291 if (size >= capacity) {
292 final int newLength = Math.max(size, 10) * 3 / 2;
293 iface = Arrays.copyOf(iface, newLength);
294 uid = Arrays.copyOf(uid, newLength);
295 set = Arrays.copyOf(set, newLength);
296 tag = Arrays.copyOf(tag, newLength);
297 roaming = Arrays.copyOf(roaming, newLength);
298 rxBytes = Arrays.copyOf(rxBytes, newLength);
299 rxPackets = Arrays.copyOf(rxPackets, newLength);
300 txBytes = Arrays.copyOf(txBytes, newLength);
301 txPackets = Arrays.copyOf(txPackets, newLength);
302 operations = Arrays.copyOf(operations, newLength);
303 capacity = newLength;
306 iface[size] = entry.iface;
307 uid[size] = entry.uid;
308 set[size] = entry.set;
309 tag[size] = entry.tag;
310 roaming[size] = entry.roaming;
311 rxBytes[size] = entry.rxBytes;
312 rxPackets[size] = entry.rxPackets;
313 txBytes[size] = entry.txBytes;
314 txPackets[size] = entry.txPackets;
315 operations[size] = entry.operations;
322 * Return specific stats entry.
324 public Entry getValues(int i, Entry recycle) {
325 final Entry entry = recycle != null ? recycle : new Entry();
326 entry.iface = iface[i];
330 entry.roaming = roaming[i];
331 entry.rxBytes = rxBytes[i];
332 entry.rxPackets = rxPackets[i];
333 entry.txBytes = txBytes[i];
334 entry.txPackets = txPackets[i];
335 entry.operations = operations[i];
339 public long getElapsedRealtime() {
340 return elapsedRealtime;
343 public void setElapsedRealtime(long time) {
344 elapsedRealtime = time;
348 * Return age of this {@link NetworkStats} object with respect to
349 * {@link SystemClock#elapsedRealtime()}.
351 public long getElapsedRealtimeAge() {
352 return SystemClock.elapsedRealtime() - elapsedRealtime;
360 public int internalSize() {
365 public NetworkStats combineValues(String iface, int uid, int tag, long rxBytes, long rxPackets,
366 long txBytes, long txPackets, long operations) {
367 return combineValues(
368 iface, uid, SET_DEFAULT, tag, rxBytes, rxPackets, txBytes,
369 txPackets, operations);
372 public NetworkStats combineValues(String iface, int uid, int set, int tag,
373 long rxBytes, long rxPackets, long txBytes, long txPackets, long operations) {
374 return combineValues(new Entry(
375 iface, uid, set, tag, rxBytes, rxPackets, txBytes, txPackets, operations));
379 * Combine given values with an existing row, or create a new row if
380 * {@link #findIndex(String, int, int, int, int)} is unable to find match. Can
381 * also be used to subtract values from existing rows.
383 public NetworkStats combineValues(Entry entry) {
384 final int i = findIndex(entry.iface, entry.uid, entry.set, entry.tag, entry.roaming);
386 // only create new entry when positive contribution
389 rxBytes[i] += entry.rxBytes;
390 rxPackets[i] += entry.rxPackets;
391 txBytes[i] += entry.txBytes;
392 txPackets[i] += entry.txPackets;
393 operations[i] += entry.operations;
399 * Combine all values from another {@link NetworkStats} into this object.
401 public void combineAllValues(NetworkStats another) {
402 NetworkStats.Entry entry = null;
403 for (int i = 0; i < another.size; i++) {
404 entry = another.getValues(i, entry);
405 combineValues(entry);
410 * Find first stats index that matches the requested parameters.
412 public int findIndex(String iface, int uid, int set, int tag, int roaming) {
413 for (int i = 0; i < size; i++) {
414 if (uid == this.uid[i] && set == this.set[i] && tag == this.tag[i]
415 && roaming == this.roaming[i] && Objects.equals(iface, this.iface[i])) {
423 * Find first stats index that matches the requested parameters, starting
424 * search around the hinted index as an optimization.
427 public int findIndexHinted(String iface, int uid, int set, int tag, int roaming,
429 for (int offset = 0; offset < size; offset++) {
430 final int halfOffset = offset / 2;
432 // search outwards from hint index, alternating forward and backward
434 if (offset % 2 == 0) {
435 i = (hintIndex + halfOffset) % size;
437 i = (size + hintIndex - halfOffset - 1) % size;
440 if (uid == this.uid[i] && set == this.set[i] && tag == this.tag[i]
441 && roaming == this.roaming[i] && Objects.equals(iface, this.iface[i])) {
449 * Splice in {@link #operations} from the given {@link NetworkStats} based
450 * on matching {@link #uid} and {@link #tag} rows. Ignores {@link #iface},
451 * since operation counts are at data layer.
453 public void spliceOperationsFrom(NetworkStats stats) {
454 for (int i = 0; i < size; i++) {
455 final int j = stats.findIndex(iface[i], uid[i], set[i], tag[i], roaming[i]);
459 operations[i] = stats.operations[j];
465 * Return list of unique interfaces known by this data structure.
467 public String[] getUniqueIfaces() {
468 final HashSet<String> ifaces = new HashSet<String>();
469 for (String iface : this.iface) {
470 if (iface != IFACE_ALL) {
474 return ifaces.toArray(new String[ifaces.size()]);
478 * Return list of unique UIDs known by this data structure.
480 public int[] getUniqueUids() {
481 final SparseBooleanArray uids = new SparseBooleanArray();
482 for (int uid : this.uid) {
486 final int size = uids.size();
487 final int[] result = new int[size];
488 for (int i = 0; i < size; i++) {
489 result[i] = uids.keyAt(i);
495 * Return total bytes represented by this snapshot object, usually used when
496 * checking if a {@link #subtract(NetworkStats)} delta passes a threshold.
498 public long getTotalBytes() {
499 final Entry entry = getTotal(null);
500 return entry.rxBytes + entry.txBytes;
504 * Return total of all fields represented by this snapshot object.
506 public Entry getTotal(Entry recycle) {
507 return getTotal(recycle, null, UID_ALL, false);
511 * Return total of all fields represented by this snapshot object matching
512 * the requested {@link #uid}.
514 public Entry getTotal(Entry recycle, int limitUid) {
515 return getTotal(recycle, null, limitUid, false);
519 * Return total of all fields represented by this snapshot object matching
520 * the requested {@link #iface}.
522 public Entry getTotal(Entry recycle, HashSet<String> limitIface) {
523 return getTotal(recycle, limitIface, UID_ALL, false);
526 public Entry getTotalIncludingTags(Entry recycle) {
527 return getTotal(recycle, null, UID_ALL, true);
531 * Return total of all fields represented by this snapshot object matching
532 * the requested {@link #iface} and {@link #uid}.
534 * @param limitIface Set of {@link #iface} to include in total; or {@code
535 * null} to include all ifaces.
537 private Entry getTotal(
538 Entry recycle, HashSet<String> limitIface, int limitUid, boolean includeTags) {
539 final Entry entry = recycle != null ? recycle : new Entry();
541 entry.iface = IFACE_ALL;
542 entry.uid = limitUid;
544 entry.tag = TAG_NONE;
545 entry.roaming = ROAMING_ALL;
550 entry.operations = 0;
552 for (int i = 0; i < size; i++) {
553 final boolean matchesUid = (limitUid == UID_ALL) || (limitUid == uid[i]);
554 final boolean matchesIface = (limitIface == null) || (limitIface.contains(iface[i]));
556 if (matchesUid && matchesIface) {
557 // skip specific tags, since already counted in TAG_NONE
558 if (tag[i] != TAG_NONE && !includeTags) continue;
560 entry.rxBytes += rxBytes[i];
561 entry.rxPackets += rxPackets[i];
562 entry.txBytes += txBytes[i];
563 entry.txPackets += txPackets[i];
564 entry.operations += operations[i];
571 * Fast path for battery stats.
573 public long getTotalPackets() {
575 for (int i = size-1; i >= 0; i--) {
576 total += rxPackets[i] + txPackets[i];
582 * Subtract the given {@link NetworkStats}, effectively leaving the delta
583 * between two snapshots in time. Assumes that statistics rows collect over
584 * time, and that none of them have disappeared.
586 public NetworkStats subtract(NetworkStats right) {
587 return subtract(this, right, null, null);
591 * Subtract the two given {@link NetworkStats} objects, returning the delta
592 * between two snapshots in time. Assumes that statistics rows collect over
593 * time, and that none of them have disappeared.
595 * If counters have rolled backwards, they are clamped to {@code 0} and
596 * reported to the given {@link NonMonotonicObserver}.
598 public static <C> NetworkStats subtract(NetworkStats left, NetworkStats right,
599 NonMonotonicObserver<C> observer, C cookie) {
600 return subtract(left, right, observer, cookie, null);
604 * Subtract the two given {@link NetworkStats} objects, returning the delta
605 * between two snapshots in time. Assumes that statistics rows collect over
606 * time, and that none of them have disappeared.
608 * If counters have rolled backwards, they are clamped to {@code 0} and
609 * reported to the given {@link NonMonotonicObserver}.
611 * If <var>recycle</var> is supplied, this NetworkStats object will be
612 * reused (and returned) as the result if it is large enough to contain
615 public static <C> NetworkStats subtract(NetworkStats left, NetworkStats right,
616 NonMonotonicObserver<C> observer, C cookie, NetworkStats recycle) {
617 long deltaRealtime = left.elapsedRealtime - right.elapsedRealtime;
618 if (deltaRealtime < 0) {
619 if (observer != null) {
620 observer.foundNonMonotonic(left, -1, right, -1, cookie);
625 // result will have our rows, and elapsed time between snapshots
626 final Entry entry = new Entry();
627 final NetworkStats result;
628 if (recycle != null && recycle.capacity >= left.size) {
631 result.elapsedRealtime = deltaRealtime;
633 result = new NetworkStats(deltaRealtime, left.size);
635 for (int i = 0; i < left.size; i++) {
636 entry.iface = left.iface[i];
637 entry.uid = left.uid[i];
638 entry.set = left.set[i];
639 entry.tag = left.tag[i];
640 entry.roaming = left.roaming[i];
642 // find remote row that matches, and subtract
643 final int j = right.findIndexHinted(entry.iface, entry.uid, entry.set, entry.tag,
646 // newly appearing row, return entire value
647 entry.rxBytes = left.rxBytes[i];
648 entry.rxPackets = left.rxPackets[i];
649 entry.txBytes = left.txBytes[i];
650 entry.txPackets = left.txPackets[i];
651 entry.operations = left.operations[i];
653 // existing row, subtract remote value
654 entry.rxBytes = left.rxBytes[i] - right.rxBytes[j];
655 entry.rxPackets = left.rxPackets[i] - right.rxPackets[j];
656 entry.txBytes = left.txBytes[i] - right.txBytes[j];
657 entry.txPackets = left.txPackets[i] - right.txPackets[j];
658 entry.operations = left.operations[i] - right.operations[j];
660 if (entry.rxBytes < 0 || entry.rxPackets < 0 || entry.txBytes < 0
661 || entry.txPackets < 0 || entry.operations < 0) {
662 if (observer != null) {
663 observer.foundNonMonotonic(left, i, right, j, cookie);
665 entry.rxBytes = Math.max(entry.rxBytes, 0);
666 entry.rxPackets = Math.max(entry.rxPackets, 0);
667 entry.txBytes = Math.max(entry.txBytes, 0);
668 entry.txPackets = Math.max(entry.txPackets, 0);
669 entry.operations = Math.max(entry.operations, 0);
673 result.addValues(entry);
680 * Return total statistics grouped by {@link #iface}; doesn't mutate the
681 * original structure.
683 public NetworkStats groupedByIface() {
684 final NetworkStats stats = new NetworkStats(elapsedRealtime, 10);
686 final Entry entry = new Entry();
689 entry.tag = TAG_NONE;
690 entry.roaming = ROAMING_ALL;
691 entry.operations = 0L;
693 for (int i = 0; i < size; i++) {
694 // skip specific tags, since already counted in TAG_NONE
695 if (tag[i] != TAG_NONE) continue;
697 entry.iface = iface[i];
698 entry.rxBytes = rxBytes[i];
699 entry.rxPackets = rxPackets[i];
700 entry.txBytes = txBytes[i];
701 entry.txPackets = txPackets[i];
702 stats.combineValues(entry);
709 * Return total statistics grouped by {@link #uid}; doesn't mutate the
710 * original structure.
712 public NetworkStats groupedByUid() {
713 final NetworkStats stats = new NetworkStats(elapsedRealtime, 10);
715 final Entry entry = new Entry();
716 entry.iface = IFACE_ALL;
718 entry.tag = TAG_NONE;
719 entry.roaming = ROAMING_ALL;
721 for (int i = 0; i < size; i++) {
722 // skip specific tags, since already counted in TAG_NONE
723 if (tag[i] != TAG_NONE) continue;
726 entry.rxBytes = rxBytes[i];
727 entry.rxPackets = rxPackets[i];
728 entry.txBytes = txBytes[i];
729 entry.txPackets = txPackets[i];
730 entry.operations = operations[i];
731 stats.combineValues(entry);
738 * Return all rows except those attributed to the requested UID; doesn't
739 * mutate the original structure.
741 public NetworkStats withoutUids(int[] uids) {
742 final NetworkStats stats = new NetworkStats(elapsedRealtime, 10);
744 Entry entry = new Entry();
745 for (int i = 0; i < size; i++) {
746 entry = getValues(i, entry);
747 if (!ArrayUtils.contains(uids, entry.uid)) {
748 stats.addValues(entry);
755 public void dump(String prefix, PrintWriter pw) {
757 pw.print("NetworkStats: elapsedRealtime="); pw.println(elapsedRealtime);
758 for (int i = 0; i < size; i++) {
760 pw.print(" ["); pw.print(i); pw.print("]");
761 pw.print(" iface="); pw.print(iface[i]);
762 pw.print(" uid="); pw.print(uid[i]);
763 pw.print(" set="); pw.print(setToString(set[i]));
764 pw.print(" tag="); pw.print(tagToString(tag[i]));
765 pw.print(" roaming="); pw.print(roamingToString(roaming[i]));
766 pw.print(" rxBytes="); pw.print(rxBytes[i]);
767 pw.print(" rxPackets="); pw.print(rxPackets[i]);
768 pw.print(" txBytes="); pw.print(txBytes[i]);
769 pw.print(" txPackets="); pw.print(txPackets[i]);
770 pw.print(" operations="); pw.println(operations[i]);
775 * Return text description of {@link #set} value.
777 public static String setToString(int set) {
787 case SET_DBG_VPN_OUT:
788 return "DBG_VPN_OUT";
795 * Return text description of {@link #set} value.
797 public static String setToCheckinString(int set) {
807 case SET_DBG_VPN_OUT:
815 * @return true if the querySet matches the dataSet.
817 public static boolean setMatches(int querySet, int dataSet) {
818 if (querySet == dataSet) {
821 // SET_ALL matches all non-debugging sets.
822 return querySet == SET_ALL && dataSet < SET_DEBUG_START;
826 * Return text description of {@link #tag} value.
828 public static String tagToString(int tag) {
829 return "0x" + Integer.toHexString(tag);
833 * Return text description of {@link #roaming} value.
835 public static String roamingToString(int roaming) {
849 public String toString() {
850 final CharArrayWriter writer = new CharArrayWriter();
851 dump("", new PrintWriter(writer));
852 return writer.toString();
856 public int describeContents() {
860 public static final Creator<NetworkStats> CREATOR = new Creator<NetworkStats>() {
862 public NetworkStats createFromParcel(Parcel in) {
863 return new NetworkStats(in);
867 public NetworkStats[] newArray(int size) {
868 return new NetworkStats[size];
872 public interface NonMonotonicObserver<C> {
873 public void foundNonMonotonic(
874 NetworkStats left, int leftIndex, NetworkStats right, int rightIndex, C cookie);
878 * VPN accounting. Move some VPN's underlying traffic to other UIDs that use tun0 iface.
880 * This method should only be called on delta NetworkStats. Do not call this method on a
881 * snapshot {@link NetworkStats} object because the tunUid and/or the underlyingIface may
884 * This method performs adjustments for one active VPN package and one VPN iface at a time.
886 * It is possible for the VPN software to use multiple underlying networks. This method
887 * only migrates traffic for the primary underlying network.
889 * @param tunUid uid of the VPN application
890 * @param tunIface iface of the vpn tunnel
891 * @param underlyingIface the primary underlying network iface used by the VPN application
892 * @return true if it successfully adjusts the accounting for VPN, false otherwise
894 public boolean migrateTun(int tunUid, String tunIface, String underlyingIface) {
895 Entry tunIfaceTotal = new Entry();
896 Entry underlyingIfaceTotal = new Entry();
898 tunAdjustmentInit(tunUid, tunIface, underlyingIface, tunIfaceTotal, underlyingIfaceTotal);
900 // If tunIface < underlyingIface, it leaves the overhead traffic in the VPN app.
901 // If tunIface > underlyingIface, the VPN app doesn't get credit for data compression.
902 // Negative stats should be avoided.
903 Entry pool = tunGetPool(tunIfaceTotal, underlyingIfaceTotal);
904 if (pool.isEmpty()) {
907 Entry moved = addTrafficToApplications(tunIface, underlyingIface, tunIfaceTotal, pool);
908 deductTrafficFromVpnApp(tunUid, underlyingIface, moved);
910 if (!moved.isEmpty()) {
911 Slog.wtf(TAG, "Failed to deduct underlying network traffic from VPN package. Moved="
919 * Initializes the data used by the migrateTun() method.
921 * This is the first pass iteration which does the following work:
922 * (1) Adds up all the traffic through tun0.
923 * (2) Adds up all the traffic through the tunUid's underlyingIface
924 * (both foreground and background).
926 private void tunAdjustmentInit(int tunUid, String tunIface, String underlyingIface,
927 Entry tunIfaceTotal, Entry underlyingIfaceTotal) {
928 Entry recycle = new Entry();
929 for (int i = 0; i < size; i++) {
930 getValues(i, recycle);
931 if (recycle.uid == UID_ALL) {
932 throw new IllegalStateException(
933 "Cannot adjust VPN accounting on an iface aggregated NetworkStats.");
934 } if (recycle.set == SET_DBG_VPN_IN || recycle.set == SET_DBG_VPN_OUT) {
935 throw new IllegalStateException(
936 "Cannot adjust VPN accounting on a NetworkStats containing SET_DBG_VPN_*");
939 if (recycle.uid == tunUid && recycle.tag == TAG_NONE
940 && Objects.equals(underlyingIface, recycle.iface)) {
941 underlyingIfaceTotal.add(recycle);
944 if (recycle.tag == TAG_NONE && Objects.equals(tunIface, recycle.iface)) {
945 // Add up all tunIface traffic.
946 tunIfaceTotal.add(recycle);
951 private static Entry tunGetPool(Entry tunIfaceTotal, Entry underlyingIfaceTotal) {
952 Entry pool = new Entry();
953 pool.rxBytes = Math.min(tunIfaceTotal.rxBytes, underlyingIfaceTotal.rxBytes);
954 pool.rxPackets = Math.min(tunIfaceTotal.rxPackets, underlyingIfaceTotal.rxPackets);
955 pool.txBytes = Math.min(tunIfaceTotal.txBytes, underlyingIfaceTotal.txBytes);
956 pool.txPackets = Math.min(tunIfaceTotal.txPackets, underlyingIfaceTotal.txPackets);
957 pool.operations = Math.min(tunIfaceTotal.operations, underlyingIfaceTotal.operations);
961 private Entry addTrafficToApplications(String tunIface, String underlyingIface,
962 Entry tunIfaceTotal, Entry pool) {
963 Entry moved = new Entry();
964 Entry tmpEntry = new Entry();
965 tmpEntry.iface = underlyingIface;
966 for (int i = 0; i < size; i++) {
967 if (Objects.equals(iface[i], tunIface)) {
968 if (tunIfaceTotal.rxBytes > 0) {
969 tmpEntry.rxBytes = pool.rxBytes * rxBytes[i] / tunIfaceTotal.rxBytes;
971 tmpEntry.rxBytes = 0;
973 if (tunIfaceTotal.rxPackets > 0) {
974 tmpEntry.rxPackets = pool.rxPackets * rxPackets[i] / tunIfaceTotal.rxPackets;
976 tmpEntry.rxPackets = 0;
978 if (tunIfaceTotal.txBytes > 0) {
979 tmpEntry.txBytes = pool.txBytes * txBytes[i] / tunIfaceTotal.txBytes;
981 tmpEntry.txBytes = 0;
983 if (tunIfaceTotal.txPackets > 0) {
984 tmpEntry.txPackets = pool.txPackets * txPackets[i] / tunIfaceTotal.txPackets;
986 tmpEntry.txPackets = 0;
988 if (tunIfaceTotal.operations > 0) {
989 tmpEntry.operations =
990 pool.operations * operations[i] / tunIfaceTotal.operations;
992 tmpEntry.operations = 0;
994 tmpEntry.uid = uid[i];
995 tmpEntry.tag = tag[i];
996 tmpEntry.set = set[i];
997 tmpEntry.roaming = roaming[i];
998 combineValues(tmpEntry);
999 if (tag[i] == TAG_NONE) {
1000 moved.add(tmpEntry);
1002 tmpEntry.set = SET_DBG_VPN_IN;
1003 combineValues(tmpEntry);
1010 private void deductTrafficFromVpnApp(int tunUid, String underlyingIface, Entry moved) {
1013 moved.set = SET_DBG_VPN_OUT;
1014 moved.tag = TAG_NONE;
1015 moved.iface = underlyingIface;
1016 moved.roaming = ROAMING_ALL;
1017 combineValues(moved);
1019 // Caveat: if the vpn software uses tag, the total tagged traffic may be greater than
1020 // the TAG_NONE traffic.
1022 // Relies on the fact that the underlying traffic only has state ROAMING_NO, which
1023 // should be the case as it comes directly from the /proc file. We only blend in the
1024 // roaming data after applying these adjustments, by checking the NetworkIdentity of the
1025 // underlying iface.
1026 int idxVpnBackground = findIndex(underlyingIface, tunUid, SET_DEFAULT, TAG_NONE,
1028 if (idxVpnBackground != -1) {
1029 tunSubtract(idxVpnBackground, this, moved);
1032 int idxVpnForeground = findIndex(underlyingIface, tunUid, SET_FOREGROUND, TAG_NONE,
1034 if (idxVpnForeground != -1) {
1035 tunSubtract(idxVpnForeground, this, moved);
1039 private static void tunSubtract(int i, NetworkStats left, Entry right) {
1040 long rxBytes = Math.min(left.rxBytes[i], right.rxBytes);
1041 left.rxBytes[i] -= rxBytes;
1042 right.rxBytes -= rxBytes;
1044 long rxPackets = Math.min(left.rxPackets[i], right.rxPackets);
1045 left.rxPackets[i] -= rxPackets;
1046 right.rxPackets -= rxPackets;
1048 long txBytes = Math.min(left.txBytes[i], right.txBytes);
1049 left.txBytes[i] -= txBytes;
1050 right.txBytes -= txBytes;
1052 long txPackets = Math.min(left.txPackets[i], right.txPackets);
1053 left.txPackets[i] -= txPackets;
1054 right.txPackets -= txPackets;