summaryrefslogtreecommitdiff
path: root/common/framework/com/android/net/module/util/NetworkStatsUtils.java
blob: 41a9428a0083e6d1f962ca3552b52b762111b93e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.net.module.util;

import android.app.usage.NetworkStats;

import com.android.internal.annotations.VisibleForTesting;

/**
 * Various utilities used for NetworkStats related code.
 *
 * @hide
 */
public class NetworkStatsUtils {
    // These constants must be synced with the definition in android.net.NetworkStats.
    // TODO: update to formal APIs once all downstreams have these APIs.
    private static final int SET_ALL = -1;
    private static final int METERED_ALL = -1;
    private static final int ROAMING_ALL = -1;
    private static final int DEFAULT_NETWORK_ALL = -1;

    /**
     * Safely multiple a value by a rational.
     * <p>
     * Internally it uses integer-based math whenever possible, but switches
     * over to double-based math if values would overflow.
     * @hide
     */
    public static long multiplySafeByRational(long value, long num, long den) {
        if (den == 0) {
            throw new ArithmeticException("Invalid Denominator");
        }
        long x = value;
        long y = num;

        // Logic shamelessly borrowed from Math.multiplyExact()
        long r = x * y;
        long ax = Math.abs(x);
        long ay = Math.abs(y);
        if (((ax | ay) >>> 31 != 0)) {
            // Some bits greater than 2^31 that might cause overflow
            // Check the result using the divide operator
            // and check for the special case of Long.MIN_VALUE * -1
            if (((y != 0) && (r / y != x))
                    || (x == Long.MIN_VALUE && y == -1)) {
                // Use double math to avoid overflowing
                return (long) (((double) num / den) * value);
            }
        }
        return r / den;
    }

    /**
     * Value of the match rule of the subscriberId to match networks with specific subscriberId.
     *
     * @hide
     */
    public static final int SUBSCRIBER_ID_MATCH_RULE_EXACT = 0;
    /**
     * Value of the match rule of the subscriberId to match networks with any subscriberId which
     * includes null and non-null.
     *
     * @hide
     */
    public static final int SUBSCRIBER_ID_MATCH_RULE_ALL = 1;

    /**
     * Name representing {@link #bandwidthSetGlobalAlert(long)} limit when delivered to
     * {@link AlertObserver#onQuotaLimitReached(String, String)}.
     */
    public static final String LIMIT_GLOBAL_ALERT = "globalAlert";

    /**
     * Return the constrained value by given the lower and upper bounds.
     */
    public static int constrain(int amount, int low, int high) {
        if (low > high) throw new IllegalArgumentException("low(" + low + ") > high(" + high + ")");
        return amount < low ? low : (amount > high ? high : amount);
    }

    /**
     * Return the constrained value by given the lower and upper bounds.
     */
    public static long constrain(long amount, long low, long high) {
        if (low > high) throw new IllegalArgumentException("low(" + low + ") > high(" + high + ")");
        return amount < low ? low : (amount > high ? high : amount);
    }

    /**
     * Convert structure from android.app.usage.NetworkStats to android.net.NetworkStats.
     */
    public static android.net.NetworkStats fromPublicNetworkStats(
            NetworkStats publiceNetworkStats) {
        android.net.NetworkStats stats = new android.net.NetworkStats(0L, 0);
        while (publiceNetworkStats.hasNextBucket()) {
            NetworkStats.Bucket bucket = new NetworkStats.Bucket();
            publiceNetworkStats.getNextBucket(bucket);
            final android.net.NetworkStats.Entry entry = fromBucket(bucket);
            stats = stats.addEntry(entry);
        }
        return stats;
    }

    @VisibleForTesting
    public static android.net.NetworkStats.Entry fromBucket(NetworkStats.Bucket bucket) {
        return new android.net.NetworkStats.Entry(
                null /* IFACE_ALL */, bucket.getUid(), convertBucketState(bucket.getState()),
                convertBucketTag(bucket.getTag()), convertBucketMetered(bucket.getMetered()),
                convertBucketRoaming(bucket.getRoaming()),
                convertBucketDefaultNetworkStatus(bucket.getDefaultNetworkStatus()),
                bucket.getRxBytes(), bucket.getRxPackets(),
                bucket.getTxBytes(), bucket.getTxPackets(), 0 /* operations */);
    }

    private static int convertBucketState(int networkStatsSet) {
        switch (networkStatsSet) {
            case NetworkStats.Bucket.STATE_ALL: return SET_ALL;
            case NetworkStats.Bucket.STATE_DEFAULT: return android.net.NetworkStats.SET_DEFAULT;
            case NetworkStats.Bucket.STATE_FOREGROUND:
                return android.net.NetworkStats.SET_FOREGROUND;
        }
        return 0;
    }

    private static int convertBucketTag(int tag) {
        switch (tag) {
            case NetworkStats.Bucket.TAG_NONE: return android.net.NetworkStats.TAG_NONE;
        }
        return tag;
    }

    private static int convertBucketMetered(int metered) {
        switch (metered) {
            case NetworkStats.Bucket.METERED_ALL: return METERED_ALL;
            case NetworkStats.Bucket.METERED_NO: return android.net.NetworkStats.METERED_NO;
            case NetworkStats.Bucket.METERED_YES: return android.net.NetworkStats.METERED_YES;
        }
        return 0;
    }

    private static int convertBucketRoaming(int roaming) {
        switch (roaming) {
            case NetworkStats.Bucket.ROAMING_ALL: return ROAMING_ALL;
            case NetworkStats.Bucket.ROAMING_NO: return android.net.NetworkStats.ROAMING_NO;
            case NetworkStats.Bucket.ROAMING_YES: return android.net.NetworkStats.ROAMING_YES;
        }
        return 0;
    }

    private static int convertBucketDefaultNetworkStatus(int defaultNetworkStatus) {
        switch (defaultNetworkStatus) {
            case NetworkStats.Bucket.DEFAULT_NETWORK_ALL:
                return DEFAULT_NETWORK_ALL;
            case NetworkStats.Bucket.DEFAULT_NETWORK_NO:
                return android.net.NetworkStats.DEFAULT_NETWORK_NO;
            case NetworkStats.Bucket.DEFAULT_NETWORK_YES:
                return android.net.NetworkStats.DEFAULT_NETWORK_YES;
        }
        return 0;
    }
}