blob: a82b55949cb915ed20fea5dcc5cbd1c8ac8d501f [file] [log] [blame]
Bookatz94726412017-08-31 09:26:15 -07001/*
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.server.stats;
17
Chenjie Yu05013b32017-11-21 10:21:41 -080018import android.annotation.Nullable;
Bookatz94726412017-08-31 09:26:15 -070019import android.app.AlarmManager;
20import android.app.PendingIntent;
Bookatzc6977972018-01-16 16:55:05 -080021import android.app.StatsManager;
Chenjie Yu9d7720b2018-01-24 10:34:48 -080022import android.bluetooth.BluetoothActivityEnergyInfo;
23import android.bluetooth.BluetoothAdapter;
24import android.bluetooth.UidTraffic;
Bookatz94726412017-08-31 09:26:15 -070025import android.content.BroadcastReceiver;
26import android.content.Context;
27import android.content.Intent;
David Chende701692017-10-05 13:16:02 -070028import android.content.IntentFilter;
Bookatzc6977972018-01-16 16:55:05 -080029import android.content.IntentSender;
David Chende701692017-10-05 13:16:02 -070030import android.content.pm.PackageInfo;
31import android.content.pm.PackageManager;
32import android.content.pm.UserInfo;
David Chenc8a43242017-10-17 16:23:28 -070033import android.net.NetworkStats;
Chenjie Yu05013b32017-11-21 10:21:41 -080034import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiActivityEnergyInfo;
David Chenc8a43242017-10-17 16:23:28 -070036import android.os.BatteryStatsInternal;
Bookatz94726412017-08-31 09:26:15 -070037import android.os.Binder;
David Chende701692017-10-05 13:16:02 -070038import android.os.Bundle;
Chenjie Yu937d7422018-01-10 16:37:53 -080039import android.os.Environment;
Bookatzb487b552017-09-18 11:26:01 -070040import android.os.IBinder;
Bookatz94726412017-08-31 09:26:15 -070041import android.os.IStatsCompanionService;
42import android.os.IStatsManager;
Chenjie Yu05013b32017-11-21 10:21:41 -080043import android.os.Parcelable;
Bookatz94726412017-08-31 09:26:15 -070044import android.os.Process;
Bookatz1b0b1142017-09-08 11:58:42 -070045import android.os.RemoteException;
Bookatz94726412017-08-31 09:26:15 -070046import android.os.ServiceManager;
Chenjie Yu937d7422018-01-10 16:37:53 -080047import android.os.StatFs;
Chenjie Yu9d7720b2018-01-24 10:34:48 -080048import android.os.StatsDimensionsValue;
David Chen1481fe12017-10-16 13:16:34 -070049import android.os.StatsLogEventWrapper;
Chenjie Yu05013b32017-11-21 10:21:41 -080050import android.os.SynchronousResultReceiver;
Chenjie Yu937d7422018-01-10 16:37:53 -080051import android.os.SystemClock;
David Chende701692017-10-05 13:16:02 -070052import android.os.UserHandle;
53import android.os.UserManager;
Chenjie Yu937d7422018-01-10 16:37:53 -080054import android.telephony.ModemActivityInfo;
55import android.telephony.TelephonyManager;
Bookatz94726412017-08-31 09:26:15 -070056import android.util.Slog;
David Chenc8a43242017-10-17 16:23:28 -070057import android.util.StatsLog;
58
59import com.android.internal.annotations.GuardedBy;
60import com.android.internal.net.NetworkStatsFactory;
Chenjie Yu937d7422018-01-10 16:37:53 -080061import com.android.internal.os.KernelCpuSpeedReader;
David Chenc8a43242017-10-17 16:23:28 -070062import com.android.internal.os.KernelWakelockReader;
63import com.android.internal.os.KernelWakelockStats;
Chenjie Yu7f8def92017-11-03 09:33:15 -070064import com.android.internal.os.PowerProfile;
David Chenc8a43242017-10-17 16:23:28 -070065import com.android.server.LocalServices;
66import com.android.server.SystemService;
Bookatz94726412017-08-31 09:26:15 -070067
David Chende701692017-10-05 13:16:02 -070068import java.util.ArrayList;
69import java.util.List;
Bookatzc68a9d22017-09-27 14:09:55 -070070import java.util.Map;
Chenjie Yu05013b32017-11-21 10:21:41 -080071import java.util.concurrent.TimeoutException;
Bookatzc68a9d22017-09-27 14:09:55 -070072
Bookatz94726412017-08-31 09:26:15 -070073/**
74 * Helper service for statsd (the native stats management service in cmds/statsd/).
75 * Used for registering and receiving alarms on behalf of statsd.
David Chen1481fe12017-10-16 13:16:34 -070076 *
Bookatz6bc51d72017-09-28 16:43:40 -070077 * @hide
Bookatz94726412017-08-31 09:26:15 -070078 */
79public class StatsCompanionService extends IStatsCompanionService.Stub {
Chenjie Yu05013b32017-11-21 10:21:41 -080080 /**
81 * How long to wait on an individual subsystem to return its stats.
82 */
83 private static final long EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS = 2000;
84
85 public static final String RESULT_RECEIVER_CONTROLLER_KEY = "controller_activity";
86
Bookatz94726412017-08-31 09:26:15 -070087 static final String TAG = "StatsCompanionService";
88 static final boolean DEBUG = true;
Bookatzc6977972018-01-16 16:55:05 -080089
David Chen661f7912018-01-22 17:46:24 -080090 public static final int CODE_DATA_BROADCAST = 1;
Bookatzc6977972018-01-16 16:55:05 -080091 public static final int CODE_SUBSCRIBER_BROADCAST = 1;
92
Bookatz94726412017-08-31 09:26:15 -070093 private final Context mContext;
94 private final AlarmManager mAlarmManager;
Bookatzb487b552017-09-18 11:26:01 -070095 @GuardedBy("sStatsdLock")
Bookatz1b0b1142017-09-08 11:58:42 -070096 private static IStatsManager sStatsd;
Bookatzb487b552017-09-18 11:26:01 -070097 private static final Object sStatsdLock = new Object();
Bookatz94726412017-08-31 09:26:15 -070098
99 private final PendingIntent mAnomalyAlarmIntent;
Chenjie Yub3dda412017-10-24 13:41:59 -0700100 private final PendingIntent mPullingAlarmIntent;
David Chende701692017-10-05 13:16:02 -0700101 private final BroadcastReceiver mAppUpdateReceiver;
David Chen47e8f4d2017-10-11 15:34:13 -0700102 private final BroadcastReceiver mUserUpdateReceiver;
yro947fbce2017-11-15 22:50:23 -0800103 private final ShutdownEventReceiver mShutdownEventReceiver;
Chenjie Yu7f8def92017-11-03 09:33:15 -0700104 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
105 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
106 private final KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
Chenjie Yu05013b32017-11-21 10:21:41 -0800107 private IWifiManager mWifiManager = null;
108 private TelephonyManager mTelephony = null;
Chenjie Yu937d7422018-01-10 16:37:53 -0800109 private final StatFs mStatFsData = new StatFs(Environment.getDataDirectory().getAbsolutePath());
110 private final StatFs mStatFsSystem =
David Chen661f7912018-01-22 17:46:24 -0800111 new StatFs(Environment.getRootDirectory().getAbsolutePath());
Chenjie Yu937d7422018-01-10 16:37:53 -0800112 private final StatFs mStatFsTemp =
David Chen661f7912018-01-22 17:46:24 -0800113 new StatFs(Environment.getDownloadCacheDirectory().getAbsolutePath());
Bookatz94726412017-08-31 09:26:15 -0700114
Bookatz94726412017-08-31 09:26:15 -0700115 public StatsCompanionService(Context context) {
116 super();
117 mContext = context;
118 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
119
120 mAnomalyAlarmIntent = PendingIntent.getBroadcast(mContext, 0,
121 new Intent(mContext, AnomalyAlarmReceiver.class), 0);
Chenjie Yub3dda412017-10-24 13:41:59 -0700122 mPullingAlarmIntent = PendingIntent.getBroadcast(
David Chen661f7912018-01-22 17:46:24 -0800123 mContext, 0, new Intent(mContext, PullingAlarmReceiver.class), 0);
David Chende701692017-10-05 13:16:02 -0700124 mAppUpdateReceiver = new AppUpdateReceiver();
David Chen47e8f4d2017-10-11 15:34:13 -0700125 mUserUpdateReceiver = new BroadcastReceiver() {
126 @Override
127 public void onReceive(Context context, Intent intent) {
128 synchronized (sStatsdLock) {
129 sStatsd = fetchStatsdService();
130 if (sStatsd == null) {
131 Slog.w(TAG, "Could not access statsd");
132 return;
133 }
134 try {
135 // Pull the latest state of UID->app name, version mapping.
136 // Needed since the new user basically has a version of every app.
137 informAllUidsLocked(context);
138 } catch (RemoteException e) {
David Chen1481fe12017-10-16 13:16:34 -0700139 Slog.e(TAG, "Failed to inform statsd latest update of all apps", e);
David Chen47e8f4d2017-10-11 15:34:13 -0700140 forgetEverything();
141 }
142 }
143 }
144 };
yro947fbce2017-11-15 22:50:23 -0800145 mShutdownEventReceiver = new ShutdownEventReceiver();
David Chende701692017-10-05 13:16:02 -0700146 Slog.w(TAG, "Registered receiver for ACTION_PACKAGE_REPLACE AND ADDED.");
Chenjie Yu7f8def92017-11-03 09:33:15 -0700147 PowerProfile powerProfile = new PowerProfile(context);
148 final int numClusters = powerProfile.getNumCpuClusters();
149 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
150 int firstCpuOfCluster = 0;
151 for (int i = 0; i < numClusters; i++) {
152 final int numSpeedSteps = powerProfile.getNumSpeedStepsInCpuCluster(i);
153 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
David Chen661f7912018-01-22 17:46:24 -0800154 numSpeedSteps);
Chenjie Yu7f8def92017-11-03 09:33:15 -0700155 firstCpuOfCluster += powerProfile.getNumCoresInCpuCluster(i);
156 }
Bookatz94726412017-08-31 09:26:15 -0700157 }
158
David Chenadaf8b32017-11-03 15:42:08 -0700159 @Override
David Chen661f7912018-01-22 17:46:24 -0800160 public void sendDataBroadcast(IBinder intentSenderBinder) {
Bookatz36920822018-01-26 09:18:07 -0800161 enforceCallingPermission();
David Chen661f7912018-01-22 17:46:24 -0800162 IntentSender intentSender = new IntentSender(intentSenderBinder);
163 Intent intent = new Intent();
164 try {
165 intentSender.sendIntent(mContext, CODE_DATA_BROADCAST, intent, null, null);
166 } catch (IntentSender.SendIntentException e) {
167 Slog.w(TAG, "Unable to send using IntentSender");
168 }
David Chenadaf8b32017-11-03 15:42:08 -0700169 }
170
Bookatzc6977972018-01-16 16:55:05 -0800171 @Override
172 public void sendSubscriberBroadcast(IBinder intentSenderBinder, long configUid, long configKey,
173 long subscriptionId, long subscriptionRuleId,
174 StatsDimensionsValue dimensionsValue) {
175 if (DEBUG) Slog.d(TAG, "Statsd requested to sendSubscriberBroadcast.");
176 enforceCallingPermission();
177 IntentSender intentSender = new IntentSender(intentSenderBinder);
178 Intent intent = new Intent()
179 .putExtra(StatsManager.EXTRA_STATS_CONFIG_UID, configUid)
180 .putExtra(StatsManager.EXTRA_STATS_CONFIG_KEY, configKey)
181 .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_ID, subscriptionId)
182 .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_RULE_ID, subscriptionRuleId)
183 .putExtra(StatsManager.EXTRA_STATS_DIMENSIONS_VALUE, dimensionsValue);
184 try {
185 intentSender.sendIntent(mContext, CODE_SUBSCRIBER_BROADCAST, intent, null, null);
186 } catch (IntentSender.SendIntentException e) {
187 Slog.w(TAG, "Unable to send using IntentSender from uid " + configUid
188 + "; presumably it had been cancelled.");
189 if (DEBUG) {
190 Slog.d(TAG, String.format("SubscriberBroadcast params {%d %d %d %d %s}",
191 configUid, configKey, subscriptionId,
192 subscriptionRuleId, dimensionsValue));
193 }
194 }
195 }
196
David Chen1481fe12017-10-16 13:16:34 -0700197 private final static int[] toIntArray(List<Integer> list) {
David Chende701692017-10-05 13:16:02 -0700198 int[] ret = new int[list.size()];
David Chen1481fe12017-10-16 13:16:34 -0700199 for (int i = 0; i < ret.length; i++) {
David Chende701692017-10-05 13:16:02 -0700200 ret[i] = list.get(i);
201 }
202 return ret;
203 }
204
Dianne Hackborn3accca02013-09-20 09:32:11 -0700205 private final static long[] toLongArray(List<Long> list) {
206 long[] ret = new long[list.size()];
207 for (int i = 0; i < ret.length; i++) {
208 ret[i] = list.get(i);
209 }
210 return ret;
211 }
212
David Chende701692017-10-05 13:16:02 -0700213 // Assumes that sStatsdLock is held.
214 private final void informAllUidsLocked(Context context) throws RemoteException {
215 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
216 PackageManager pm = context.getPackageManager();
217 final List<UserInfo> users = um.getUsers(true);
218 if (DEBUG) {
David Chen1481fe12017-10-16 13:16:34 -0700219 Slog.w(TAG, "Iterating over " + users.size() + " profiles.");
David Chende701692017-10-05 13:16:02 -0700220 }
221
222 List<Integer> uids = new ArrayList();
Dianne Hackborn3accca02013-09-20 09:32:11 -0700223 List<Long> versions = new ArrayList();
David Chende701692017-10-05 13:16:02 -0700224 List<String> apps = new ArrayList();
225
226 // Add in all the apps for every user/profile.
227 for (UserInfo profile : users) {
David Chen1481fe12017-10-16 13:16:34 -0700228 List<PackageInfo> pi = pm.getInstalledPackagesAsUser(0, profile.id);
229 for (int j = 0; j < pi.size(); j++) {
230 if (pi.get(j).applicationInfo != null) {
231 uids.add(pi.get(j).applicationInfo.uid);
Dianne Hackborn3accca02013-09-20 09:32:11 -0700232 versions.add(pi.get(j).getLongVersionCode());
David Chen1481fe12017-10-16 13:16:34 -0700233 apps.add(pi.get(j).packageName);
234 }
235 }
David Chende701692017-10-05 13:16:02 -0700236 }
Dianne Hackborn3accca02013-09-20 09:32:11 -0700237 sStatsd.informAllUidData(toIntArray(uids), toLongArray(versions), apps.toArray(new
David Chen1481fe12017-10-16 13:16:34 -0700238 String[apps.size()]));
David Chende701692017-10-05 13:16:02 -0700239 if (DEBUG) {
David Chen1481fe12017-10-16 13:16:34 -0700240 Slog.w(TAG, "Sent data for " + uids.size() + " apps");
David Chende701692017-10-05 13:16:02 -0700241 }
242 }
243
Bookatz36920822018-01-26 09:18:07 -0800244 private final static class AppUpdateReceiver extends BroadcastReceiver {
David Chende701692017-10-05 13:16:02 -0700245 @Override
246 public void onReceive(Context context, Intent intent) {
David Chen47e8f4d2017-10-11 15:34:13 -0700247 /**
248 * App updates actually consist of REMOVE, ADD, and then REPLACE broadcasts. To avoid
249 * waste, we ignore the REMOVE and ADD broadcasts that contain the replacing flag.
David Chend6896892017-10-25 11:49:03 -0700250 * If we can't find the value for EXTRA_REPLACING, we default to false.
David Chen47e8f4d2017-10-11 15:34:13 -0700251 */
David Chend6896892017-10-25 11:49:03 -0700252 if (!intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)
253 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
David Chen47e8f4d2017-10-11 15:34:13 -0700254 return; // Keep only replacing or normal add and remove.
255 }
David Chend6896892017-10-25 11:49:03 -0700256 Slog.i(TAG, "StatsCompanionService noticed an app was updated.");
David Chende701692017-10-05 13:16:02 -0700257 synchronized (sStatsdLock) {
258 if (sStatsd == null) {
yrof6d1ca52017-11-15 15:38:34 -0800259 Slog.w(TAG, "Could not access statsd to inform it of an app update");
David Chende701692017-10-05 13:16:02 -0700260 return;
261 }
262 try {
263 if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
264 Bundle b = intent.getExtras();
265 int uid = b.getInt(Intent.EXTRA_UID);
266 boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
267 if (!replacing) {
268 // Don't bother sending an update if we're right about to get another
269 // intent for the new version that's added.
270 PackageManager pm = context.getPackageManager();
271 String app = intent.getData().getSchemeSpecificPart();
272 sStatsd.informOnePackageRemoved(app, uid);
273 }
274 } else {
275 PackageManager pm = context.getPackageManager();
276 Bundle b = intent.getExtras();
277 int uid = b.getInt(Intent.EXTRA_UID);
278 String app = intent.getData().getSchemeSpecificPart();
279 PackageInfo pi = pm.getPackageInfo(app, PackageManager.MATCH_ANY_USER);
Dianne Hackborn3accca02013-09-20 09:32:11 -0700280 sStatsd.informOnePackage(app, uid, pi.getLongVersionCode());
David Chende701692017-10-05 13:16:02 -0700281 }
282 } catch (Exception e) {
283 Slog.w(TAG, "Failed to inform statsd of an app update", e);
284 }
285 }
286 }
David Chen1481fe12017-10-16 13:16:34 -0700287 }
David Chende701692017-10-05 13:16:02 -0700288
Bookatz582870e2018-02-06 14:24:49 -0800289 public final static class AnomalyAlarmReceiver extends BroadcastReceiver {
Bookatz94726412017-08-31 09:26:15 -0700290 @Override
Bookatzb487b552017-09-18 11:26:01 -0700291 public void onReceive(Context context, Intent intent) {
292 Slog.i(TAG, "StatsCompanionService believes an anomaly has occurred.");
293 synchronized (sStatsdLock) {
294 if (sStatsd == null) {
295 Slog.w(TAG, "Could not access statsd to inform it of anomaly alarm firing");
296 return;
297 }
298 try {
299 // Two-way call to statsd to retain AlarmManager wakelock
300 sStatsd.informAnomalyAlarmFired();
301 } catch (RemoteException e) {
302 Slog.w(TAG, "Failed to inform statsd of anomaly alarm firing", e);
303 }
Bookatz94726412017-08-31 09:26:15 -0700304 }
Bookatzb487b552017-09-18 11:26:01 -0700305 // AlarmManager releases its own wakelock here.
Bookatz94726412017-08-31 09:26:15 -0700306 }
David Chen1481fe12017-10-16 13:16:34 -0700307 }
Bookatzb487b552017-09-18 11:26:01 -0700308
Bookatz582870e2018-02-06 14:24:49 -0800309 public final static class PullingAlarmReceiver extends BroadcastReceiver {
David Chen661f7912018-01-22 17:46:24 -0800310 @Override
311 public void onReceive(Context context, Intent intent) {
312 if (DEBUG)
313 Slog.d(TAG, "Time to poll something.");
314 synchronized (sStatsdLock) {
315 if (sStatsd == null) {
316 Slog.w(TAG, "Could not access statsd to inform it of pulling alarm firing.");
317 return;
318 }
319 try {
320 // Two-way call to statsd to retain AlarmManager wakelock
321 sStatsd.informPollAlarmFired();
322 } catch (RemoteException e) {
323 Slog.w(TAG, "Failed to inform statsd of pulling alarm firing.", e);
324 }
325 }
Bookatzb487b552017-09-18 11:26:01 -0700326 }
David Chen1481fe12017-10-16 13:16:34 -0700327 }
Bookatz94726412017-08-31 09:26:15 -0700328
Bookatz36920822018-01-26 09:18:07 -0800329 private final static class ShutdownEventReceiver extends BroadcastReceiver {
yro947fbce2017-11-15 22:50:23 -0800330 @Override
331 public void onReceive(Context context, Intent intent) {
332 /**
333 * Skip immediately if intent is not relevant to device shutdown.
334 */
335 if (!intent.getAction().equals(Intent.ACTION_REBOOT)
David Chen661f7912018-01-22 17:46:24 -0800336 && !(intent.getAction().equals(Intent.ACTION_SHUTDOWN)
337 && (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0)) {
338 return;
yro947fbce2017-11-15 22:50:23 -0800339 }
yrof7a3bcb2018-01-24 17:18:55 -0800340
yro947fbce2017-11-15 22:50:23 -0800341 Slog.i(TAG, "StatsCompanionService noticed a shutdown.");
342 synchronized (sStatsdLock) {
343 if (sStatsd == null) {
344 Slog.w(TAG, "Could not access statsd to inform it of a shutdown event.");
345 return;
346 }
347 try {
348 sStatsd.writeDataToDisk();
349 } catch (Exception e) {
350 Slog.w(TAG, "Failed to inform statsd of a shutdown event.", e);
351 }
352 }
353 }
354 }
355
Bookatz94726412017-08-31 09:26:15 -0700356 @Override // Binder call
357 public void setAnomalyAlarm(long timestampMs) {
358 enforceCallingPermission();
359 if (DEBUG) Slog.d(TAG, "Setting anomaly alarm for " + timestampMs);
360 final long callingToken = Binder.clearCallingIdentity();
361 try {
362 // using RTC, not RTC_WAKEUP, so if device is asleep, will only fire when it awakens.
363 // This alarm is inexact, leaving its exactness completely up to the OS optimizations.
364 // AlarmManager will automatically cancel any previous mAnomalyAlarmIntent alarm.
365 mAlarmManager.set(AlarmManager.RTC, timestampMs, mAnomalyAlarmIntent);
366 } finally {
367 Binder.restoreCallingIdentity(callingToken);
368 }
369 }
370
371 @Override // Binder call
372 public void cancelAnomalyAlarm() {
373 enforceCallingPermission();
374 if (DEBUG) Slog.d(TAG, "Cancelling anomaly alarm");
375 final long callingToken = Binder.clearCallingIdentity();
376 try {
377 mAlarmManager.cancel(mAnomalyAlarmIntent);
378 } finally {
379 Binder.restoreCallingIdentity(callingToken);
380 }
381 }
382
383 @Override // Binder call
Chenjie Yub3dda412017-10-24 13:41:59 -0700384 public void setPullingAlarms(long timestampMs, long intervalMs) {
David Chen661f7912018-01-22 17:46:24 -0800385 enforceCallingPermission();
386 if (DEBUG)
387 Slog.d(TAG, "Setting pulling alarm for " + timestampMs + " every " + intervalMs + "ms");
388 final long callingToken = Binder.clearCallingIdentity();
389 try {
390 // using RTC, not RTC_WAKEUP, so if device is asleep, will only fire when it awakens.
391 // This alarm is inexact, leaving its exactness completely up to the OS optimizations.
392 // TODO: totally inexact means that stats per bucket could be quite off. Is this okay?
393 mAlarmManager.setRepeating(AlarmManager.RTC, timestampMs, intervalMs, mPullingAlarmIntent);
394 } finally {
395 Binder.restoreCallingIdentity(callingToken);
396 }
Bookatz94726412017-08-31 09:26:15 -0700397 }
398
399 @Override // Binder call
Chenjie Yub3dda412017-10-24 13:41:59 -0700400 public void cancelPullingAlarms() {
David Chen661f7912018-01-22 17:46:24 -0800401 enforceCallingPermission();
402 if (DEBUG)
403 Slog.d(TAG, "Cancelling pulling alarm");
404 final long callingToken = Binder.clearCallingIdentity();
405 try {
406 mAlarmManager.cancel(mPullingAlarmIntent);
407 } finally {
408 Binder.restoreCallingIdentity(callingToken);
409 }
Bookatz94726412017-08-31 09:26:15 -0700410 }
411
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800412 private void addNetworkStats(
David Chen661f7912018-01-22 17:46:24 -0800413 int tag, List<StatsLogEventWrapper> ret, NetworkStats stats, boolean withFGBG) {
414 int size = stats.size();
415 NetworkStats.Entry entry = new NetworkStats.Entry(); // For recycling
416 for (int j = 0; j < size; j++) {
417 stats.getValues(j, entry);
418 StatsLogEventWrapper e = new StatsLogEventWrapper(tag, withFGBG ? 6 : 5);
419 e.writeInt(entry.uid);
420 if (withFGBG) {
421 e.writeInt(entry.set);
422 }
423 e.writeLong(entry.rxBytes);
424 e.writeLong(entry.rxPackets);
425 e.writeLong(entry.txBytes);
426 e.writeLong(entry.txPackets);
427 ret.add(e);
David Chenc8a43242017-10-17 16:23:28 -0700428 }
David Chenc8a43242017-10-17 16:23:28 -0700429 }
430
431 /**
432 * Allows rollups per UID but keeping the set (foreground/background) slicing.
433 * Adapted from groupedByUid in frameworks/base/core/java/android/net/NetworkStats.java
434 */
435 private NetworkStats rollupNetworkStatsByFGBG(NetworkStats stats) {
436 final NetworkStats ret = new NetworkStats(stats.getElapsedRealtime(), 1);
437
438 final NetworkStats.Entry entry = new NetworkStats.Entry();
439 entry.iface = NetworkStats.IFACE_ALL;
440 entry.tag = NetworkStats.TAG_NONE;
441 entry.metered = NetworkStats.METERED_ALL;
442 entry.roaming = NetworkStats.ROAMING_ALL;
443
444 int size = stats.size();
445 NetworkStats.Entry recycle = new NetworkStats.Entry(); // Used for retrieving values
446 for (int i = 0; i < size; i++) {
447 stats.getValues(i, recycle);
448
449 // Skip specific tags, since already counted in TAG_NONE
450 if (recycle.tag != NetworkStats.TAG_NONE) continue;
451
452 entry.set = recycle.set; // Allows slicing by background/foreground
453 entry.uid = recycle.uid;
454 entry.rxBytes = recycle.rxBytes;
455 entry.rxPackets = recycle.rxPackets;
456 entry.txBytes = recycle.txBytes;
457 entry.txPackets = recycle.txPackets;
458 // Operations purposefully omitted since we don't use them for statsd.
459 ret.combineValues(entry);
460 }
461 return ret;
462 }
463
Chenjie Yu05013b32017-11-21 10:21:41 -0800464 /**
465 * Helper method to extract the Parcelable controller info from a
466 * SynchronousResultReceiver.
467 */
468 private static <T extends Parcelable> T awaitControllerInfo(
469 @Nullable SynchronousResultReceiver receiver) {
470 if (receiver == null) {
471 return null;
472 }
473
474 try {
475 final SynchronousResultReceiver.Result result =
476 receiver.awaitResult(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS);
477 if (result.bundle != null) {
478 // This is the final destination for the Bundle.
479 result.bundle.setDefusable(true);
480
481 final T data = result.bundle.getParcelable(
482 RESULT_RECEIVER_CONTROLLER_KEY);
483 if (data != null) {
484 return data;
485 }
486 }
487 Slog.e(TAG, "no controller energy info supplied for " + receiver.getName());
488 } catch (TimeoutException e) {
489 Slog.w(TAG, "timeout reading " + receiver.getName() + " stats");
490 }
491 return null;
492 }
493
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800494 private void pullKernelWakelock(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800495 final KernelWakelockStats wakelockStats =
496 mKernelWakelockReader.readKernelWakelockStats(mTmpWakelockStats);
497 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
498 String name = ent.getKey();
499 KernelWakelockStats.Entry kws = ent.getValue();
500 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 4);
501 e.writeString(name);
502 e.writeInt(kws.mCount);
503 e.writeInt(kws.mVersion);
504 e.writeLong(kws.mTotalTime);
505 pulledData.add(e);
506 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800507 }
508
509 private void pullWifiBytesTransfer(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800510 long token = Binder.clearCallingIdentity();
511 try {
512 // TODO: Consider caching the following call to get BatteryStatsInternal.
513 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
514 String[] ifaces = bs.getWifiIfaces();
515 if (ifaces.length == 0) {
516 return;
517 }
518 NetworkStatsFactory nsf = new NetworkStatsFactory();
519 // Combine all the metrics per Uid into one record.
520 NetworkStats stats =
521 nsf.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces, NetworkStats.TAG_NONE, null)
522 .groupedByUid();
523 addNetworkStats(tagId, pulledData, stats, false);
524 } catch (java.io.IOException e) {
525 Slog.e(TAG, "Pulling netstats for wifi bytes has error", e);
526 } finally {
527 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800528 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800529 }
530
531 private void pullWifiBytesTransferByFgBg(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800532 long token = Binder.clearCallingIdentity();
533 try {
534 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
535 String[] ifaces = bs.getWifiIfaces();
536 if (ifaces.length == 0) {
537 return;
538 }
539 NetworkStatsFactory nsf = new NetworkStatsFactory();
540 NetworkStats stats = rollupNetworkStatsByFGBG(
541 nsf.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces, NetworkStats.TAG_NONE, null));
542 addNetworkStats(tagId, pulledData, stats, true);
543 } catch (java.io.IOException e) {
544 Slog.e(TAG, "Pulling netstats for wifi bytes w/ fg/bg has error", e);
545 } finally {
546 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800547 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800548 }
549
550 private void pullMobileBytesTransfer(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800551 long token = Binder.clearCallingIdentity();
552 try {
553 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
554 String[] ifaces = bs.getMobileIfaces();
555 if (ifaces.length == 0) {
556 return;
557 }
558 NetworkStatsFactory nsf = new NetworkStatsFactory();
559 // Combine all the metrics per Uid into one record.
560 NetworkStats stats =
561 nsf.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces, NetworkStats.TAG_NONE, null)
562 .groupedByUid();
563 addNetworkStats(tagId, pulledData, stats, false);
564 } catch (java.io.IOException e) {
565 Slog.e(TAG, "Pulling netstats for mobile bytes has error", e);
566 } finally {
567 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800568 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800569 }
570
571 private void pullBluetoothBytesTransfer(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800572 BluetoothActivityEnergyInfo info = pullBluetoothData();
573 for (UidTraffic traffic : info.getUidTraffic()) {
574 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 3);
575 e.writeInt(traffic.getUid());
576 e.writeLong(traffic.getRxBytes());
577 e.writeLong(traffic.getTxBytes());
578 pulledData.add(e);
579 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800580 }
581
582 private void pullMobileBytesTransferByFgBg(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800583 long token = Binder.clearCallingIdentity();
584 try {
585 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
586 String[] ifaces = bs.getMobileIfaces();
587 if (ifaces.length == 0) {
588 return;
589 }
590 NetworkStatsFactory nsf = new NetworkStatsFactory();
591 NetworkStats stats = rollupNetworkStatsByFGBG(
592 nsf.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces, NetworkStats.TAG_NONE, null));
593 addNetworkStats(tagId, pulledData, stats, true);
594 } catch (java.io.IOException e) {
595 Slog.e(TAG, "Pulling netstats for mobile bytes w/ fg/bg has error", e);
596 } finally {
597 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800598 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800599 }
600
601 private void pullCpuTimePerFreq(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800602 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
603 long[] clusterTimeMs = mKernelCpuSpeedReaders[cluster].readAbsolute();
604 if (clusterTimeMs != null) {
605 for (int speed = clusterTimeMs.length - 1; speed >= 0; --speed) {
606 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 3);
607 e.writeInt(cluster);
608 e.writeInt(speed);
609 e.writeLong(clusterTimeMs[speed]);
610 pulledData.add(e);
611 }
612 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800613 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800614 }
615
616 private void pullWifiActivityEnergyInfo(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800617 long token = Binder.clearCallingIdentity();
618 if (mWifiManager == null) {
619 mWifiManager =
620 IWifiManager.Stub.asInterface(ServiceManager.getService(Context.WIFI_SERVICE));
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800621 }
David Chen661f7912018-01-22 17:46:24 -0800622 if (mWifiManager != null) {
623 try {
624 SynchronousResultReceiver wifiReceiver = new SynchronousResultReceiver("wifi");
625 mWifiManager.requestActivityInfo(wifiReceiver);
626 final WifiActivityEnergyInfo wifiInfo = awaitControllerInfo(wifiReceiver);
627 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 6);
628 e.writeLong(wifiInfo.getTimeStamp());
629 e.writeInt(wifiInfo.getStackState());
630 e.writeLong(wifiInfo.getControllerTxTimeMillis());
631 e.writeLong(wifiInfo.getControllerRxTimeMillis());
632 e.writeLong(wifiInfo.getControllerIdleTimeMillis());
633 e.writeLong(wifiInfo.getControllerEnergyUsed());
634 pulledData.add(e);
635 } catch (RemoteException e) {
636 Slog.e(TAG, "Pulling wifiManager for wifi controller activity energy info has error", e);
637 } finally {
638 Binder.restoreCallingIdentity(token);
639 }
640 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800641 }
642
643 private void pullModemActivityInfo(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800644 long token = Binder.clearCallingIdentity();
645 if (mTelephony == null) {
646 mTelephony = TelephonyManager.from(mContext);
647 }
648 if (mTelephony != null) {
649 SynchronousResultReceiver modemReceiver = new SynchronousResultReceiver("telephony");
650 mTelephony.requestModemActivityInfo(modemReceiver);
651 final ModemActivityInfo modemInfo = awaitControllerInfo(modemReceiver);
652 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 6);
653 e.writeLong(modemInfo.getTimestamp());
654 e.writeLong(modemInfo.getSleepTimeMillis());
655 e.writeLong(modemInfo.getIdleTimeMillis());
656 e.writeLong(modemInfo.getTxTimeMillis()[0]);
657 e.writeLong(modemInfo.getTxTimeMillis()[1]);
658 e.writeLong(modemInfo.getTxTimeMillis()[2]);
659 e.writeLong(modemInfo.getTxTimeMillis()[3]);
660 e.writeLong(modemInfo.getTxTimeMillis()[4]);
661 e.writeLong(modemInfo.getRxTimeMillis());
662 e.writeLong(modemInfo.getEnergyUsed());
663 pulledData.add(e);
664 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800665 }
666
667 private void pullBluetoothActivityInfo(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800668 BluetoothActivityEnergyInfo info = pullBluetoothData();
669 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 6);
670 e.writeLong(info.getTimeStamp());
671 e.writeInt(info.getBluetoothStackState());
672 e.writeLong(info.getControllerTxTimeMillis());
673 e.writeLong(info.getControllerRxTimeMillis());
674 e.writeLong(info.getControllerIdleTimeMillis());
675 e.writeLong(info.getControllerEnergyUsed());
676 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800677 }
678
679 private synchronized BluetoothActivityEnergyInfo pullBluetoothData() {
Chenjie Yuc2d65442018-02-01 22:27:17 -0800680 final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
David Chen661f7912018-01-22 17:46:24 -0800681 if (adapter != null) {
682 SynchronousResultReceiver bluetoothReceiver = new SynchronousResultReceiver("bluetooth");
683 adapter.requestControllerActivityEnergyInfo(bluetoothReceiver);
684 return awaitControllerInfo(bluetoothReceiver);
685 } else {
686 Slog.e(TAG, "Failed to get bluetooth adapter!");
687 return null;
688 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800689 }
690
691 private void pullSystemElapsedRealtime(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800692 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 1);
693 e.writeLong(SystemClock.elapsedRealtime());
694 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800695 }
696
697 private void pullDiskSpace(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800698 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 3);
699 e.writeLong(mStatFsData.getAvailableBytes());
700 e.writeLong(mStatFsSystem.getAvailableBytes());
701 e.writeLong(mStatFsTemp.getAvailableBytes());
702 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800703 }
704
705 private void pullSystemUpTime(int tagId, List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800706 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, 1);
707 e.writeLong(SystemClock.uptimeMillis());
708 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800709 }
710
Chenjie Yu05013b32017-11-21 10:21:41 -0800711 /**
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800712 * Pulls various data.
Chenjie Yu05013b32017-11-21 10:21:41 -0800713 */
Bookatzc68a9d22017-09-27 14:09:55 -0700714 @Override // Binder call
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700715 public StatsLogEventWrapper[] pullData(int tagId) {
Bookatzc68a9d22017-09-27 14:09:55 -0700716 enforceCallingPermission();
David Chenc8a43242017-10-17 16:23:28 -0700717 if (DEBUG)
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700718 Slog.d(TAG, "Pulling " + tagId);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800719 List<StatsLogEventWrapper> ret = new ArrayList();
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700720 switch (tagId) {
Chenjie Yu31d14d72017-12-12 17:54:33 -0800721 case StatsLog.WIFI_BYTES_TRANSFER: {
David Chen661f7912018-01-22 17:46:24 -0800722 pullWifiBytesTransfer(tagId, ret);
723 break;
David Chenc8a43242017-10-17 16:23:28 -0700724 }
Chenjie Yu31d14d72017-12-12 17:54:33 -0800725 case StatsLog.MOBILE_BYTES_TRANSFER: {
David Chen661f7912018-01-22 17:46:24 -0800726 pullMobileBytesTransfer(tagId, ret);
727 break;
David Chenc8a43242017-10-17 16:23:28 -0700728 }
Chenjie Yu31d14d72017-12-12 17:54:33 -0800729 case StatsLog.WIFI_BYTES_TRANSFER_BY_FG_BG: {
David Chen661f7912018-01-22 17:46:24 -0800730 pullWifiBytesTransferByFgBg(tagId, ret);
731 break;
David Chenc8a43242017-10-17 16:23:28 -0700732 }
Chenjie Yu31d14d72017-12-12 17:54:33 -0800733 case StatsLog.MOBILE_BYTES_TRANSFER_BY_FG_BG: {
David Chen661f7912018-01-22 17:46:24 -0800734 pullMobileBytesTransferByFgBg(tagId, ret);
735 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800736 }
737 case StatsLog.BLUETOOTH_BYTES_TRANSFER: {
David Chen661f7912018-01-22 17:46:24 -0800738 pullBluetoothBytesTransfer(tagId, ret);
739 break;
David Chenc8a43242017-10-17 16:23:28 -0700740 }
Chenjie Yu31d14d72017-12-12 17:54:33 -0800741 case StatsLog.KERNEL_WAKELOCK: {
David Chen661f7912018-01-22 17:46:24 -0800742 pullKernelWakelock(tagId, ret);
743 break;
David Chen1481fe12017-10-16 13:16:34 -0700744 }
Chenjie Yu31d14d72017-12-12 17:54:33 -0800745 case StatsLog.CPU_TIME_PER_FREQ: {
David Chen661f7912018-01-22 17:46:24 -0800746 pullCpuTimePerFreq(tagId, ret);
747 break;
Chenjie Yu7f8def92017-11-03 09:33:15 -0700748 }
Chenjie Yu31d14d72017-12-12 17:54:33 -0800749 case StatsLog.WIFI_ACTIVITY_ENERGY_INFO: {
David Chen661f7912018-01-22 17:46:24 -0800750 pullWifiActivityEnergyInfo(tagId, ret);
751 break;
Chenjie Yu05013b32017-11-21 10:21:41 -0800752 }
Chenjie Yu31d14d72017-12-12 17:54:33 -0800753 case StatsLog.MODEM_ACTIVITY_INFO: {
David Chen661f7912018-01-22 17:46:24 -0800754 pullModemActivityInfo(tagId, ret);
755 break;
Chenjie Yu05013b32017-11-21 10:21:41 -0800756 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800757 case StatsLog.BLUETOOTH_ACTIVITY_INFO: {
David Chen661f7912018-01-22 17:46:24 -0800758 pullBluetoothActivityInfo(tagId, ret);
759 break;
Chenjie Yu937d7422018-01-10 16:37:53 -0800760 }
761 case StatsLog.SYSTEM_UPTIME: {
David Chen661f7912018-01-22 17:46:24 -0800762 pullSystemUpTime(tagId, ret);
763 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800764 }
765 case StatsLog.SYSTEM_ELAPSED_REALTIME: {
David Chen661f7912018-01-22 17:46:24 -0800766 pullSystemElapsedRealtime(tagId, ret);
767 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800768 }
769 case StatsLog.DISK_SPACE: {
David Chen661f7912018-01-22 17:46:24 -0800770 pullDiskSpace(tagId, ret);
771 break;
Chenjie Yu9da105b2018-01-13 12:41:08 -0800772 }
Bookatzc68a9d22017-09-27 14:09:55 -0700773 default:
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700774 Slog.w(TAG, "No such tagId data as " + tagId);
Bookatzc68a9d22017-09-27 14:09:55 -0700775 return null;
776 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800777 return ret.toArray(new StatsLogEventWrapper[ret.size()]);
Bookatzc68a9d22017-09-27 14:09:55 -0700778 }
779
780 @Override // Binder call
Bookatzb487b552017-09-18 11:26:01 -0700781 public void statsdReady() {
782 enforceCallingPermission();
783 if (DEBUG) Slog.d(TAG, "learned that statsdReady");
784 sayHiToStatsd(); // tell statsd that we're ready too and link to it
Bookatz0eb58ae392018-01-25 15:49:26 -0800785 mContext.sendBroadcastAsUser(new Intent(StatsManager.ACTION_STATSD_STARTED),
786 UserHandle.SYSTEM,
Bookatz5c800e32018-01-24 14:59:52 -0800787 android.Manifest.permission.DUMP);
Bookatzb487b552017-09-18 11:26:01 -0700788 }
789
David Chenc136f452017-11-27 11:52:26 -0800790 @Override
791 public void triggerUidSnapshot() {
David Chen661f7912018-01-22 17:46:24 -0800792 enforceCallingPermission();
793 synchronized (sStatsdLock) {
794 try {
795 informAllUidsLocked(mContext);
796 } catch (RemoteException e) {
797 Slog.e(TAG, "Failed to trigger uid snapshot.", e);
798 }
David Chenc136f452017-11-27 11:52:26 -0800799 }
David Chenc136f452017-11-27 11:52:26 -0800800 }
801
Bookatz94726412017-08-31 09:26:15 -0700802 private void enforceCallingPermission() {
803 if (Binder.getCallingPid() == Process.myPid()) {
804 return;
805 }
806 mContext.enforceCallingPermission(android.Manifest.permission.STATSCOMPANION, null);
807 }
808
Bookatzb487b552017-09-18 11:26:01 -0700809 // Lifecycle and related code
810
David Chen1481fe12017-10-16 13:16:34 -0700811 /**
812 * Fetches the statsd IBinder service
813 */
Bookatzb487b552017-09-18 11:26:01 -0700814 private static IStatsManager fetchStatsdService() {
815 return IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
816 }
817
818 public static final class Lifecycle extends SystemService {
819 private StatsCompanionService mStatsCompanionService;
820
821 public Lifecycle(Context context) {
822 super(context);
823 }
824
825 @Override
826 public void onStart() {
827 mStatsCompanionService = new StatsCompanionService(getContext());
828 try {
829 publishBinderService(Context.STATS_COMPANION_SERVICE, mStatsCompanionService);
830 if (DEBUG) Slog.d(TAG, "Published " + Context.STATS_COMPANION_SERVICE);
831 } catch (Exception e) {
832 Slog.e(TAG, "Failed to publishBinderService", e);
833 }
834 }
835
836 @Override
837 public void onBootPhase(int phase) {
838 super.onBootPhase(phase);
839 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
840 mStatsCompanionService.systemReady();
841 }
842 }
843 }
844
David Chen1481fe12017-10-16 13:16:34 -0700845 /**
846 * Now that the android system is ready, StatsCompanion is ready too, so inform statsd.
847 */
Bookatzb487b552017-09-18 11:26:01 -0700848 private void systemReady() {
849 if (DEBUG) Slog.d(TAG, "Learned that systemReady");
850 sayHiToStatsd();
851 }
852
David Chen1481fe12017-10-16 13:16:34 -0700853 /**
854 * Tells statsd that statscompanion is ready. If the binder call returns, link to statsd.
855 */
Bookatzb487b552017-09-18 11:26:01 -0700856 private void sayHiToStatsd() {
857 synchronized (sStatsdLock) {
858 if (sStatsd != null) {
859 Slog.e(TAG, "Trying to fetch statsd, but it was already fetched",
860 new IllegalStateException("sStatsd is not null when being fetched"));
861 return;
862 }
863 sStatsd = fetchStatsdService();
864 if (sStatsd == null) {
865 Slog.w(TAG, "Could not access statsd");
866 return;
867 }
868 if (DEBUG) Slog.d(TAG, "Saying hi to statsd");
869 try {
870 sStatsd.statsCompanionReady();
871 // If the statsCompanionReady two-way binder call returns, link to statsd.
872 try {
873 sStatsd.asBinder().linkToDeath(new StatsdDeathRecipient(), 0);
874 } catch (RemoteException e) {
875 Slog.e(TAG, "linkToDeath(StatsdDeathRecipient) failed", e);
876 forgetEverything();
877 }
yro947fbce2017-11-15 22:50:23 -0800878 // Setup broadcast receiver for updates.
David Chende701692017-10-05 13:16:02 -0700879 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REPLACED);
880 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
881 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
882 filter.addDataScheme("package");
883 mContext.registerReceiverAsUser(mAppUpdateReceiver, UserHandle.ALL, filter, null,
David Chen1481fe12017-10-16 13:16:34 -0700884 null);
David Chen47e8f4d2017-10-11 15:34:13 -0700885
886 // Setup receiver for user initialize (which happens once for a new user) and
887 // if a user is removed.
888 filter = new IntentFilter(Intent.ACTION_USER_INITIALIZE);
889 filter.addAction(Intent.ACTION_USER_REMOVED);
890 mContext.registerReceiverAsUser(mUserUpdateReceiver, UserHandle.ALL,
David Chen1481fe12017-10-16 13:16:34 -0700891 filter, null, null);
David Chen47e8f4d2017-10-11 15:34:13 -0700892
yro947fbce2017-11-15 22:50:23 -0800893 // Setup receiver for device reboots or shutdowns.
894 filter = new IntentFilter(Intent.ACTION_REBOOT);
895 filter.addAction(Intent.ACTION_SHUTDOWN);
896 mContext.registerReceiverAsUser(
897 mShutdownEventReceiver, UserHandle.ALL, filter, null, null);
Yao Chen0f217102018-01-09 10:33:15 -0800898 final long token = Binder.clearCallingIdentity();
899 try {
900 // Pull the latest state of UID->app name, version mapping when statsd starts.
901 informAllUidsLocked(mContext);
902 } finally {
903 restoreCallingIdentity(token);
904 }
Bookatzb487b552017-09-18 11:26:01 -0700905 } catch (RemoteException e) {
906 Slog.e(TAG, "Failed to inform statsd that statscompanion is ready", e);
907 forgetEverything();
908 }
909 }
910 }
911
912 private class StatsdDeathRecipient implements IBinder.DeathRecipient {
913 @Override
914 public void binderDied() {
915 Slog.i(TAG, "Statsd is dead - erase all my knowledge.");
916 forgetEverything();
917 }
918 }
919
920 private void forgetEverything() {
921 synchronized (sStatsdLock) {
922 sStatsd = null;
David Chende701692017-10-05 13:16:02 -0700923 mContext.unregisterReceiver(mAppUpdateReceiver);
David Chen47e8f4d2017-10-11 15:34:13 -0700924 mContext.unregisterReceiver(mUserUpdateReceiver);
yro947fbce2017-11-15 22:50:23 -0800925 mContext.unregisterReceiver(mShutdownEventReceiver);
Bookatzb487b552017-09-18 11:26:01 -0700926 cancelAnomalyAlarm();
Chenjie Yub3dda412017-10-24 13:41:59 -0700927 cancelPullingAlarms();
Bookatzb487b552017-09-18 11:26:01 -0700928 }
929 }
930
Bookatz94726412017-08-31 09:26:15 -0700931}