1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17package android.net; 18 19import android.os.Parcel; 20import android.os.Parcelable; 21import android.os.SystemClock; 22import android.util.SparseBooleanArray; 23 24import com.android.internal.annotations.VisibleForTesting; 25import com.android.internal.util.ArrayUtils; 26import com.android.internal.util.Objects; 27 28import java.io.CharArrayWriter; 29import java.io.PrintWriter; 30import java.util.Arrays; 31import java.util.HashSet; 32 33/** 34 * Collection of active network statistics. Can contain summary details across 35 * all interfaces, or details with per-UID granularity. Internally stores data 36 * as a large table, closely matching {@code /proc/} data format. This structure 37 * optimizes for rapid in-memory comparison, but consider using 38 * {@link NetworkStatsHistory} when persisting. 39 * 40 * @hide 41 */ 42public class NetworkStats implements Parcelable { 43 /** {@link #iface} value when interface details unavailable. */ 44 public static final String IFACE_ALL = null; 45 /** {@link #uid} value when UID details unavailable. */ 46 public static final int UID_ALL = -1; 47 /** {@link #set} value when all sets combined. */ 48 public static final int SET_ALL = -1; 49 /** {@link #set} value where background data is accounted. */ 50 public static final int SET_DEFAULT = 0; 51 /** {@link #set} value where foreground data is accounted. */ 52 public static final int SET_FOREGROUND = 1; 53 /** {@link #tag} value for total data across all tags. */ 54 public static final int TAG_NONE = 0; 55 56 // TODO: move fields to "mVariable" notation 57 58 /** 59 * {@link SystemClock#elapsedRealtime()} timestamp when this data was 60 * generated. 61 */ 62 private final long elapsedRealtime; 63 private int size; 64 private String[] iface; 65 private int[] uid; 66 private int[] set; 67 private int[] tag; 68 private long[] rxBytes; 69 private long[] rxPackets; 70 private long[] txBytes; 71 private long[] txPackets; 72 private long[] operations; 73 74 public static class Entry { 75 public String iface; 76 public int uid; 77 public int set; 78 public int tag; 79 public long rxBytes; 80 public long rxPackets; 81 public long txBytes; 82 public long txPackets; 83 public long operations; 84 85 public Entry() { 86 this(IFACE_ALL, UID_ALL, SET_DEFAULT, TAG_NONE, 0L, 0L, 0L, 0L, 0L); 87 } 88 89 public Entry(long rxBytes, long rxPackets, long txBytes, long txPackets, long operations) { 90 this(IFACE_ALL, UID_ALL, SET_DEFAULT, TAG_NONE, rxBytes, rxPackets, txBytes, txPackets, 91 operations); 92 } 93 94 public Entry(String iface, int uid, int set, int tag, long rxBytes, long rxPackets, 95 long txBytes, long txPackets, long operations) { 96 this.iface = iface; 97 this.uid = uid; 98 this.set = set; 99 this.tag = tag; 100 this.rxBytes = rxBytes; 101 this.rxPackets = rxPackets; 102 this.txBytes = txBytes; 103 this.txPackets = txPackets; 104 this.operations = operations; 105 } 106 107 public boolean isNegative() { 108 return rxBytes < 0 || rxPackets < 0 || txBytes < 0 || txPackets < 0 || operations < 0; 109 } 110 111 public boolean isEmpty() { 112 return rxBytes == 0 && rxPackets == 0 && txBytes == 0 && txPackets == 0 113 && operations == 0; 114 } 115 116 public void add(Entry another) { 117 this.rxBytes += another.rxBytes; 118 this.rxPackets += another.rxPackets; 119 this.txBytes += another.txBytes; 120 this.txPackets += another.txPackets; 121 this.operations += another.operations; 122 } 123 124 @Override 125 public String toString() { 126 final StringBuilder builder = new StringBuilder(); 127 builder.append("iface=").append(iface); 128 builder.append(" uid=").append(uid); 129 builder.append(" set=").append(setToString(set)); 130 builder.append(" tag=").append(tagToString(tag)); 131 builder.append(" rxBytes=").append(rxBytes); 132 builder.append(" rxPackets=").append(rxPackets); 133 builder.append(" txBytes=").append(txBytes); 134 builder.append(" txPackets=").append(txPackets); 135 builder.append(" operations=").append(operations); 136 return builder.toString(); 137 } 138 } 139 140 public NetworkStats(long elapsedRealtime, int initialSize) { 141 this.elapsedRealtime = elapsedRealtime; 142 this.size = 0; 143 this.iface = new String[initialSize]; 144 this.uid = new int[initialSize]; 145 this.set = new int[initialSize]; 146 this.tag = new int[initialSize]; 147 this.rxBytes = new long[initialSize]; 148 this.rxPackets = new long[initialSize]; 149 this.txBytes = new long[initialSize]; 150 this.txPackets = new long[initialSize]; 151 this.operations = new long[initialSize]; 152 } 153 154 public NetworkStats(Parcel parcel) { 155 elapsedRealtime = parcel.readLong(); 156 size = parcel.readInt(); 157 iface = parcel.createStringArray(); 158 uid = parcel.createIntArray(); 159 set = parcel.createIntArray(); 160 tag = parcel.createIntArray(); 161 rxBytes = parcel.createLongArray(); 162 rxPackets = parcel.createLongArray(); 163 txBytes = parcel.createLongArray(); 164 txPackets = parcel.createLongArray(); 165 operations = parcel.createLongArray(); 166 } 167 168 @Override 169 public void writeToParcel(Parcel dest, int flags) { 170 dest.writeLong(elapsedRealtime); 171 dest.writeInt(size); 172 dest.writeStringArray(iface); 173 dest.writeIntArray(uid); 174 dest.writeIntArray(set); 175 dest.writeIntArray(tag); 176 dest.writeLongArray(rxBytes); 177 dest.writeLongArray(rxPackets); 178 dest.writeLongArray(txBytes); 179 dest.writeLongArray(txPackets); 180 dest.writeLongArray(operations); 181 } 182 183 @Override 184 public NetworkStats clone() { 185 final NetworkStats clone = new NetworkStats(elapsedRealtime, size); 186 NetworkStats.Entry entry = null; 187 for (int i = 0; i < size; i++) { 188 entry = getValues(i, entry); 189 clone.addValues(entry); 190 } 191 return clone; 192 } 193 194 @VisibleForTesting 195 public NetworkStats addIfaceValues( 196 String iface, long rxBytes, long rxPackets, long txBytes, long txPackets) { 197 return addValues( 198 iface, UID_ALL, SET_DEFAULT, TAG_NONE, rxBytes, rxPackets, txBytes, txPackets, 0L); 199 } 200 201 @VisibleForTesting 202 public NetworkStats addValues(String iface, int uid, int set, int tag, long rxBytes, 203 long rxPackets, long txBytes, long txPackets, long operations) { 204 return addValues(new Entry( 205 iface, uid, set, tag, rxBytes, rxPackets, txBytes, txPackets, operations)); 206 } 207 208 /** 209 * Add new stats entry, copying from given {@link Entry}. The {@link Entry} 210 * object can be recycled across multiple calls. 211 */ 212 public NetworkStats addValues(Entry entry) { 213 if (size >= this.iface.length) { 214 final int newLength = Math.max(iface.length, 10) * 3 / 2; 215 iface = Arrays.copyOf(iface, newLength); 216 uid = Arrays.copyOf(uid, newLength); 217 set = Arrays.copyOf(set, newLength); 218 tag = Arrays.copyOf(tag, newLength); 219 rxBytes = Arrays.copyOf(rxBytes, newLength); 220 rxPackets = Arrays.copyOf(rxPackets, newLength); 221 txBytes = Arrays.copyOf(txBytes, newLength); 222 txPackets = Arrays.copyOf(txPackets, newLength); 223 operations = Arrays.copyOf(operations, newLength); 224 } 225 226 iface[size] = entry.iface; 227 uid[size] = entry.uid; 228 set[size] = entry.set; 229 tag[size] = entry.tag; 230 rxBytes[size] = entry.rxBytes; 231 rxPackets[size] = entry.rxPackets; 232 txBytes[size] = entry.txBytes; 233 txPackets[size] = entry.txPackets; 234 operations[size] = entry.operations; 235 size++; 236 237 return this; 238 } 239 240 /** 241 * Return specific stats entry. 242 */ 243 public Entry getValues(int i, Entry recycle) { 244 final Entry entry = recycle != null ? recycle : new Entry(); 245 entry.iface = iface[i]; 246 entry.uid = uid[i]; 247 entry.set = set[i]; 248 entry.tag = tag[i]; 249 entry.rxBytes = rxBytes[i]; 250 entry.rxPackets = rxPackets[i]; 251 entry.txBytes = txBytes[i]; 252 entry.txPackets = txPackets[i]; 253 entry.operations = operations[i]; 254 return entry; 255 } 256 257 public long getElapsedRealtime() { 258 return elapsedRealtime; 259 } 260 261 /** 262 * Return age of this {@link NetworkStats} object with respect to 263 * {@link SystemClock#elapsedRealtime()}. 264 */ 265 public long getElapsedRealtimeAge() { 266 return SystemClock.elapsedRealtime() - elapsedRealtime; 267 } 268 269 public int size() { 270 return size; 271 } 272 273 @VisibleForTesting 274 public int internalSize() { 275 return iface.length; 276 } 277 278 @Deprecated 279 public NetworkStats combineValues(String iface, int uid, int tag, long rxBytes, long rxPackets, 280 long txBytes, long txPackets, long operations) { 281 return combineValues( 282 iface, uid, SET_DEFAULT, tag, rxBytes, rxPackets, txBytes, txPackets, operations); 283 } 284 285 public NetworkStats combineValues(String iface, int uid, int set, int tag, long rxBytes, 286 long rxPackets, long txBytes, long txPackets, long operations) { 287 return combineValues(new Entry( 288 iface, uid, set, tag, rxBytes, rxPackets, txBytes, txPackets, operations)); 289 } 290 291 /** 292 * Combine given values with an existing row, or create a new row if 293 * {@link #findIndex(String, int, int, int)} is unable to find match. Can 294 * also be used to subtract values from existing rows. 295 */ 296 public NetworkStats combineValues(Entry entry) { 297 final int i = findIndex(entry.iface, entry.uid, entry.set, entry.tag); 298 if (i == -1) { 299 // only create new entry when positive contribution 300 addValues(entry); 301 } else { 302 rxBytes[i] += entry.rxBytes; 303 rxPackets[i] += entry.rxPackets; 304 txBytes[i] += entry.txBytes; 305 txPackets[i] += entry.txPackets; 306 operations[i] += entry.operations; 307 } 308 return this; 309 } 310 311 /** 312 * Combine all values from another {@link NetworkStats} into this object. 313 */ 314 public void combineAllValues(NetworkStats another) { 315 NetworkStats.Entry entry = null; 316 for (int i = 0; i < another.size; i++) { 317 entry = another.getValues(i, entry); 318 combineValues(entry); 319 } 320 } 321 322 /** 323 * Find first stats index that matches the requested parameters. 324 */ 325 public int findIndex(String iface, int uid, int set, int tag) { 326 for (int i = 0; i < size; i++) { 327 if (uid == this.uid[i] && set == this.set[i] && tag == this.tag[i] 328 && Objects.equal(iface, this.iface[i])) { 329 return i; 330 } 331 } 332 return -1; 333 } 334 335 /** 336 * Find first stats index that matches the requested parameters, starting 337 * search around the hinted index as an optimization. 338 */ 339 @VisibleForTesting 340 public int findIndexHinted(String iface, int uid, int set, int tag, int hintIndex) { 341 for (int offset = 0; offset < size; offset++) { 342 final int halfOffset = offset / 2; 343 344 // search outwards from hint index, alternating forward and backward 345 final int i; 346 if (offset % 2 == 0) { 347 i = (hintIndex + halfOffset) % size; 348 } else { 349 i = (size + hintIndex - halfOffset - 1) % size; 350 } 351 352 if (uid == this.uid[i] && set == this.set[i] && tag == this.tag[i] 353 && Objects.equal(iface, this.iface[i])) { 354 return i; 355 } 356 } 357 return -1; 358 } 359 360 /** 361 * Splice in {@link #operations} from the given {@link NetworkStats} based 362 * on matching {@link #uid} and {@link #tag} rows. Ignores {@link #iface}, 363 * since operation counts are at data layer. 364 */ 365 public void spliceOperationsFrom(NetworkStats stats) { 366 for (int i = 0; i < size; i++) { 367 final int j = stats.findIndex(iface[i], uid[i], set[i], tag[i]); 368 if (j == -1) { 369 operations[i] = 0; 370 } else { 371 operations[i] = stats.operations[j]; 372 } 373 } 374 } 375 376 /** 377 * Return list of unique interfaces known by this data structure. 378 */ 379 public String[] getUniqueIfaces() { 380 final HashSet<String> ifaces = new HashSet<String>(); 381 for (String iface : this.iface) { 382 if (iface != IFACE_ALL) { 383 ifaces.add(iface); 384 } 385 } 386 return ifaces.toArray(new String[ifaces.size()]); 387 } 388 389 /** 390 * Return list of unique UIDs known by this data structure. 391 */ 392 public int[] getUniqueUids() { 393 final SparseBooleanArray uids = new SparseBooleanArray(); 394 for (int uid : this.uid) { 395 uids.put(uid, true); 396 } 397 398 final int size = uids.size(); 399 final int[] result = new int[size]; 400 for (int i = 0; i < size; i++) { 401 result[i] = uids.keyAt(i); 402 } 403 return result; 404 } 405 406 /** 407 * Return total bytes represented by this snapshot object, usually used when 408 * checking if a {@link #subtract(NetworkStats)} delta passes a threshold. 409 */ 410 public long getTotalBytes() { 411 final Entry entry = getTotal(null); 412 return entry.rxBytes + entry.txBytes; 413 } 414 415 /** 416 * Return total of all fields represented by this snapshot object. 417 */ 418 public Entry getTotal(Entry recycle) { 419 return getTotal(recycle, null, UID_ALL, false); 420 } 421 422 /** 423 * Return total of all fields represented by this snapshot object matching 424 * the requested {@link #uid}. 425 */ 426 public Entry getTotal(Entry recycle, int limitUid) { 427 return getTotal(recycle, null, limitUid, false); 428 } 429 430 /** 431 * Return total of all fields represented by this snapshot object matching 432 * the requested {@link #iface}. 433 */ 434 public Entry getTotal(Entry recycle, HashSet<String> limitIface) { 435 return getTotal(recycle, limitIface, UID_ALL, false); 436 } 437 438 public Entry getTotalIncludingTags(Entry recycle) { 439 return getTotal(recycle, null, UID_ALL, true); 440 } 441 442 /** 443 * Return total of all fields represented by this snapshot object matching 444 * the requested {@link #iface} and {@link #uid}. 445 * 446 * @param limitIface Set of {@link #iface} to include in total; or {@code 447 * null} to include all ifaces. 448 */ 449 private Entry getTotal( 450 Entry recycle, HashSet<String> limitIface, int limitUid, boolean includeTags) { 451 final Entry entry = recycle != null ? recycle : new Entry(); 452 453 entry.iface = IFACE_ALL; 454 entry.uid = limitUid; 455 entry.set = SET_ALL; 456 entry.tag = TAG_NONE; 457 entry.rxBytes = 0; 458 entry.rxPackets = 0; 459 entry.txBytes = 0; 460 entry.txPackets = 0; 461 entry.operations = 0; 462 463 for (int i = 0; i < size; i++) { 464 final boolean matchesUid = (limitUid == UID_ALL) || (limitUid == uid[i]); 465 final boolean matchesIface = (limitIface == null) || (limitIface.contains(iface[i])); 466 467 if (matchesUid && matchesIface) { 468 // skip specific tags, since already counted in TAG_NONE 469 if (tag[i] != TAG_NONE && !includeTags) continue; 470 471 entry.rxBytes += rxBytes[i]; 472 entry.rxPackets += rxPackets[i]; 473 entry.txBytes += txBytes[i]; 474 entry.txPackets += txPackets[i]; 475 entry.operations += operations[i]; 476 } 477 } 478 return entry; 479 } 480 481 /** 482 * Subtract the given {@link NetworkStats}, effectively leaving the delta 483 * between two snapshots in time. Assumes that statistics rows collect over 484 * time, and that none of them have disappeared. 485 */ 486 public NetworkStats subtract(NetworkStats right) { 487 return subtract(this, right, null, null); 488 } 489 490 /** 491 * Subtract the two given {@link NetworkStats} objects, returning the delta 492 * between two snapshots in time. Assumes that statistics rows collect over 493 * time, and that none of them have disappeared. 494 * <p> 495 * If counters have rolled backwards, they are clamped to {@code 0} and 496 * reported to the given {@link NonMonotonicObserver}. 497 */ 498 public static <C> NetworkStats subtract( 499 NetworkStats left, NetworkStats right, NonMonotonicObserver<C> observer, C cookie) { 500 long deltaRealtime = left.elapsedRealtime - right.elapsedRealtime; 501 if (deltaRealtime < 0) { 502 if (observer != null) { 503 observer.foundNonMonotonic(left, -1, right, -1, cookie); 504 } 505 deltaRealtime = 0; 506 } 507 508 // result will have our rows, and elapsed time between snapshots 509 final Entry entry = new Entry(); 510 final NetworkStats result = new NetworkStats(deltaRealtime, left.size); 511 for (int i = 0; i < left.size; i++) { 512 entry.iface = left.iface[i]; 513 entry.uid = left.uid[i]; 514 entry.set = left.set[i]; 515 entry.tag = left.tag[i]; 516 517 // find remote row that matches, and subtract 518 final int j = right.findIndexHinted(entry.iface, entry.uid, entry.set, entry.tag, i); 519 if (j == -1) { 520 // newly appearing row, return entire value 521 entry.rxBytes = left.rxBytes[i]; 522 entry.rxPackets = left.rxPackets[i]; 523 entry.txBytes = left.txBytes[i]; 524 entry.txPackets = left.txPackets[i]; 525 entry.operations = left.operations[i]; 526 } else { 527 // existing row, subtract remote value 528 entry.rxBytes = left.rxBytes[i] - right.rxBytes[j]; 529 entry.rxPackets = left.rxPackets[i] - right.rxPackets[j]; 530 entry.txBytes = left.txBytes[i] - right.txBytes[j]; 531 entry.txPackets = left.txPackets[i] - right.txPackets[j]; 532 entry.operations = left.operations[i] - right.operations[j]; 533 534 if (entry.rxBytes < 0 || entry.rxPackets < 0 || entry.txBytes < 0 535 || entry.txPackets < 0 || entry.operations < 0) { 536 if (observer != null) { 537 observer.foundNonMonotonic(left, i, right, j, cookie); 538 } 539 entry.rxBytes = Math.max(entry.rxBytes, 0); 540 entry.rxPackets = Math.max(entry.rxPackets, 0); 541 entry.txBytes = Math.max(entry.txBytes, 0); 542 entry.txPackets = Math.max(entry.txPackets, 0); 543 entry.operations = Math.max(entry.operations, 0); 544 } 545 } 546 547 result.addValues(entry); 548 } 549 550 return result; 551 } 552 553 /** 554 * Return total statistics grouped by {@link #iface}; doesn't mutate the 555 * original structure. 556 */ 557 public NetworkStats groupedByIface() { 558 final NetworkStats stats = new NetworkStats(elapsedRealtime, 10); 559 560 final Entry entry = new Entry(); 561 entry.uid = UID_ALL; 562 entry.set = SET_ALL; 563 entry.tag = TAG_NONE; 564 entry.operations = 0L; 565 566 for (int i = 0; i < size; i++) { 567 // skip specific tags, since already counted in TAG_NONE 568 if (tag[i] != TAG_NONE) continue; 569 570 entry.iface = iface[i]; 571 entry.rxBytes = rxBytes[i]; 572 entry.rxPackets = rxPackets[i]; 573 entry.txBytes = txBytes[i]; 574 entry.txPackets = txPackets[i]; 575 stats.combineValues(entry); 576 } 577 578 return stats; 579 } 580 581 /** 582 * Return total statistics grouped by {@link #uid}; doesn't mutate the 583 * original structure. 584 */ 585 public NetworkStats groupedByUid() { 586 final NetworkStats stats = new NetworkStats(elapsedRealtime, 10); 587 588 final Entry entry = new Entry(); 589 entry.iface = IFACE_ALL; 590 entry.set = SET_ALL; 591 entry.tag = TAG_NONE; 592 593 for (int i = 0; i < size; i++) { 594 // skip specific tags, since already counted in TAG_NONE 595 if (tag[i] != TAG_NONE) continue; 596 597 entry.uid = uid[i]; 598 entry.rxBytes = rxBytes[i]; 599 entry.rxPackets = rxPackets[i]; 600 entry.txBytes = txBytes[i]; 601 entry.txPackets = txPackets[i]; 602 entry.operations = operations[i]; 603 stats.combineValues(entry); 604 } 605 606 return stats; 607 } 608 609 /** 610 * Return all rows except those attributed to the requested UID; doesn't 611 * mutate the original structure. 612 */ 613 public NetworkStats withoutUids(int[] uids) { 614 final NetworkStats stats = new NetworkStats(elapsedRealtime, 10); 615 616 Entry entry = new Entry(); 617 for (int i = 0; i < size; i++) { 618 entry = getValues(i, entry); 619 if (!ArrayUtils.contains(uids, entry.uid)) { 620 stats.addValues(entry); 621 } 622 } 623 624 return stats; 625 } 626 627 public void dump(String prefix, PrintWriter pw) { 628 pw.print(prefix); 629 pw.print("NetworkStats: elapsedRealtime="); pw.println(elapsedRealtime); 630 for (int i = 0; i < size; i++) { 631 pw.print(prefix); 632 pw.print(" ["); pw.print(i); pw.print("]"); 633 pw.print(" iface="); pw.print(iface[i]); 634 pw.print(" uid="); pw.print(uid[i]); 635 pw.print(" set="); pw.print(setToString(set[i])); 636 pw.print(" tag="); pw.print(tagToString(tag[i])); 637 pw.print(" rxBytes="); pw.print(rxBytes[i]); 638 pw.print(" rxPackets="); pw.print(rxPackets[i]); 639 pw.print(" txBytes="); pw.print(txBytes[i]); 640 pw.print(" txPackets="); pw.print(txPackets[i]); 641 pw.print(" operations="); pw.println(operations[i]); 642 } 643 } 644 645 /** 646 * Return text description of {@link #set} value. 647 */ 648 public static String setToString(int set) { 649 switch (set) { 650 case SET_ALL: 651 return "ALL"; 652 case SET_DEFAULT: 653 return "DEFAULT"; 654 case SET_FOREGROUND: 655 return "FOREGROUND"; 656 default: 657 return "UNKNOWN"; 658 } 659 } 660 661 /** 662 * Return text description of {@link #tag} value. 663 */ 664 public static String tagToString(int tag) { 665 return "0x" + Integer.toHexString(tag); 666 } 667 668 @Override 669 public String toString() { 670 final CharArrayWriter writer = new CharArrayWriter(); 671 dump("", new PrintWriter(writer)); 672 return writer.toString(); 673 } 674 675 @Override 676 public int describeContents() { 677 return 0; 678 } 679 680 public static final Creator<NetworkStats> CREATOR = new Creator<NetworkStats>() { 681 @Override 682 public NetworkStats createFromParcel(Parcel in) { 683 return new NetworkStats(in); 684 } 685 686 @Override 687 public NetworkStats[] newArray(int size) { 688 return new NetworkStats[size]; 689 } 690 }; 691 692 public interface NonMonotonicObserver<C> { 693 public void foundNonMonotonic( 694 NetworkStats left, int leftIndex, NetworkStats right, int rightIndex, C cookie); 695 } 696} 697