aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/internal/telephony/metrics/DataStallRecoveryStats.java
blob: 0fd97ba25eb31c4d64f0ffa9514c9fe4d91e3915 (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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/*
 * Copyright (C) 2020 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.internal.telephony.metrics;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.net.NetworkCapabilities;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.telephony.AccessNetworkConstants;
import android.telephony.Annotation.NetworkType;
import android.telephony.CellSignalStrength;
import android.telephony.NetworkRegistrationInfo;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.telephony.data.DataCallResponse;
import android.telephony.data.DataCallResponse.LinkStatus;

import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.TelephonyStatsLog;
import com.android.internal.telephony.data.DataNetwork;
import com.android.internal.telephony.data.DataNetworkController;
import com.android.internal.telephony.data.DataNetworkController.DataNetworkControllerCallback;
import com.android.internal.telephony.data.DataStallRecoveryManager;
import com.android.internal.telephony.subscription.SubscriptionInfoInternal;
import com.android.internal.telephony.subscription.SubscriptionManagerService;
import com.android.telephony.Rlog;

import java.util.List;

/**
 * Generates metrics related to data stall recovery events per phone ID for the pushed atom.
 */
public class DataStallRecoveryStats {

    /**
     * Value indicating that link bandwidth is unspecified.
     * Copied from {@code NetworkCapabilities#LINK_BANDWIDTH_UNSPECIFIED}
     */
    private static final int LINK_BANDWIDTH_UNSPECIFIED = 0;

    private static final String TAG = "DSRS-";

    // Handler to upload metrics.
    private final @NonNull Handler mHandler;

    private final @NonNull String mTag;
    private final @NonNull Phone mPhone;

    // The interface name of the internet network.
    private @Nullable String mIfaceName = null;

    /* Metrics and stats data variables */
    private int mPhoneId = 0;
    private int mCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
    private int mSignalStrength = CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
    private int mBand = 0;
    // The RAT used for data (including IWLAN).
    private @NetworkType int mRat = TelephonyManager.NETWORK_TYPE_UNKNOWN;
    private boolean mIsOpportunistic = false;
    private boolean mIsMultiSim = false;
    private int mNetworkRegState = NetworkRegistrationInfo
                    .REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING;
    // Info of the other device in case of DSDS
    private int mOtherSignalStrength = CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
    private int mOtherNetworkRegState = NetworkRegistrationInfo
                    .REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING;
    // Link status of the data network
    private @LinkStatus int mInternetLinkStatus = DataCallResponse.LINK_STATUS_UNKNOWN;

    // The link bandwidth of the data network
    private int mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
    private int mLinkUpBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;

    /**
     * Constructs a new instance of {@link DataStallRecoveryStats}.
     */
    public DataStallRecoveryStats(@NonNull final Phone phone,
            @NonNull final DataNetworkController dataNetworkController) {
        mTag = TAG + phone.getPhoneId();
        mPhone = phone;

        HandlerThread handlerThread = new HandlerThread(mTag + "-thread");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper());

        dataNetworkController.registerDataNetworkControllerCallback(
                new DataNetworkControllerCallback(mHandler::post) {
                @Override
                public void onInternetDataNetworkConnected(
                        @NonNull List<DataNetwork> internetNetworks) {
                    for (DataNetwork dataNetwork : internetNetworks) {
                        mIfaceName = dataNetwork.getLinkProperties().getInterfaceName();
                        break;
                    }
                }

                @Override
                public void onInternetDataNetworkDisconnected() {
                    mIfaceName = null;
                }

                @Override
                public void onPhysicalLinkStatusChanged(@LinkStatus int status) {
                    mInternetLinkStatus = status;
                }
            });
    }

    /**
     * Create and push new atom when there is a data stall recovery event.
     *
     * @param action The recovery action.
     * @param isRecovered Whether the data stall has been recovered.
     * @param duration The duration from data stall occurred in milliseconds.
     * @param reason The reason for the recovery.
     * @param isFirstValidation Whether this is the first validation after recovery.
     * @param durationOfAction The duration of the current action in milliseconds.
     */
    public void uploadMetrics(
            @DataStallRecoveryManager.RecoveryAction int action,
            boolean isRecovered,
            int duration,
            @DataStallRecoveryManager.RecoveredReason int reason,
            boolean isFirstValidation,
            int durationOfAction) {

        mHandler.post(() -> {
            // Update data stall stats
            log("Set recovery action to " + action);

            // Refreshes the metrics data.
            try {
                refreshMetricsData();
            } catch (Exception e) {
                loge("The metrics data cannot be refreshed.", e);
                return;
            }

            TelephonyStatsLog.write(
                    TelephonyStatsLog.DATA_STALL_RECOVERY_REPORTED,
                    mCarrierId,
                    mRat,
                    mSignalStrength,
                    action,
                    mIsOpportunistic,
                    mIsMultiSim,
                    mBand,
                    isRecovered,
                    duration,
                    reason,
                    mOtherSignalStrength,
                    mOtherNetworkRegState,
                    mNetworkRegState,
                    isFirstValidation,
                    mPhoneId,
                    durationOfAction,
                    mInternetLinkStatus,
                    mLinkUpBandwidthKbps,
                    mLinkDownBandwidthKbps);

            log("Upload stats: "
                    + "Action:"
                    + action
                    + ", Recovered:"
                    + isRecovered
                    + ", Duration:"
                    + duration
                    + ", Reason:"
                    + reason
                    + ", First validation:"
                    + isFirstValidation
                    + ", Duration of action:"
                    + durationOfAction
                    + ", "
                    + this);
        });
    }

    /**
     * Refreshes the metrics data.
     */
    private void refreshMetricsData() {
        logd("Refreshes the metrics data.");
        // Update phone id/carrier id and signal strength
        mPhoneId = mPhone.getPhoneId() + 1;
        mCarrierId = mPhone.getCarrierId();
        mSignalStrength = mPhone.getSignalStrength().getLevel();

        // Update the bandwidth.
        updateBandwidths();

        // Update the RAT and band.
        updateRatAndBand();

        // Update the opportunistic state.
        mIsOpportunistic = getIsOpportunistic(mPhone);

        // Update the multi-SIM state.
        mIsMultiSim = SimSlotState.getCurrentState().numActiveSims > 1;

        // Update the network registration state.
        updateNetworkRegState();

        // Update the DSDS information.
        updateDsdsInfo();
    }

    /**
     * Updates the bandwidth for the current data network.
     */
    private void updateBandwidths() {
        mLinkDownBandwidthKbps = mLinkUpBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;

        if (mIfaceName == null) {
            loge("Interface name is null");
            return;
        }

        DataNetworkController dataNetworkController = mPhone.getDataNetworkController();
        if (dataNetworkController == null) {
            loge("DataNetworkController is null");
            return;
        }

        DataNetwork dataNetwork = dataNetworkController.getDataNetworkByInterface(mIfaceName);
        if (dataNetwork == null) {
            loge("DataNetwork is null");
            return;
        }
        NetworkCapabilities networkCapabilities = dataNetwork.getNetworkCapabilities();
        if (networkCapabilities == null) {
            loge("NetworkCapabilities is null");
            return;
        }

        mLinkDownBandwidthKbps = networkCapabilities.getLinkDownstreamBandwidthKbps();
        mLinkUpBandwidthKbps = networkCapabilities.getLinkUpstreamBandwidthKbps();
    }

    private void updateRatAndBand() {
        mRat = TelephonyManager.NETWORK_TYPE_UNKNOWN;
        mBand = 0;
        ServiceState serviceState = mPhone.getServiceState();
        if (serviceState == null) {
            loge("ServiceState is null");
            return;
        }

        mRat = serviceState.getDataNetworkType();
        mBand =
            (mRat == TelephonyManager.NETWORK_TYPE_IWLAN) ? 0 : ServiceStateStats.getBand(mPhone);
    }

    private static boolean getIsOpportunistic(@NonNull Phone phone) {
        SubscriptionInfoInternal subInfo = SubscriptionManagerService.getInstance()
                .getSubscriptionInfoInternal(phone.getSubId());
        return subInfo != null && subInfo.isOpportunistic();
    }

    private void updateNetworkRegState() {
        mNetworkRegState = NetworkRegistrationInfo
            .REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING;

        NetworkRegistrationInfo phoneRegInfo = mPhone.getServiceState()
                .getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
                AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
        if (phoneRegInfo != null) {
            mNetworkRegState = phoneRegInfo.getRegistrationState();
        }
    }

    private void updateDsdsInfo() {
        mOtherSignalStrength = CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
        mOtherNetworkRegState = NetworkRegistrationInfo
            .REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING;
        for (Phone otherPhone : PhoneFactory.getPhones()) {
            if (otherPhone.getPhoneId() == mPhone.getPhoneId()) continue;
            if (!getIsOpportunistic(otherPhone)) {
                mOtherSignalStrength = otherPhone.getSignalStrength().getLevel();
                NetworkRegistrationInfo regInfo = otherPhone.getServiceState()
                        .getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
                        AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
                if (regInfo != null) {
                    mOtherNetworkRegState = regInfo.getRegistrationState();
                }
                break;
            }
        }
    }

    /**
     * Return bundled data stall recovery metrics data.
     *
     * @param action The recovery action.
     * @param isRecovered Whether the data stall has been recovered.
     * @param duration The duration from data stall occurred in milliseconds.
     * @param reason The reason for the recovery.
     * @param isFirstValidation Whether this is the first validation after recovery.
     * @param durationOfAction The duration of the current action in milliseconds.
     */
    public Bundle getDataStallRecoveryMetricsData(
            @DataStallRecoveryManager.RecoveryAction int action,
            boolean isRecovered,
            int duration,
            @DataStallRecoveryManager.RecoveredReason int reason,
            boolean isFirstValidation,
            int durationOfAction) {
        Bundle bundle = new Bundle();
        bundle.putInt("Action", action);
        bundle.putBoolean("IsRecovered", isRecovered);
        bundle.putInt("Duration", duration);
        bundle.putInt("Reason", reason);
        bundle.putBoolean("IsFirstValidation", isFirstValidation);
        bundle.putInt("DurationOfAction", durationOfAction);
        bundle.putInt("PhoneId", mPhoneId);
        bundle.putInt("CarrierId", mCarrierId);
        bundle.putInt("SignalStrength", mSignalStrength);
        bundle.putInt("Band", mBand);
        bundle.putInt("Rat", mRat);
        bundle.putBoolean("IsOpportunistic", mIsOpportunistic);
        bundle.putBoolean("IsMultiSim", mIsMultiSim);
        bundle.putInt("NetworkRegState", mNetworkRegState);
        bundle.putInt("OtherSignalStrength", mOtherSignalStrength);
        bundle.putInt("OtherNetworkRegState", mOtherNetworkRegState);
        bundle.putInt("InternetLinkStatus", mInternetLinkStatus);
        bundle.putInt("LinkDownBandwidthKbps", mLinkDownBandwidthKbps);
        bundle.putInt("LinkUpBandwidthKbps", mLinkUpBandwidthKbps);
        return bundle;
    }

    private void log(@NonNull String s) {
        Rlog.i(mTag, s);
    }

    private void logd(@NonNull String s) {
        Rlog.d(mTag, s);
    }

    private void loge(@NonNull String s) {
        Rlog.e(mTag, s);
    }

    private void loge(@NonNull String s, Throwable tr) {
        Rlog.e(mTag, s, tr);
    }

    @Override
    public String toString() {
        return "DataStallRecoveryStats {"
            + "Phone id:"
            + mPhoneId
            + ", Signal strength:"
            + mSignalStrength
            + ", Band:" + mBand
            + ", RAT:" + mRat
            + ", Opportunistic:"
            + mIsOpportunistic
            + ", Multi-SIM:"
            + mIsMultiSim
            + ", Network reg state:"
            + mNetworkRegState
            + ", Other signal strength:"
            + mOtherSignalStrength
            + ", Other network reg state:"
            + mOtherNetworkRegState
            + ", Link status:"
            + mInternetLinkStatus
            + ", Link down bandwidth:"
            + mLinkDownBandwidthKbps
            + ", Link up bandwidth:"
            + mLinkUpBandwidthKbps
            + "}";
    }
}