1 /*
2  * Copyright (C) 2013 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  */
16 
17 package com.android.launcher3.testing;
18 
19 import android.app.ActivityManager;
20 import android.app.Service;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.os.Binder;
24 import android.os.Debug;
25 import android.os.Handler;
26 import android.os.IBinder;
27 import android.os.Message;
28 import android.os.SystemClock;
29 import android.util.Log;
30 import android.util.LongSparseArray;
31 
32 import com.android.launcher3.util.TestingUtils;
33 
34 import java.util.ArrayList;
35 import java.util.List;
36 
37 public class MemoryTracker extends Service {
38     public static final String TAG = MemoryTracker.class.getSimpleName();
39 
40     private static final long UPDATE_RATE = 5000;
41 
42     private static final int MSG_START = 1;
43     private static final int MSG_STOP = 2;
44     private static final int MSG_UPDATE = 3;
45 
46     public static class ProcessMemInfo {
47         public int pid;
48         public String name;
49         public long startTime;
50         public long currentPss, currentUss;
51         public long[] pss = new long[256];
52         public long[] uss = new long[256];
53             //= new Meminfo[(int) (30 * 60 / (UPDATE_RATE / 1000))]; // 30 minutes
54         public long max = 1;
55         public int head = 0;
ProcessMemInfo(int pid, String name, long start)56         public ProcessMemInfo(int pid, String name, long start) {
57             this.pid = pid;
58             this.name = name;
59             this.startTime = start;
60         }
getUptime()61         public long getUptime() {
62             return System.currentTimeMillis() - startTime;
63         }
64     };
65     public final LongSparseArray<ProcessMemInfo> mData = new LongSparseArray<ProcessMemInfo>();
66     public final ArrayList<Long> mPids = new ArrayList<Long>();
67     private int[] mPidsArray = new int[0];
68     private final Object mLock = new Object();
69 
70     Handler mHandler = new Handler() {
71         @Override
72         public void handleMessage(Message m) {
73             switch (m.what) {
74                 case MSG_START:
75                     mHandler.removeMessages(MSG_UPDATE);
76                     mHandler.sendEmptyMessage(MSG_UPDATE);
77                     break;
78                 case MSG_STOP:
79                     mHandler.removeMessages(MSG_UPDATE);
80                     break;
81                 case MSG_UPDATE:
82                     update();
83                     mHandler.removeMessages(MSG_UPDATE);
84                     mHandler.sendEmptyMessageDelayed(MSG_UPDATE, UPDATE_RATE);
85                     break;
86             }
87         }
88     };
89 
90     ActivityManager mAm;
91 
getMemInfo(int pid)92     public ProcessMemInfo getMemInfo(int pid) {
93         return mData.get(pid);
94     }
95 
getTrackedProcesses()96     public int[] getTrackedProcesses() {
97         return mPidsArray;
98     }
99 
startTrackingProcess(int pid, String name, long start)100     public void startTrackingProcess(int pid, String name, long start) {
101         synchronized (mLock) {
102             final Long lpid = Long.valueOf(pid);
103 
104             if (mPids.contains(lpid)) return;
105 
106             mPids.add(lpid);
107             updatePidsArrayL();
108 
109             mData.put(pid, new ProcessMemInfo(pid, name, start));
110         }
111     }
112 
updatePidsArrayL()113     void updatePidsArrayL() {
114         final int N = mPids.size();
115         mPidsArray = new int[N];
116         StringBuffer sb = new StringBuffer("Now tracking processes: ");
117         for (int i=0; i<N; i++) {
118             final int p = mPids.get(i).intValue();
119             mPidsArray[i] = p;
120             sb.append(p); sb.append(" ");
121         }
122         Log.v(TAG, sb.toString());
123     }
124 
update()125     void update() {
126         synchronized (mLock) {
127             Debug.MemoryInfo[] dinfos = mAm.getProcessMemoryInfo(mPidsArray);
128             for (int i=0; i<dinfos.length; i++) {
129                 Debug.MemoryInfo dinfo = dinfos[i];
130                 if (i > mPids.size()) {
131                     Log.e(TAG, "update: unknown process info received: " + dinfo);
132                     break;
133                 }
134                 final long pid = mPids.get(i).intValue();
135                 final ProcessMemInfo info = mData.get(pid);
136                 info.head = (info.head+1) % info.pss.length;
137                 info.pss[info.head] = info.currentPss = dinfo.getTotalPss();
138                 info.uss[info.head] = info.currentUss = dinfo.getTotalPrivateDirty();
139                 if (info.currentPss > info.max) info.max = info.currentPss;
140                 if (info.currentUss > info.max) info.max = info.currentUss;
141                 // Log.v(TAG, "update: pid " + pid + " pss=" + info.currentPss + " uss=" + info.currentUss);
142                 if (info.currentPss == 0) {
143                     Log.v(TAG, "update: pid " + pid + " has pss=0, it probably died");
144                     mData.remove(pid);
145                 }
146             }
147             for (int i=mPids.size()-1; i>=0; i--) {
148                 final long pid = mPids.get(i).intValue();
149                 if (mData.get(pid) == null) {
150                     mPids.remove(i);
151                     updatePidsArrayL();
152                 }
153             }
154         }
155     }
156 
157     @Override
onCreate()158     public void onCreate() {
159         mAm = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
160 
161         // catch up in case we crashed but other processes are still running
162         List<ActivityManager.RunningServiceInfo> svcs = mAm.getRunningServices(256);
163         for (ActivityManager.RunningServiceInfo svc : svcs) {
164             if (svc.service.getPackageName().equals(getPackageName())) {
165                 Log.v(TAG, "discovered running service: " + svc.process + " (" + svc.pid + ")");
166                 startTrackingProcess(svc.pid, svc.process,
167                         System.currentTimeMillis() - (SystemClock.elapsedRealtime() - svc.activeSince));
168             }
169         }
170 
171         List<ActivityManager.RunningAppProcessInfo> procs = mAm.getRunningAppProcesses();
172         for (ActivityManager.RunningAppProcessInfo proc : procs) {
173             final String pname = proc.processName;
174             if (pname.startsWith(getPackageName())) {
175                 Log.v(TAG, "discovered other running process: " + pname + " (" + proc.pid + ")");
176                 startTrackingProcess(proc.pid, pname, System.currentTimeMillis());
177             }
178         }
179     }
180 
181     @Override
onDestroy()182     public void onDestroy() {
183         mHandler.sendEmptyMessage(MSG_STOP);
184     }
185 
186     @Override
onStartCommand(Intent intent, int flags, int startId)187     public int onStartCommand(Intent intent, int flags, int startId) {
188         Log.v(TAG, "Received start id " + startId + ": " + intent);
189 
190         if (intent != null) {
191             if (TestingUtils.ACTION_START_TRACKING.equals(intent.getAction())) {
192                 final int pid = intent.getIntExtra("pid", -1);
193                 final String name = intent.getStringExtra("name");
194                 final long start = intent.getLongExtra("start", System.currentTimeMillis());
195                 startTrackingProcess(pid, name, start);
196             }
197         }
198 
199         mHandler.sendEmptyMessage(MSG_START);
200 
201         return START_STICKY;
202     }
203 
204     public class MemoryTrackerInterface extends Binder {
getService()205         MemoryTracker getService() {
206             return MemoryTracker.this;
207         }
208     }
209 
210     private final IBinder mBinder = new MemoryTrackerInterface();
211 
onBind(Intent intent)212     public IBinder onBind(Intent intent) {
213         mHandler.sendEmptyMessage(MSG_START);
214 
215         return mBinder;
216     }
217 }
218