summaryrefslogtreecommitdiff
path: root/test_framework/com/android/tradefed/device/metric/LogcatTimingMetricCollector.java
blob: 648a3af5859e2f2ddccdeb0218ffa1388066f38b (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
/*
 * Copyright (C) 2019 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.tradefed.device.metric;

import com.android.loganalysis.item.GenericTimingItem;
import com.android.loganalysis.parser.TimingsLogParser;
import com.android.tradefed.config.Option;
import com.android.tradefed.config.OptionClass;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.device.LogcatReceiver;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.metrics.proto.MetricMeasurement.DataType;
import com.android.tradefed.metrics.proto.MetricMeasurement.Measurements;
import com.android.tradefed.metrics.proto.MetricMeasurement.Metric;
import com.android.tradefed.result.InputStreamSource;
import com.android.tradefed.result.LogDataType;
import com.android.tradefed.result.TestDescription;

import com.google.common.annotations.VisibleForTesting;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * A metric collector that collects timing information (e.g. user switch time) from logcat during
 * one or multiple repeated tests by using given regex patterns to parse start and end signals of an
 * event from logcat lines.
 */
@OptionClass(alias = "timing-metric-collector")
public class LogcatTimingMetricCollector extends BaseDeviceMetricCollector {

    private static final String LOGCAT_NAME_FORMAT = "device_%s_test_logcat";
    // Use logcat -T 'count' to only print a few line before we start and not the full buffer
    private static final String LOGCAT_CMD = "logcat *:D -T 150";

    @Option(
            name = "start-pattern",
            description =
                    "Key-value pairs to specify the timing metric start patterns to capture from"
                            + " logcat. Key: metric name, value: regex pattern of logcat line"
                            + " indicating the start of the timing metric")
    private final Map<String, String> mStartPatterns = new HashMap<>();

    @Option(
            name = "end-pattern",
            description =
                    "Key-value pairs to specify the timing metric end patterns to capture from"
                            + " logcat. Key: metric name, value: regex pattern of logcat line"
                            + " indicating the end of the timing metric")
    private final Map<String, String> mEndPatterns = new HashMap<>();

    @Option(
            name = "logcat-buffer",
            description =
                    "Logcat buffers where the timing metrics are captured. Default buffers will be"
                            + " used if not specified.")
    private final List<String> mLogcatBuffers = new ArrayList<>();

    private final Map<ITestDevice, LogcatReceiver> mLogcatReceivers = new HashMap<>();
    private final TimingsLogParser mParser = new TimingsLogParser();

    @Override
    public void onTestRunStart(DeviceMetricData testData) {
        // Adding patterns
        mParser.clearDurationPatterns();
        for (Map.Entry<String, String> entry : mStartPatterns.entrySet()) {
            String name = entry.getKey();
            if (!mEndPatterns.containsKey(name)) {
                CLog.w("Metric %s is missing end pattern, skipping.", name);
                continue;
            }
            Pattern start = Pattern.compile(entry.getValue());
            Pattern end = Pattern.compile(mEndPatterns.get(name));
            CLog.d("Adding metric: %s", name);
            mParser.addDurationPatternPair(name, start, end);
        }
        // Start receiving logcat
        String logcatCmd = LOGCAT_CMD;
        if (!mLogcatBuffers.isEmpty()) {
            logcatCmd += " -b " + String.join(",", mLogcatBuffers);
        }
        for (ITestDevice device : getDevices()) {
            CLog.d(
                    "Creating logcat receiver on device %s with command %s",
                    device.getSerialNumber(), logcatCmd);
            mLogcatReceivers.put(device, createLogcatReceiver(device, logcatCmd));
            try {
                device.executeShellCommand("logcat -c");
            } catch (DeviceNotAvailableException e) {
                CLog.e(
                        "Device not available when clear logcat. Skip logcat collection on %s",
                        device.getSerialNumber());
                continue;
            }
            mLogcatReceivers.get(device).start();
        }
    }

    @Override
    public void onTestRunEnd(
            DeviceMetricData testData, final Map<String, Metric> currentTestCaseMetrics) {
        boolean isMultiDevice = getDevices().size() > 1;
        for (ITestDevice device : getDevices()) {
            try (InputStreamSource logcatData = mLogcatReceivers.get(device).getLogcatData()) {
                Map<String, List<Double>> metrics = parse(logcatData);
                for (Map.Entry<String, List<Double>> entry : metrics.entrySet()) {
                    String name = entry.getKey();
                    List<Double> values = entry.getValue();
                    if (isMultiDevice) {
                        testData.addMetricForDevice(device, name, createMetric(values));
                    } else {
                        testData.addMetric(name, createMetric(values));
                    }
                    CLog.d(
                            "Metric: %s with value: %s, added to device %s",
                            name, values, device.getSerialNumber());
                }
                testLog(
                        String.format(LOGCAT_NAME_FORMAT, device.getSerialNumber()),
                        LogDataType.TEXT,
                        logcatData);
            }
            mLogcatReceivers.get(device).stop();
            mLogcatReceivers.get(device).clear();
        }
    }

    @Override
    public void onTestFail(DeviceMetricData testData, TestDescription test) {
        for (ITestDevice device : getDevices()) {
            try (InputStreamSource logcatData = mLogcatReceivers.get(device).getLogcatData()) {
                testLog(
                        String.format(LOGCAT_NAME_FORMAT, device.getSerialNumber()),
                        LogDataType.TEXT,
                        logcatData);
            }
            mLogcatReceivers.get(device).stop();
            mLogcatReceivers.get(device).clear();
        }
    }

    @VisibleForTesting
    Map<String, List<Double>> parse(InputStreamSource logcatData) {
        Map<String, List<Double>> metrics = new HashMap<>();
        try (InputStream inputStream = logcatData.createInputStream();
                InputStreamReader logcatReader = new InputStreamReader(inputStream);
                BufferedReader br = new BufferedReader(logcatReader)) {
            List<GenericTimingItem> items = mParser.parseGenericTimingItems(br);
            for (GenericTimingItem item : items) {
                String metricKey = item.getName();
                if (!metrics.containsKey(metricKey)) {
                    metrics.put(metricKey, new ArrayList<>());
                }
                metrics.get(metricKey).add(item.getDuration());
            }
        } catch (IOException e) {
            CLog.e("Failed to parse timing metrics from logcat %s", e);
        }
        return metrics;
    }

    @VisibleForTesting
    LogcatReceiver createLogcatReceiver(ITestDevice device, String logcatCmd) {
        return new LogcatReceiver(device, logcatCmd, device.getOptions().getMaxLogcatDataSize(), 0);
    }

    private Metric.Builder createMetric(List<Double> values) {
        // TODO: Fix post processors to handle double values. For now use concatenated string as we
        // prefer to use AggregatedPostProcessor
        String stringValue =
                values.stream()
                        .map(value -> Double.toString(value))
                        .collect(Collectors.joining(","));
        return Metric.newBuilder()
                .setType(DataType.RAW)
                .setMeasurements(Measurements.newBuilder().setSingleString(stringValue));
    }
}