1/*
2 * Copyright (C) 2017 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 */
16package com.android.statsd.loadtest;
17
18import android.annotation.Nullable;
19import android.os.SystemClock;
20import android.util.Log;
21import java.util.regex.Matcher;
22import java.util.regex.Pattern;
23
24/** Parses PSS info from dumpsys meminfo */
25public class MemInfoParser implements PerfParser {
26
27    private static final Pattern LINE_PATTERN =
28        Pattern.compile("\\s*(\\d*,*\\d*)K:\\s(\\S*)\\s\\.*");
29    private static final String PSS_BY_PROCESS = "Total PSS by process:";
30    private static final String TAG = "loadtest.MemInfoParser";
31
32    private boolean mPssStarted;
33    private boolean mPssEnded;
34    private final long mStartTimeMillis;
35
36    public MemInfoParser(long startTimeMillis) {
37        mStartTimeMillis = startTimeMillis;
38    }
39
40    @Override
41    @Nullable
42    public String parseLine(String line) {
43        if (mPssEnded) {
44            return null;
45        }
46        if (!mPssStarted) {
47            if (line.contains(PSS_BY_PROCESS)) {
48                mPssStarted = true;
49            }
50            return null;
51        }
52        if (line.isEmpty()) {
53            mPssEnded = true;
54            return null;
55        }
56        Matcher lineMatcher = LINE_PATTERN.matcher(line);
57        if (lineMatcher.find() && lineMatcher.group(1) != null && lineMatcher.group(2) != null) {
58            if (lineMatcher.group(2).equals("statsd")) {
59                long timeDeltaMillis = SystemClock.elapsedRealtime() - mStartTimeMillis;
60                return timeDeltaMillis + "," + convertToPss(lineMatcher.group(1));
61            }
62        }
63        return null;
64    }
65
66    private String convertToPss(String input) {
67        return input.replace(",", "");
68    }
69}
70