CpuInfo.java 10.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2012-2013 NetEase, Inc. and other contributors
 *
 *  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.
 *
 */
K
kevinkong 已提交
17 18
package com.netease.qa.emmagee.utils;

19 20
import java.io.File;
import java.io.FileFilter;
K
kevinkong 已提交
21 22 23 24 25 26 27
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
28
import java.util.regex.Pattern;
K
kevinkong 已提交
29 30 31 32

import com.netease.qa.emmagee.service.EmmageeService;

import android.content.Context;
A
andrewleo2013 已提交
33
import android.os.Build;
K
kevinkong 已提交
34 35
import android.util.Log;

36 37 38
/**
 * operate CPU information
 * 
A
andrewleo 已提交
39
 * @author andrewleo
40
 */
K
kevinkong 已提交
41 42
public class CpuInfo {

A
andrewleo 已提交
43
	private static final String LOG_TAG = "Emmagee-" + CpuInfo.class.getSimpleName();
K
kevinkong 已提交
44 45 46

	private Context context;
	private long processCpu;
47 48
	private ArrayList<Long> idleCpu = new ArrayList<Long>();
	private ArrayList<Long> totalCpu = new ArrayList<Long>();
K
kevinkong 已提交
49 50 51 52 53 54 55 56
	private boolean isInitialStatics = true;
	private SimpleDateFormat formatterFile;
	private MemoryInfo mi;
	private long totalMemorySize;
	private long initialTraffic;
	private long lastestTraffic;
	private long traffic;
	private TrafficInfo trafficInfo;
57 58
	private ArrayList<String> cpuUsedRatio = new ArrayList<String>();
	private ArrayList<Long> totalCpu2 = new ArrayList<Long>();
K
kevinkong 已提交
59
	private long processCpu2;
60
	private ArrayList<Long> idleCpu2 = new ArrayList<Long>();
K
kevinkong 已提交
61
	private String processCpuRatio = "";
62
	private ArrayList<String> totalCpuRatio = new ArrayList<String>();
K
kevinkong 已提交
63 64
	private int pid;

65
	private static final String INTEL_CPU_NAME = "model name";
66
	private static final String CPU_DIR_PATH = "/sys/devices/system/cpu/";
67 68
	private static final String CPU_X86 = "x86";
	private static final String CPU_INFO_PATH = "/proc/cpuinfo";
69
	private static final String CPU_STAT = "/proc/stat";
70

A
andrewleo 已提交
71
	public CpuInfo(Context context, int pid, String uid) {
K
kevinkong 已提交
72 73 74 75 76 77
		this.pid = pid;
		this.context = context;
		trafficInfo = new TrafficInfo(uid);
		formatterFile = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mi = new MemoryInfo();
		totalMemorySize = mi.getTotalMemory();
78
		cpuUsedRatio = new ArrayList<String>();
K
kevinkong 已提交
79 80 81
	}

	/**
A
andrewleo2013 已提交
82
	 * read the status of CPU.
K
kevinkong 已提交
83 84 85 86 87 88 89 90
	 * 
	 * @throws FileNotFoundException
	 */
	public void readCpuStat() {
		String processPid = Integer.toString(pid);
		String cpuStatPath = "/proc/" + processPid + "/stat";
		try {
			// monitor cpu stat of certain process
A
andrewleo 已提交
91
			RandomAccessFile processCpuInfo = new RandomAccessFile(cpuStatPath, "r");
K
kevinkong 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
			String line = "";
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.setLength(0);
			while ((line = processCpuInfo.readLine()) != null) {
				stringBuffer.append(line + "\n");
			}
			String[] tok = stringBuffer.toString().split(" ");
			processCpu = Long.parseLong(tok[13]) + Long.parseLong(tok[14]);
			processCpuInfo.close();
		} catch (FileNotFoundException e) {
			Log.e(LOG_TAG, "FileNotFoundException: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
107 108
		read_total_cpu_stat();
	}
K
kevinkong 已提交
109

110
	private void read_total_cpu_stat() {
K
kevinkong 已提交
111 112
		try {
			// monitor total and idle cpu stat of certain process
113 114 115 116 117 118 119
			RandomAccessFile cpuInfo = new RandomAccessFile(CPU_STAT, "r");
			String line = "";
			while ((null != (line = cpuInfo.readLine())) && line.startsWith("cpu")) {
				String[] toks = line.split("\\s+");
				idleCpu.add(Long.parseLong(toks[4]));
				totalCpu.add(Long.parseLong(toks[1]) + Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
						+ Long.parseLong(toks[6]) + Long.parseLong(toks[5]) + Long.parseLong(toks[7]));
120
			}
K
kevinkong 已提交
121 122 123 124 125 126 127 128 129
			cpuInfo.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
A
andrewleo2013 已提交
130
	 * get CPU name.
K
kevinkong 已提交
131
	 * 
132
	 * @return CPU name
K
kevinkong 已提交
133 134 135
	 */
	public String getCpuName() {
		try {
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
			RandomAccessFile cpuStat = new RandomAccessFile(CPU_INFO_PATH, "r");
			// 需要判断是intel or arm
			if (Build.CPU_ABI.equalsIgnoreCase(CPU_X86)) {
				String line;
				while (null != (line = cpuStat.readLine())) {
					String[] values = line.split(":");
					if (values[0].contains(INTEL_CPU_NAME)) {
						return values[1];
					}
				}
			} else {
				String[] cpu = cpuStat.readLine().split(":"); // cpu信息的前一段是含有processor字符串,此处替换为不显示
				cpuStat.close();
				return cpu[1];
			}
K
kevinkong 已提交
151 152 153 154 155 156
		} catch (IOException e) {
			Log.e(LOG_TAG, "IOException: " + e.getMessage());
		}
		return "";
	}

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
	/**
	 * display directories naming with "cpu*"
	 * 
	 * @author andrewleo
	 */
	class CpuFilter implements FileFilter {
		@Override
		public boolean accept(File pathname) {
			// Check if filename matchs "cpu[0-9]"
			if (Pattern.matches("cpu[0-9]", pathname.getName())) {
				return true;
			}
			return false;
		}
	}

	/**
	 * get CPU core numbers
	 * 
	 * @return cpu core numbers
	 */
	public int getCpuNum() {
		try {
			// Get directory containing CPU info
			File dir = new File(CPU_DIR_PATH);
			// Filter to only list the devices we care about
			File[] files = dir.listFiles(new CpuFilter());
			return files.length;
		} catch (Exception e) {
			e.printStackTrace();
			return 1;
		}
	}

	/**
	 * get CPU core list
	 * 
	 * @return cpu core list
	 */
	public ArrayList<String> getCpuList() {
		ArrayList<String> cpuList = new ArrayList<String>();
		try {
			// Get directory containing CPU info
			File dir = new File(CPU_DIR_PATH);
			// Filter to only list the devices we care about
			File[] files = dir.listFiles(new CpuFilter());
			for (int i = 0; i < files.length; i++) {
				cpuList.add(files[i].getName());
			}
			return cpuList;
		} catch (Exception e) {
			e.printStackTrace();
			cpuList.add("cpu0");
			return cpuList;
		}
	}

K
kevinkong 已提交
214
	/**
215
	 * reserve used ratio of process CPU and total CPU, meanwhile collect
A
andrewleo2013 已提交
216
	 * network traffic.
K
kevinkong 已提交
217
	 * 
218 219
	 * @return network traffic ,used ratio of process CPU and total CPU in
	 *         certain interval
K
kevinkong 已提交
220
	 */
A
andrewleo 已提交
221
	public ArrayList<String> getCpuRatioInfo(String totalBatt, String currentBatt, String temperature, String voltage) {
K
kevinkong 已提交
222 223

		DecimalFormat fomart = new DecimalFormat();
K
kevinkong 已提交
224
		fomart.setGroupingUsed(false);
K
kevinkong 已提交
225 226 227
		fomart.setMaximumFractionDigits(2);
		fomart.setMinimumFractionDigits(2);

228
		cpuUsedRatio.clear();
229 230 231 232
		idleCpu.clear();
		totalCpu.clear();
		totalCpuRatio.clear();
		readCpuStat();
K
kevinkong 已提交
233 234

		try {
A
andrewleo2013 已提交
235
			String mDateTime2;
K
kevinkong 已提交
236
			Calendar cal = Calendar.getInstance();
A
andrewleo 已提交
237 238
			if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"))) {
				mDateTime2 = formatterFile.format(cal.getTime().getTime() + 8 * 60 * 60 * 1000);
A
andrewleo 已提交
239 240 241 242
				totalBatt = "N/A";
				currentBatt = "N/A";
				temperature = "N/A";
				voltage = "N/A";
A
andrewleo2013 已提交
243
			} else
A
andrewleo2013 已提交
244
				mDateTime2 = formatterFile.format(cal.getTime().getTime());
A
andrewleo2013 已提交
245
			if (isInitialStatics) {
K
kevinkong 已提交
246 247 248 249 250 251 252 253
				initialTraffic = trafficInfo.getTrafficInfo();
				isInitialStatics = false;
			} else {
				lastestTraffic = trafficInfo.getTrafficInfo();
				if (initialTraffic == -1)
					traffic = -1;
				else
					traffic = (lastestTraffic - initialTraffic + 1023) / 1024;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
				StringBuffer totalCpuBuffer = new StringBuffer();
				if (null != totalCpu2 && totalCpu2.size() > 0) {
					processCpuRatio = fomart.format(100 * ((double) (processCpu - processCpu2) / ((double) (totalCpu.get(0) - totalCpu2.get(0)))));
					for (int i = 0; i < (totalCpu.size() > totalCpu2.size() ? totalCpu2.size() : totalCpu.size()); i++) {
						String cpuRatio = fomart.format(100 * ((double) ((totalCpu.get(i) - idleCpu.get(i)) - (totalCpu2.get(i) - idleCpu2.get(i))) / (double) (totalCpu
								.get(i) - totalCpu2.get(i))));
						totalCpuRatio.add(cpuRatio);
						totalCpuBuffer.append(cpuRatio+",");
					}
				} else {
					processCpuRatio = "0";
					totalCpuRatio.add("0");
					totalCpuBuffer.append("0,");
					totalCpu2 = (ArrayList<Long>) totalCpu.clone();
					processCpu2 = processCpu;
					idleCpu2 = (ArrayList<Long>) idleCpu.clone();
				}
				// 多核cpu的值写入csv文件中
				for(int i =0;i<getCpuNum()-totalCpuRatio.size()+1;i++){
					totalCpuBuffer.append("N/A,");
				}
A
andrewleo 已提交
275
				long pidMemory = mi.getPidMemorySize(pid, context);
K
kevinkong 已提交
276 277 278 279 280
				String pMemory = fomart.format((double) pidMemory / 1024);
				long freeMemory = mi.getFreeMemorySize(context);
				String fMemory = fomart.format((double) freeMemory / 1024);
				String percent = "统计出错";
				if (totalMemorySize != 0) {
A
andrewleo 已提交
281
					percent = fomart.format(((double) pidMemory / (double) totalMemorySize) * 100);
K
kevinkong 已提交
282 283
				}

284
				if (isPositive(processCpuRatio) && isPositive(totalCpuRatio.get(0))) {
A
andrewleo 已提交
285
					// whether certain device supports traffic statics or not
286
					if (traffic == -1) {
A
andrewleo 已提交
287
						EmmageeService.bw.write(mDateTime2 + "," + pMemory + "," + percent + "," + fMemory + "," + processCpuRatio + ","
288
								+ totalCpuBuffer.toString() + "N/A" + "," + totalBatt + "," + currentBatt + "," + temperature + "," + voltage + "\r\n");
A
andrewleo 已提交
289 290
					} else {
						EmmageeService.bw.write(mDateTime2 + "," + pMemory + "," + percent + "," + fMemory + "," + processCpuRatio + ","
291
								+ totalCpuBuffer.toString() + traffic + "," + totalBatt + "," + currentBatt + "," + temperature + "," + voltage + "\r\n");
A
andrewleo 已提交
292
					}
293
					totalCpu2 = (ArrayList<Long>) totalCpu.clone();
A
andrewleo 已提交
294
					processCpu2 = processCpu;
295
					idleCpu2 = (ArrayList<Long>) idleCpu.clone();
A
andrewleo 已提交
296
					cpuUsedRatio.add(processCpuRatio);
297
					cpuUsedRatio.add(totalCpuRatio.get(0));
A
andrewleo 已提交
298
					cpuUsedRatio.add(String.valueOf(traffic));
K
kevinkong 已提交
299 300 301 302 303
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
304
		return cpuUsedRatio;
K
kevinkong 已提交
305
	}
A
andrewleo 已提交
306 307

	/**
308
	 * is text a positive number
A
andrewleo 已提交
309 310 311 312
	 * 
	 * @param text
	 * @return
	 */
313 314
	private boolean isPositive(String text) {
		Double num;
A
andrewleo 已提交
315
		try {
316
			num = Double.parseDouble(text);
A
andrewleo 已提交
317 318 319
		} catch (NumberFormatException e) {
			return false;
		}
320
		return num >= 0;
A
andrewleo 已提交
321 322
	}

K
kevinkong 已提交
323
}