blob: 9f1eace321807a74f451cf7ad4ad4264f36d239d [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
Philip P. Moltmannf21a3502019-01-30 09:53:04 -080018import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
19import static android.content.pm.PermissionInfo.PROTECTION_DANGEROUS;
Rafal Slawikc3762622018-11-07 12:07:26 +000020import static android.os.Process.getPidsForCommands;
21import static android.os.Process.getUidForPid;
22
Chenjie Yuab530202018-09-26 12:39:20 -070023import static com.android.internal.util.Preconditions.checkNotNull;
Rafal Slawikc3762622018-11-07 12:07:26 +000024import static com.android.server.am.MemoryStatUtil.readCmdlineFromProcfs;
25import static com.android.server.am.MemoryStatUtil.readMemoryStatFromProcfs;
Rafal Slawik3bea8952018-11-15 12:39:33 +000026import static com.android.server.am.MemoryStatUtil.readRssHighWaterMarkFromProcfs;
Rafal Slawikd4e87572019-03-12 13:08:38 +000027import static com.android.server.am.MemoryStatUtil.readSystemIonHeapSizeFromDebugfs;
Chenjie Yuab530202018-09-26 12:39:20 -070028
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -080029import android.annotation.NonNull;
Chenjie Yu05013b32017-11-21 10:21:41 -080030import android.annotation.Nullable;
Rajeev Kumar22d92b72018-02-07 18:38:36 -080031import android.app.ActivityManagerInternal;
Bookatz94726412017-08-31 09:26:15 -070032import android.app.AlarmManager;
Bookatz75158ac2018-05-18 15:55:23 -070033import android.app.AlarmManager.OnAlarmListener;
Rafal Slawik3bea8952018-11-15 12:39:33 +000034import android.app.ProcessMemoryHighWaterMark;
Rajeev Kumar22d92b72018-02-07 18:38:36 -080035import android.app.ProcessMemoryState;
Bookatzc6977972018-01-16 16:55:05 -080036import android.app.StatsManager;
Chenjie Yu9d7720b2018-01-24 10:34:48 -080037import android.bluetooth.BluetoothActivityEnergyInfo;
38import android.bluetooth.BluetoothAdapter;
39import android.bluetooth.UidTraffic;
Bookatz94726412017-08-31 09:26:15 -070040import android.content.BroadcastReceiver;
41import android.content.Context;
42import android.content.Intent;
David Chende701692017-10-05 13:16:02 -070043import android.content.IntentFilter;
Bookatzc6977972018-01-16 16:55:05 -080044import android.content.IntentSender;
David Chende701692017-10-05 13:16:02 -070045import android.content.pm.PackageInfo;
46import android.content.pm.PackageManager;
Philip P. Moltmannf21a3502019-01-30 09:53:04 -080047import android.content.pm.PermissionInfo;
David Chende701692017-10-05 13:16:02 -070048import android.content.pm.UserInfo;
Kevin Chyn6ecc5702019-01-28 12:00:37 -080049import android.hardware.biometrics.BiometricsProtoEnums;
50import android.hardware.face.FaceManager;
Tej Singhd6d6d772018-09-05 17:41:25 -070051import android.hardware.fingerprint.FingerprintManager;
Chenjie Yuae9dfac2018-10-25 16:06:56 -070052import android.net.ConnectivityManager;
Chenbo Fenge62e2872019-01-11 15:50:17 -080053import android.net.INetworkStatsService;
Chenjie Yuae9dfac2018-10-25 16:06:56 -070054import android.net.Network;
55import android.net.NetworkRequest;
David Chenc8a43242017-10-17 16:23:28 -070056import android.net.NetworkStats;
Chenjie Yu05013b32017-11-21 10:21:41 -080057import android.net.wifi.IWifiManager;
58import android.net.wifi.WifiActivityEnergyInfo;
Bookatz75ee6042018-11-09 12:27:37 -080059import android.os.BatteryStats;
David Chenc8a43242017-10-17 16:23:28 -070060import android.os.BatteryStatsInternal;
Bookatz94726412017-08-31 09:26:15 -070061import android.os.Binder;
Bookatz366a4432018-11-20 09:42:33 -080062import android.os.Build;
David Chende701692017-10-05 13:16:02 -070063import android.os.Bundle;
Chenjie Yu937d7422018-01-10 16:37:53 -080064import android.os.Environment;
yroe26c97b2018-03-27 10:30:11 -070065import android.os.FileUtils;
Olivier Gaillard21fb5232018-10-09 13:19:27 +010066import android.os.Handler;
67import android.os.HandlerThread;
Bookatzb487b552017-09-18 11:26:01 -070068import android.os.IBinder;
Bookatz94726412017-08-31 09:26:15 -070069import android.os.IStatsCompanionService;
70import android.os.IStatsManager;
Tej Singh86dc9db2018-09-06 00:39:57 +000071import android.os.IStoraged;
Yangster-mace16189a2018-08-26 12:20:16 -070072import android.os.IThermalEventListener;
73import android.os.IThermalService;
Olivier Gaillard21fb5232018-10-09 13:19:27 +010074import android.os.Looper;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -070075import android.os.ParcelFileDescriptor;
Chenjie Yu05013b32017-11-21 10:21:41 -080076import android.os.Parcelable;
Bookatz94726412017-08-31 09:26:15 -070077import android.os.Process;
Bookatz1b0b1142017-09-08 11:58:42 -070078import android.os.RemoteException;
Bookatz94726412017-08-31 09:26:15 -070079import android.os.ServiceManager;
Chenjie Yu937d7422018-01-10 16:37:53 -080080import android.os.StatFs;
Chenjie Yu9d7720b2018-01-24 10:34:48 -080081import android.os.StatsDimensionsValue;
David Chen1481fe12017-10-16 13:16:34 -070082import android.os.StatsLogEventWrapper;
Chenjie Yu05013b32017-11-21 10:21:41 -080083import android.os.SynchronousResultReceiver;
Chenjie Yu937d7422018-01-10 16:37:53 -080084import android.os.SystemClock;
Rafal Slawik44b88142018-12-15 16:48:09 +000085import android.os.SystemProperties;
Yangster-mace16189a2018-08-26 12:20:16 -070086import android.os.Temperature;
David Chende701692017-10-05 13:16:02 -070087import android.os.UserHandle;
88import android.os.UserManager;
Carmen Agimof35f7f6f2019-02-05 18:19:21 +000089import android.os.storage.DiskInfo;
Tej Singh86dc9db2018-09-06 00:39:57 +000090import android.os.storage.StorageManager;
Carmen Agimof35f7f6f2019-02-05 18:19:21 +000091import android.os.storage.VolumeInfo;
Chenjie Yu937d7422018-01-10 16:37:53 -080092import android.telephony.ModemActivityInfo;
93import android.telephony.TelephonyManager;
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +010094import android.util.ArrayMap;
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -080095import android.util.ArraySet;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -070096import android.util.Log;
Bookatz94726412017-08-31 09:26:15 -070097import android.util.Slog;
David Chenc8a43242017-10-17 16:23:28 -070098import android.util.StatsLog;
Chenjie Yuab530202018-09-26 12:39:20 -070099import android.util.proto.ProtoOutputStream;
David Chenc8a43242017-10-17 16:23:28 -0700100
101import com.android.internal.annotations.GuardedBy;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700102import com.android.internal.app.procstats.IProcessStats;
103import com.android.internal.app.procstats.ProcessStats;
Bookatz75ee6042018-11-09 12:27:37 -0800104import com.android.internal.os.BatterySipper;
105import com.android.internal.os.BatteryStatsHelper;
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +0100106import com.android.internal.os.BinderCallsStats.ExportedCallStat;
Chenjie Yu937d7422018-01-10 16:37:53 -0800107import com.android.internal.os.KernelCpuSpeedReader;
Misha Wagner5a51e002018-10-03 15:04:09 +0100108import com.android.internal.os.KernelCpuThreadReader;
Misha Wagner4b32c9f2019-01-25 15:30:14 +0000109import com.android.internal.os.KernelCpuThreadReaderSettingsObserver;
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800110import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidActiveTimeReader;
111import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidClusterTimeReader;
112import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidFreqTimeReader;
113import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidUserSysTimeReader;
David Chenc8a43242017-10-17 16:23:28 -0700114import com.android.internal.os.KernelWakelockReader;
115import com.android.internal.os.KernelWakelockStats;
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +0100116import com.android.internal.os.LooperStats;
Chenjie Yu7f8def92017-11-03 09:33:15 -0700117import com.android.internal.os.PowerProfile;
Yangster-mac308ea0c2018-10-22 13:10:25 -0700118import com.android.internal.os.ProcessCpuTracker;
Tej Singhe7726dc2018-09-21 11:42:12 -0700119import com.android.internal.os.StoragedUidIoStatsReader;
yroe26c97b2018-03-27 10:30:11 -0700120import com.android.internal.util.DumpUtils;
Olivier Gaillard289ba402018-07-24 18:50:13 +0100121import com.android.server.BinderCallsStatsService;
David Chenc8a43242017-10-17 16:23:28 -0700122import com.android.server.LocalServices;
123import com.android.server.SystemService;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700124import com.android.server.SystemServiceManager;
Rafal Slawikc3762622018-11-07 12:07:26 +0000125import com.android.server.am.MemoryStatUtil.MemoryStat;
Hai Zhang85fd0622019-02-01 14:06:04 -0800126import com.android.server.role.RoleManagerInternal;
Tej Singh86dc9db2018-09-06 00:39:57 +0000127import com.android.server.storage.DiskStatsFileLogger;
128import com.android.server.storage.DiskStatsLoggingService;
129
130import libcore.io.IoUtils;
131
132import org.json.JSONArray;
133import org.json.JSONException;
134import org.json.JSONObject;
Bookatz94726412017-08-31 09:26:15 -0700135
yroe26c97b2018-03-27 10:30:11 -0700136import java.io.File;
137import java.io.FileDescriptor;
Tej Singh86dc9db2018-09-06 00:39:57 +0000138import java.io.FileOutputStream;
139import java.io.IOException;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700140import java.io.InputStream;
yroe26c97b2018-03-27 10:30:11 -0700141import java.io.PrintWriter;
David Chende701692017-10-05 13:16:02 -0700142import java.util.ArrayList;
Bookatz058d8692018-03-06 09:53:47 -0800143import java.util.Arrays;
yroe26c97b2018-03-27 10:30:11 -0700144import java.util.HashMap;
145import java.util.HashSet;
David Chende701692017-10-05 13:16:02 -0700146import java.util.List;
Bookatzc68a9d22017-09-27 14:09:55 -0700147import java.util.Map;
Olivier Gaillard6f52d152018-07-25 12:13:12 +0100148import java.util.Map.Entry;
yroe26c97b2018-03-27 10:30:11 -0700149import java.util.concurrent.TimeUnit;
Chenjie Yu05013b32017-11-21 10:21:41 -0800150import java.util.concurrent.TimeoutException;
Bookatzc68a9d22017-09-27 14:09:55 -0700151
Bookatz94726412017-08-31 09:26:15 -0700152/**
153 * Helper service for statsd (the native stats management service in cmds/statsd/).
154 * Used for registering and receiving alarms on behalf of statsd.
David Chen1481fe12017-10-16 13:16:34 -0700155 *
Bookatz6bc51d72017-09-28 16:43:40 -0700156 * @hide
Bookatz94726412017-08-31 09:26:15 -0700157 */
158public class StatsCompanionService extends IStatsCompanionService.Stub {
Chenjie Yu05013b32017-11-21 10:21:41 -0800159 /**
160 * How long to wait on an individual subsystem to return its stats.
161 */
162 private static final long EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS = 2000;
yroe26c97b2018-03-27 10:30:11 -0700163 private static final long MILLIS_IN_A_DAY = TimeUnit.DAYS.toMillis(1);
Chenjie Yu05013b32017-11-21 10:21:41 -0800164
165 public static final String RESULT_RECEIVER_CONTROLLER_KEY = "controller_activity";
yroe26c97b2018-03-27 10:30:11 -0700166 public static final String CONFIG_DIR = "/data/misc/stats-service";
Chenjie Yu05013b32017-11-21 10:21:41 -0800167
Bookatz94726412017-08-31 09:26:15 -0700168 static final String TAG = "StatsCompanionService";
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700169 static final boolean DEBUG = false;
Bookatzc6977972018-01-16 16:55:05 -0800170
David Chen661f7912018-01-22 17:46:24 -0800171 public static final int CODE_DATA_BROADCAST = 1;
Bookatzc6977972018-01-16 16:55:05 -0800172 public static final int CODE_SUBSCRIBER_BROADCAST = 1;
Tej Singh6ede28b2019-01-29 17:06:54 -0800173 public static final int CODE_ACTIVE_CONFIGS_BROADCAST = 1;
David Chend37bc232018-04-12 18:05:11 -0700174 /**
175 * The last report time is provided with each intent registered to
176 * StatsManager#setFetchReportsOperation. This allows easy de-duping in the receiver if
177 * statsd is requesting the client to retrieve the same statsd data. The last report time
178 * corresponds to the last_report_elapsed_nanos that will provided in the current
179 * ConfigMetricsReport, and this timestamp also corresponds to the
180 * current_report_elapsed_nanos of the most recently obtained ConfigMetricsReport.
181 */
182 public static final String EXTRA_LAST_REPORT_TIME = "android.app.extra.LAST_REPORT_TIME";
yroe26c97b2018-03-27 10:30:11 -0700183 public static final int DEATH_THRESHOLD = 10;
Rafal Slawik3bea8952018-11-15 12:39:33 +0000184 /**
185 * Which native processes to snapshot memory for.
186 *
187 * <p>Processes are matched by their cmdline in procfs. Example: cat /proc/pid/cmdline returns
188 * /system/bin/statsd for the stats daemon.
189 */
190 private static final String[] MEMORY_INTERESTING_NATIVE_PROCESSES = new String[]{
191 "/system/bin/statsd", // Stats daemon.
192 "/system/bin/surfaceflinger",
193 "/system/bin/apexd", // APEX daemon.
194 "/system/bin/audioserver",
195 "/system/bin/cameraserver",
196 "/system/bin/drmserver",
197 "/system/bin/healthd",
198 "/system/bin/incidentd",
199 "/system/bin/installd",
200 "/system/bin/lmkd", // Low memory killer daemon.
201 "/system/bin/logd",
202 "media.codec",
203 "media.extractor",
204 "media.metrics",
205 "/system/bin/mediadrmserver",
206 "/system/bin/mediaserver",
207 "/system/bin/performanced",
208 "/system/bin/tombstoned",
209 "/system/bin/traced", // Perfetto.
210 "/system/bin/traced_probes", // Perfetto.
211 "webview_zygote",
Rafal Slawik932c71e2018-11-30 16:10:32 +0000212 "zygote",
213 "zygote64",
Rafal Slawik3bea8952018-11-15 12:39:33 +0000214 };
Bookatzc6977972018-01-16 16:55:05 -0800215
Misha Wagner4b32c9f2019-01-25 15:30:14 +0000216 private static final int CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES = 8;
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100217
218 static final class CompanionHandler extends Handler {
219 CompanionHandler(Looper looper) {
220 super(looper);
221 }
222 }
223
Bookatz94726412017-08-31 09:26:15 -0700224 private final Context mContext;
225 private final AlarmManager mAlarmManager;
Chenbo Fenge62e2872019-01-11 15:50:17 -0800226 private final INetworkStatsService mNetworkStatsService;
Bookatzb487b552017-09-18 11:26:01 -0700227 @GuardedBy("sStatsdLock")
Bookatz1b0b1142017-09-08 11:58:42 -0700228 private static IStatsManager sStatsd;
Bookatzb487b552017-09-18 11:26:01 -0700229 private static final Object sStatsdLock = new Object();
Bookatz94726412017-08-31 09:26:15 -0700230
Bookatz75158ac2018-05-18 15:55:23 -0700231 private final OnAlarmListener mAnomalyAlarmListener = new AnomalyAlarmListener();
232 private final OnAlarmListener mPullingAlarmListener = new PullingAlarmListener();
233 private final OnAlarmListener mPeriodicAlarmListener = new PeriodicAlarmListener();
David Chende701692017-10-05 13:16:02 -0700234 private final BroadcastReceiver mAppUpdateReceiver;
David Chen47e8f4d2017-10-11 15:34:13 -0700235 private final BroadcastReceiver mUserUpdateReceiver;
yro947fbce2017-11-15 22:50:23 -0800236 private final ShutdownEventReceiver mShutdownEventReceiver;
Chenjie Yu7f8def92017-11-03 09:33:15 -0700237 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
238 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
Chenjie Yu05013b32017-11-21 10:21:41 -0800239 private IWifiManager mWifiManager = null;
240 private TelephonyManager mTelephony = null;
yroe26c97b2018-03-27 10:30:11 -0700241 @GuardedBy("sStatsdLock")
242 private final HashSet<Long> mDeathTimeMillis = new HashSet<>();
243 @GuardedBy("sStatsdLock")
244 private final HashMap<Long, String> mDeletedFiles = new HashMap<>();
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100245 private final CompanionHandler mHandler;
Bookatz94726412017-08-31 09:26:15 -0700246
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800247 // Disables throttler on CPU time readers.
248 private KernelCpuUidUserSysTimeReader mCpuUidUserSysTimeReader =
249 new KernelCpuUidUserSysTimeReader(false);
Chenjie Yuec676612018-03-07 09:19:17 -0800250 private KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800251 private KernelCpuUidFreqTimeReader mCpuUidFreqTimeReader =
252 new KernelCpuUidFreqTimeReader(false);
253 private KernelCpuUidActiveTimeReader mCpuUidActiveTimeReader =
254 new KernelCpuUidActiveTimeReader(false);
255 private KernelCpuUidClusterTimeReader mCpuUidClusterTimeReader =
256 new KernelCpuUidClusterTimeReader(false);
Tej Singhe7726dc2018-09-21 11:42:12 -0700257 private StoragedUidIoStatsReader mStoragedUidIoStatsReader =
258 new StoragedUidIoStatsReader();
Misha Wagner5a51e002018-10-03 15:04:09 +0100259 @Nullable
260 private final KernelCpuThreadReader mKernelCpuThreadReader;
Chenjie Yuec676612018-03-07 09:19:17 -0800261
Olivier Gaillard18d452202019-01-22 15:03:41 +0000262 private long mDebugElapsedClockPreviousValue = 0;
263 private long mDebugElapsedClockPullCount = 0;
264 private long mDebugFailingElapsedClockPreviousValue = 0;
265 private long mDebugFailingElapsedClockPullCount = 0;
Bookatz75ee6042018-11-09 12:27:37 -0800266 private BatteryStatsHelper mBatteryStatsHelper = null;
267 private static final int MAX_BATTERY_STATS_HELPER_FREQUENCY_MS = 1000;
268 private long mBatteryStatsHelperTimestampMs = -MAX_BATTERY_STATS_HELPER_FREQUENCY_MS;
269
Yangster-mace16189a2018-08-26 12:20:16 -0700270 private static IThermalService sThermalService;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700271 private File mBaseDir =
272 new File(SystemServiceManager.ensureSystemDir(), "stats_companion");
Yangster-mac308ea0c2018-10-22 13:10:25 -0700273 @GuardedBy("this")
274 ProcessCpuTracker mProcessCpuTracker = null;
Yangster-mace16189a2018-08-26 12:20:16 -0700275
Bookatz94726412017-08-31 09:26:15 -0700276 public StatsCompanionService(Context context) {
277 super();
278 mContext = context;
279 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800280 mNetworkStatsService = INetworkStatsService.Stub.asInterface(
281 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700282 mBaseDir.mkdirs();
David Chende701692017-10-05 13:16:02 -0700283 mAppUpdateReceiver = new AppUpdateReceiver();
David Chen47e8f4d2017-10-11 15:34:13 -0700284 mUserUpdateReceiver = new BroadcastReceiver() {
285 @Override
286 public void onReceive(Context context, Intent intent) {
287 synchronized (sStatsdLock) {
288 sStatsd = fetchStatsdService();
289 if (sStatsd == null) {
Bookatz111ed732018-02-16 15:54:05 -0800290 Slog.w(TAG, "Could not access statsd for UserUpdateReceiver");
David Chen47e8f4d2017-10-11 15:34:13 -0700291 return;
292 }
293 try {
294 // Pull the latest state of UID->app name, version mapping.
295 // Needed since the new user basically has a version of every app.
296 informAllUidsLocked(context);
297 } catch (RemoteException e) {
David Chen1481fe12017-10-16 13:16:34 -0700298 Slog.e(TAG, "Failed to inform statsd latest update of all apps", e);
yroe26c97b2018-03-27 10:30:11 -0700299 forgetEverythingLocked();
David Chen47e8f4d2017-10-11 15:34:13 -0700300 }
301 }
302 }
303 };
yro947fbce2017-11-15 22:50:23 -0800304 mShutdownEventReceiver = new ShutdownEventReceiver();
Bookatz111ed732018-02-16 15:54:05 -0800305 if (DEBUG) Slog.d(TAG, "Registered receiver for ACTION_PACKAGE_REPLACED and ADDED.");
Chenjie Yu7f8def92017-11-03 09:33:15 -0700306 PowerProfile powerProfile = new PowerProfile(context);
307 final int numClusters = powerProfile.getNumCpuClusters();
308 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
309 int firstCpuOfCluster = 0;
310 for (int i = 0; i < numClusters; i++) {
311 final int numSpeedSteps = powerProfile.getNumSpeedStepsInCpuCluster(i);
312 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
David Chen661f7912018-01-22 17:46:24 -0800313 numSpeedSteps);
Chenjie Yu7f8def92017-11-03 09:33:15 -0700314 firstCpuOfCluster += powerProfile.getNumCoresInCpuCluster(i);
315 }
Yangster-mace16189a2018-08-26 12:20:16 -0700316
317 // Enable push notifications of throttling from vendor thermal
318 // management subsystem via thermalservice.
319 IBinder b = ServiceManager.getService("thermalservice");
320
321 if (b != null) {
322 sThermalService = IThermalService.Stub.asInterface(b);
323 try {
Wei Wangbad7c202018-11-01 11:57:39 -0700324 sThermalService.registerThermalEventListenerWithType(
325 new ThermalEventListener(), Temperature.TYPE_SKIN);
Yangster-mace16189a2018-08-26 12:20:16 -0700326 Slog.i(TAG, "register thermal listener successfully");
327 } catch (RemoteException e) {
328 // Should never happen.
329 Slog.e(TAG, "register thermal listener error");
330 }
331 } else {
332 Slog.e(TAG, "cannot find thermalservice, no throttling push notifications");
333 }
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100334
Chenjie Yuae9dfac2018-10-25 16:06:56 -0700335 // Default NetworkRequest should cover all transport types.
336 final NetworkRequest request = new NetworkRequest.Builder().build();
337 final ConnectivityManager connectivityManager =
338 (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
339 connectivityManager.registerNetworkCallback(request, new ConnectivityStatsCallback());
340
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100341 HandlerThread handlerThread = new HandlerThread(TAG);
342 handlerThread.start();
343 mHandler = new CompanionHandler(handlerThread.getLooper());
344
Misha Wagner4b32c9f2019-01-25 15:30:14 +0000345 mKernelCpuThreadReader =
346 KernelCpuThreadReaderSettingsObserver.getSettingsModifiedReader(mContext);
Bookatz94726412017-08-31 09:26:15 -0700347 }
348
David Chenadaf8b32017-11-03 15:42:08 -0700349 @Override
David Chend37bc232018-04-12 18:05:11 -0700350 public void sendDataBroadcast(IBinder intentSenderBinder, long lastReportTimeNs) {
Bookatz36920822018-01-26 09:18:07 -0800351 enforceCallingPermission();
David Chen661f7912018-01-22 17:46:24 -0800352 IntentSender intentSender = new IntentSender(intentSenderBinder);
353 Intent intent = new Intent();
David Chend37bc232018-04-12 18:05:11 -0700354 intent.putExtra(EXTRA_LAST_REPORT_TIME, lastReportTimeNs);
David Chen661f7912018-01-22 17:46:24 -0800355 try {
356 intentSender.sendIntent(mContext, CODE_DATA_BROADCAST, intent, null, null);
357 } catch (IntentSender.SendIntentException e) {
358 Slog.w(TAG, "Unable to send using IntentSender");
359 }
David Chenadaf8b32017-11-03 15:42:08 -0700360 }
361
Bookatzc6977972018-01-16 16:55:05 -0800362 @Override
Tej Singh6ede28b2019-01-29 17:06:54 -0800363 public void sendActiveConfigsChangedBroadcast(IBinder intentSenderBinder, long[] configIds) {
364 enforceCallingPermission();
365 IntentSender intentSender = new IntentSender(intentSenderBinder);
366 Intent intent = new Intent();
367 intent.putExtra(StatsManager.EXTRA_STATS_ACTIVE_CONFIG_KEYS, configIds);
368 try {
369 intentSender.sendIntent(mContext, CODE_ACTIVE_CONFIGS_BROADCAST, intent, null, null);
370 if (DEBUG) {
371 Slog.d(TAG, "Sent broadcast with config ids " + Arrays.toString(configIds));
372 }
373 } catch (IntentSender.SendIntentException e) {
374 Slog.w(TAG, "Unable to send active configs changed broadcast using IntentSender");
375 }
376 }
377
378 @Override
Bookatzc6977972018-01-16 16:55:05 -0800379 public void sendSubscriberBroadcast(IBinder intentSenderBinder, long configUid, long configKey,
Chenjie Yu12e5e672018-09-14 15:54:59 -0700380 long subscriptionId, long subscriptionRuleId, String[] cookies,
381 StatsDimensionsValue dimensionsValue) {
Bookatzc6977972018-01-16 16:55:05 -0800382 enforceCallingPermission();
383 IntentSender intentSender = new IntentSender(intentSenderBinder);
Chenjie Yu12e5e672018-09-14 15:54:59 -0700384 Intent intent =
385 new Intent()
386 .putExtra(StatsManager.EXTRA_STATS_CONFIG_UID, configUid)
387 .putExtra(StatsManager.EXTRA_STATS_CONFIG_KEY, configKey)
388 .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_ID, subscriptionId)
389 .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_RULE_ID, subscriptionRuleId)
390 .putExtra(StatsManager.EXTRA_STATS_DIMENSIONS_VALUE, dimensionsValue);
Bookatz058d8692018-03-06 09:53:47 -0800391
392 ArrayList<String> cookieList = new ArrayList<>(cookies.length);
Chenjie Yu12e5e672018-09-14 15:54:59 -0700393 for (String cookie : cookies) {
394 cookieList.add(cookie);
395 }
Bookatz058d8692018-03-06 09:53:47 -0800396 intent.putStringArrayListExtra(
397 StatsManager.EXTRA_STATS_BROADCAST_SUBSCRIBER_COOKIES, cookieList);
398
Bookatz1476ef22018-02-13 12:26:01 -0800399 if (DEBUG) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700400 Slog.d(TAG,
401 String.format("Statsd sendSubscriberBroadcast with params {%d %d %d %d %s %s}",
402 configUid, configKey, subscriptionId, subscriptionRuleId,
403 Arrays.toString(cookies),
404 dimensionsValue));
Bookatz1476ef22018-02-13 12:26:01 -0800405 }
Bookatzc6977972018-01-16 16:55:05 -0800406 try {
407 intentSender.sendIntent(mContext, CODE_SUBSCRIBER_BROADCAST, intent, null, null);
408 } catch (IntentSender.SendIntentException e) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700409 Slog.w(TAG,
410 "Unable to send using IntentSender from uid " + configUid
411 + "; presumably it had been cancelled.");
Bookatzc6977972018-01-16 16:55:05 -0800412 }
413 }
414
David Chen1481fe12017-10-16 13:16:34 -0700415 private final static int[] toIntArray(List<Integer> list) {
David Chende701692017-10-05 13:16:02 -0700416 int[] ret = new int[list.size()];
David Chen1481fe12017-10-16 13:16:34 -0700417 for (int i = 0; i < ret.length; i++) {
David Chende701692017-10-05 13:16:02 -0700418 ret[i] = list.get(i);
419 }
420 return ret;
421 }
422
Dianne Hackborn3accca02013-09-20 09:32:11 -0700423 private final static long[] toLongArray(List<Long> list) {
424 long[] ret = new long[list.size()];
425 for (int i = 0; i < ret.length; i++) {
426 ret[i] = list.get(i);
427 }
428 return ret;
429 }
430
David Chende701692017-10-05 13:16:02 -0700431 // Assumes that sStatsdLock is held.
Andreas Gampea36dc622018-02-05 17:19:22 -0800432 @GuardedBy("sStatsdLock")
David Chende701692017-10-05 13:16:02 -0700433 private final void informAllUidsLocked(Context context) throws RemoteException {
434 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
435 PackageManager pm = context.getPackageManager();
436 final List<UserInfo> users = um.getUsers(true);
437 if (DEBUG) {
Bookatz111ed732018-02-16 15:54:05 -0800438 Slog.d(TAG, "Iterating over " + users.size() + " profiles.");
David Chende701692017-10-05 13:16:02 -0700439 }
440
Rajeev Kumar22d92b72018-02-07 18:38:36 -0800441 List<Integer> uids = new ArrayList<>();
442 List<Long> versions = new ArrayList<>();
443 List<String> apps = new ArrayList<>();
dwchen730403e2018-10-29 11:41:56 -0700444 List<String> versionStrings = new ArrayList<>();
445 List<String> installers = new ArrayList<>();
David Chende701692017-10-05 13:16:02 -0700446
447 // Add in all the apps for every user/profile.
448 for (UserInfo profile : users) {
David Chenbd125272018-04-04 19:02:50 -0700449 List<PackageInfo> pi =
Chenjie Yu12e5e672018-09-14 15:54:59 -0700450 pm.getInstalledPackagesAsUser(PackageManager.MATCH_KNOWN_PACKAGES, profile.id);
David Chen1481fe12017-10-16 13:16:34 -0700451 for (int j = 0; j < pi.size(); j++) {
452 if (pi.get(j).applicationInfo != null) {
dwchen730403e2018-10-29 11:41:56 -0700453 String installer;
454 try {
455 installer = pm.getInstallerPackageName(pi.get(j).packageName);
456 } catch (IllegalArgumentException e) {
457 installer = "";
458 }
459 installers.add(installer == null ? "" : installer);
David Chen1481fe12017-10-16 13:16:34 -0700460 uids.add(pi.get(j).applicationInfo.uid);
Dianne Hackborn3accca02013-09-20 09:32:11 -0700461 versions.add(pi.get(j).getLongVersionCode());
dwchen730403e2018-10-29 11:41:56 -0700462 versionStrings.add(pi.get(j).versionName);
David Chen1481fe12017-10-16 13:16:34 -0700463 apps.add(pi.get(j).packageName);
464 }
465 }
David Chende701692017-10-05 13:16:02 -0700466 }
dwchen730403e2018-10-29 11:41:56 -0700467 sStatsd.informAllUidData(toIntArray(uids), toLongArray(versions),
468 versionStrings.toArray(new String[versionStrings.size()]),
469 apps.toArray(new String[apps.size()]),
470 installers.toArray(new String[installers.size()]));
David Chende701692017-10-05 13:16:02 -0700471 if (DEBUG) {
Bookatz111ed732018-02-16 15:54:05 -0800472 Slog.d(TAG, "Sent data for " + uids.size() + " apps");
David Chende701692017-10-05 13:16:02 -0700473 }
474 }
475
Bookatz36920822018-01-26 09:18:07 -0800476 private final static class AppUpdateReceiver extends BroadcastReceiver {
David Chende701692017-10-05 13:16:02 -0700477 @Override
478 public void onReceive(Context context, Intent intent) {
David Chen47e8f4d2017-10-11 15:34:13 -0700479 /**
480 * App updates actually consist of REMOVE, ADD, and then REPLACE broadcasts. To avoid
481 * waste, we ignore the REMOVE and ADD broadcasts that contain the replacing flag.
David Chend6896892017-10-25 11:49:03 -0700482 * If we can't find the value for EXTRA_REPLACING, we default to false.
David Chen47e8f4d2017-10-11 15:34:13 -0700483 */
David Chend6896892017-10-25 11:49:03 -0700484 if (!intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)
485 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
David Chen47e8f4d2017-10-11 15:34:13 -0700486 return; // Keep only replacing or normal add and remove.
487 }
Tej Singh90d3aa02018-03-08 19:07:58 -0800488 if (DEBUG) Slog.d(TAG, "StatsCompanionService noticed an app was updated.");
David Chende701692017-10-05 13:16:02 -0700489 synchronized (sStatsdLock) {
490 if (sStatsd == null) {
yrof6d1ca52017-11-15 15:38:34 -0800491 Slog.w(TAG, "Could not access statsd to inform it of an app update");
David Chende701692017-10-05 13:16:02 -0700492 return;
493 }
494 try {
495 if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
496 Bundle b = intent.getExtras();
497 int uid = b.getInt(Intent.EXTRA_UID);
498 boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
499 if (!replacing) {
500 // Don't bother sending an update if we're right about to get another
501 // intent for the new version that's added.
502 PackageManager pm = context.getPackageManager();
503 String app = intent.getData().getSchemeSpecificPart();
504 sStatsd.informOnePackageRemoved(app, uid);
505 }
506 } else {
507 PackageManager pm = context.getPackageManager();
508 Bundle b = intent.getExtras();
509 int uid = b.getInt(Intent.EXTRA_UID);
510 String app = intent.getData().getSchemeSpecificPart();
511 PackageInfo pi = pm.getPackageInfo(app, PackageManager.MATCH_ANY_USER);
dwchen730403e2018-10-29 11:41:56 -0700512 String installer;
513 try {
514 installer = pm.getInstallerPackageName(app);
515 } catch (IllegalArgumentException e) {
516 installer = "";
517 }
518 sStatsd.informOnePackage(app, uid, pi.getLongVersionCode(), pi.versionName,
519 installer == null ? "" : installer);
David Chende701692017-10-05 13:16:02 -0700520 }
521 } catch (Exception e) {
522 Slog.w(TAG, "Failed to inform statsd of an app update", e);
523 }
524 }
525 }
David Chen1481fe12017-10-16 13:16:34 -0700526 }
David Chende701692017-10-05 13:16:02 -0700527
Bookatz75158ac2018-05-18 15:55:23 -0700528 public final static class AnomalyAlarmListener implements OnAlarmListener {
Bookatz94726412017-08-31 09:26:15 -0700529 @Override
Bookatz75158ac2018-05-18 15:55:23 -0700530 public void onAlarm() {
Bookatz66fe0612018-02-07 18:51:48 -0800531 Slog.i(TAG, "StatsCompanionService believes an anomaly has occurred at time "
532 + System.currentTimeMillis() + "ms.");
Bookatzb487b552017-09-18 11:26:01 -0700533 synchronized (sStatsdLock) {
534 if (sStatsd == null) {
535 Slog.w(TAG, "Could not access statsd to inform it of anomaly alarm firing");
536 return;
537 }
538 try {
539 // Two-way call to statsd to retain AlarmManager wakelock
540 sStatsd.informAnomalyAlarmFired();
541 } catch (RemoteException e) {
542 Slog.w(TAG, "Failed to inform statsd of anomaly alarm firing", e);
543 }
Bookatz94726412017-08-31 09:26:15 -0700544 }
Bookatzb487b552017-09-18 11:26:01 -0700545 // AlarmManager releases its own wakelock here.
Bookatz94726412017-08-31 09:26:15 -0700546 }
David Chen1481fe12017-10-16 13:16:34 -0700547 }
Bookatzb487b552017-09-18 11:26:01 -0700548
Bookatz75158ac2018-05-18 15:55:23 -0700549 public final static class PullingAlarmListener implements OnAlarmListener {
David Chen661f7912018-01-22 17:46:24 -0800550 @Override
Bookatz75158ac2018-05-18 15:55:23 -0700551 public void onAlarm() {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700552 if (DEBUG) {
David Chen661f7912018-01-22 17:46:24 -0800553 Slog.d(TAG, "Time to poll something.");
Chenjie Yu12e5e672018-09-14 15:54:59 -0700554 }
David Chen661f7912018-01-22 17:46:24 -0800555 synchronized (sStatsdLock) {
556 if (sStatsd == null) {
557 Slog.w(TAG, "Could not access statsd to inform it of pulling alarm firing.");
558 return;
559 }
560 try {
561 // Two-way call to statsd to retain AlarmManager wakelock
562 sStatsd.informPollAlarmFired();
563 } catch (RemoteException e) {
564 Slog.w(TAG, "Failed to inform statsd of pulling alarm firing.", e);
565 }
566 }
Bookatzb487b552017-09-18 11:26:01 -0700567 }
David Chen1481fe12017-10-16 13:16:34 -0700568 }
Bookatz94726412017-08-31 09:26:15 -0700569
Bookatz75158ac2018-05-18 15:55:23 -0700570 public final static class PeriodicAlarmListener implements OnAlarmListener {
Yangster-mac932ecec2018-02-01 10:23:52 -0800571 @Override
Bookatz75158ac2018-05-18 15:55:23 -0700572 public void onAlarm() {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700573 if (DEBUG) {
Yangster-macc04feba2018-04-02 14:37:33 -0700574 Slog.d(TAG, "Time to trigger periodic alarm.");
Chenjie Yu12e5e672018-09-14 15:54:59 -0700575 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800576 synchronized (sStatsdLock) {
577 if (sStatsd == null) {
578 Slog.w(TAG, "Could not access statsd to inform it of periodic alarm firing.");
579 return;
580 }
581 try {
582 // Two-way call to statsd to retain AlarmManager wakelock
583 sStatsd.informAlarmForSubscriberTriggeringFired();
584 } catch (RemoteException e) {
585 Slog.w(TAG, "Failed to inform statsd of periodic alarm firing.", e);
586 }
587 }
588 // AlarmManager releases its own wakelock here.
589 }
590 }
591
592 public final static class ShutdownEventReceiver extends BroadcastReceiver {
yro947fbce2017-11-15 22:50:23 -0800593 @Override
594 public void onReceive(Context context, Intent intent) {
595 /**
596 * Skip immediately if intent is not relevant to device shutdown.
597 */
598 if (!intent.getAction().equals(Intent.ACTION_REBOOT)
David Chen661f7912018-01-22 17:46:24 -0800599 && !(intent.getAction().equals(Intent.ACTION_SHUTDOWN)
600 && (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0)) {
601 return;
yro947fbce2017-11-15 22:50:23 -0800602 }
yrof7a3bcb2018-01-24 17:18:55 -0800603
yro947fbce2017-11-15 22:50:23 -0800604 Slog.i(TAG, "StatsCompanionService noticed a shutdown.");
605 synchronized (sStatsdLock) {
606 if (sStatsd == null) {
607 Slog.w(TAG, "Could not access statsd to inform it of a shutdown event.");
608 return;
609 }
610 try {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700611 sStatsd.informDeviceShutdown();
yro947fbce2017-11-15 22:50:23 -0800612 } catch (Exception e) {
613 Slog.w(TAG, "Failed to inform statsd of a shutdown event.", e);
614 }
615 }
616 }
617 }
618
Bookatz94726412017-08-31 09:26:15 -0700619 @Override // Binder call
620 public void setAnomalyAlarm(long timestampMs) {
621 enforceCallingPermission();
622 if (DEBUG) Slog.d(TAG, "Setting anomaly alarm for " + timestampMs);
623 final long callingToken = Binder.clearCallingIdentity();
624 try {
Yangster-mac330af582018-02-08 15:24:38 -0800625 // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
626 // only fire when it awakens.
Bookatz75158ac2018-05-18 15:55:23 -0700627 // AlarmManager will automatically cancel any previous mAnomalyAlarmListener alarm.
628 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, TAG + ".anomaly",
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100629 mAnomalyAlarmListener, mHandler);
Bookatz94726412017-08-31 09:26:15 -0700630 } finally {
631 Binder.restoreCallingIdentity(callingToken);
632 }
633 }
634
635 @Override // Binder call
636 public void cancelAnomalyAlarm() {
637 enforceCallingPermission();
638 if (DEBUG) Slog.d(TAG, "Cancelling anomaly alarm");
639 final long callingToken = Binder.clearCallingIdentity();
640 try {
Bookatz75158ac2018-05-18 15:55:23 -0700641 mAlarmManager.cancel(mAnomalyAlarmListener);
Bookatz94726412017-08-31 09:26:15 -0700642 } finally {
643 Binder.restoreCallingIdentity(callingToken);
644 }
645 }
646
647 @Override // Binder call
Yangster-mac932ecec2018-02-01 10:23:52 -0800648 public void setAlarmForSubscriberTriggering(long timestampMs) {
649 enforceCallingPermission();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700650 if (DEBUG) {
651 Slog.d(TAG,
652 "Setting periodic alarm in about " + (timestampMs
653 - SystemClock.elapsedRealtime()));
654 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800655 final long callingToken = Binder.clearCallingIdentity();
656 try {
657 // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
658 // only fire when it awakens.
Bookatz75158ac2018-05-18 15:55:23 -0700659 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, TAG + ".periodic",
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100660 mPeriodicAlarmListener, mHandler);
Yangster-mac932ecec2018-02-01 10:23:52 -0800661 } finally {
662 Binder.restoreCallingIdentity(callingToken);
663 }
664 }
665
666 @Override // Binder call
667 public void cancelAlarmForSubscriberTriggering() {
668 enforceCallingPermission();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700669 if (DEBUG) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800670 Slog.d(TAG, "Cancelling periodic alarm");
Chenjie Yu12e5e672018-09-14 15:54:59 -0700671 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800672 final long callingToken = Binder.clearCallingIdentity();
673 try {
Bookatz75158ac2018-05-18 15:55:23 -0700674 mAlarmManager.cancel(mPeriodicAlarmListener);
Yangster-mac932ecec2018-02-01 10:23:52 -0800675 } finally {
676 Binder.restoreCallingIdentity(callingToken);
677 }
678 }
679
680 @Override // Binder call
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700681 public void setPullingAlarm(long nextPullTimeMs) {
Bookatz75158ac2018-05-18 15:55:23 -0700682 enforceCallingPermission();
683 if (DEBUG) {
684 Slog.d(TAG, "Setting pulling alarm in about "
685 + (nextPullTimeMs - SystemClock.elapsedRealtime()));
686 }
687 final long callingToken = Binder.clearCallingIdentity();
688 try {
689 // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
690 // only fire when it awakens.
691 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, nextPullTimeMs, TAG + ".pull",
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100692 mPullingAlarmListener, mHandler);
Bookatz75158ac2018-05-18 15:55:23 -0700693 } finally {
694 Binder.restoreCallingIdentity(callingToken);
695 }
Bookatz94726412017-08-31 09:26:15 -0700696 }
697
698 @Override // Binder call
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700699 public void cancelPullingAlarm() {
Bookatz75158ac2018-05-18 15:55:23 -0700700 enforceCallingPermission();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700701 if (DEBUG) {
Bookatz75158ac2018-05-18 15:55:23 -0700702 Slog.d(TAG, "Cancelling pulling alarm");
Chenjie Yu12e5e672018-09-14 15:54:59 -0700703 }
Bookatz75158ac2018-05-18 15:55:23 -0700704 final long callingToken = Binder.clearCallingIdentity();
705 try {
706 mAlarmManager.cancel(mPullingAlarmListener);
707 } finally {
708 Binder.restoreCallingIdentity(callingToken);
709 }
Bookatz94726412017-08-31 09:26:15 -0700710 }
711
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800712 private void addNetworkStats(
David Chen661f7912018-01-22 17:46:24 -0800713 int tag, List<StatsLogEventWrapper> ret, NetworkStats stats, boolean withFGBG) {
714 int size = stats.size();
Yangster-macc552b352018-02-22 10:00:45 -0800715 long elapsedNanos = SystemClock.elapsedRealtimeNanos();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700716 long wallClockNanos = SystemClock.currentTimeMicro() * 1000L;
David Chen661f7912018-01-22 17:46:24 -0800717 NetworkStats.Entry entry = new NetworkStats.Entry(); // For recycling
718 for (int j = 0; j < size; j++) {
719 stats.getValues(j, entry);
Chenjie Yu12e5e672018-09-14 15:54:59 -0700720 StatsLogEventWrapper e = new StatsLogEventWrapper(tag, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -0800721 e.writeInt(entry.uid);
722 if (withFGBG) {
723 e.writeInt(entry.set);
724 }
725 e.writeLong(entry.rxBytes);
726 e.writeLong(entry.rxPackets);
727 e.writeLong(entry.txBytes);
728 e.writeLong(entry.txPackets);
729 ret.add(e);
David Chenc8a43242017-10-17 16:23:28 -0700730 }
David Chenc8a43242017-10-17 16:23:28 -0700731 }
732
733 /**
734 * Allows rollups per UID but keeping the set (foreground/background) slicing.
735 * Adapted from groupedByUid in frameworks/base/core/java/android/net/NetworkStats.java
736 */
737 private NetworkStats rollupNetworkStatsByFGBG(NetworkStats stats) {
738 final NetworkStats ret = new NetworkStats(stats.getElapsedRealtime(), 1);
739
740 final NetworkStats.Entry entry = new NetworkStats.Entry();
741 entry.iface = NetworkStats.IFACE_ALL;
742 entry.tag = NetworkStats.TAG_NONE;
743 entry.metered = NetworkStats.METERED_ALL;
744 entry.roaming = NetworkStats.ROAMING_ALL;
745
746 int size = stats.size();
747 NetworkStats.Entry recycle = new NetworkStats.Entry(); // Used for retrieving values
748 for (int i = 0; i < size; i++) {
749 stats.getValues(i, recycle);
750
751 // Skip specific tags, since already counted in TAG_NONE
752 if (recycle.tag != NetworkStats.TAG_NONE) continue;
753
754 entry.set = recycle.set; // Allows slicing by background/foreground
755 entry.uid = recycle.uid;
756 entry.rxBytes = recycle.rxBytes;
757 entry.rxPackets = recycle.rxPackets;
758 entry.txBytes = recycle.txBytes;
759 entry.txPackets = recycle.txPackets;
760 // Operations purposefully omitted since we don't use them for statsd.
761 ret.combineValues(entry);
762 }
763 return ret;
764 }
765
Chenjie Yu05013b32017-11-21 10:21:41 -0800766 /**
767 * Helper method to extract the Parcelable controller info from a
768 * SynchronousResultReceiver.
769 */
770 private static <T extends Parcelable> T awaitControllerInfo(
771 @Nullable SynchronousResultReceiver receiver) {
772 if (receiver == null) {
773 return null;
774 }
775
776 try {
777 final SynchronousResultReceiver.Result result =
778 receiver.awaitResult(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS);
779 if (result.bundle != null) {
780 // This is the final destination for the Bundle.
781 result.bundle.setDefusable(true);
782
783 final T data = result.bundle.getParcelable(
784 RESULT_RECEIVER_CONTROLLER_KEY);
785 if (data != null) {
786 return data;
787 }
788 }
789 Slog.e(TAG, "no controller energy info supplied for " + receiver.getName());
790 } catch (TimeoutException e) {
791 Slog.w(TAG, "timeout reading " + receiver.getName() + " stats");
792 }
793 return null;
794 }
795
Chenjie Yu12e5e672018-09-14 15:54:59 -0700796 private void pullKernelWakelock(
797 int tagId, long elapsedNanos, long wallClockNanos,
798 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800799 final KernelWakelockStats wakelockStats =
800 mKernelWakelockReader.readKernelWakelockStats(mTmpWakelockStats);
801 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
802 String name = ent.getKey();
803 KernelWakelockStats.Entry kws = ent.getValue();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700804 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -0800805 e.writeString(name);
806 e.writeInt(kws.mCount);
807 e.writeInt(kws.mVersion);
808 e.writeLong(kws.mTotalTime);
809 pulledData.add(e);
810 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800811 }
812
Chenjie Yu12e5e672018-09-14 15:54:59 -0700813 private void pullWifiBytesTransfer(
814 int tagId, long elapsedNanos, long wallClockNanos,
815 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800816 long token = Binder.clearCallingIdentity();
817 try {
818 // TODO: Consider caching the following call to get BatteryStatsInternal.
819 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
820 String[] ifaces = bs.getWifiIfaces();
821 if (ifaces.length == 0) {
822 return;
823 }
Chenbo Fenge62e2872019-01-11 15:50:17 -0800824 if (mNetworkStatsService == null) {
825 Slog.e(TAG, "NetworkStats Service is not available!");
826 return;
827 }
David Chen661f7912018-01-22 17:46:24 -0800828 // Combine all the metrics per Uid into one record.
Chenbo Fenge62e2872019-01-11 15:50:17 -0800829 NetworkStats stats = mNetworkStatsService.getDetailedUidStats(ifaces).groupedByUid();
David Chen661f7912018-01-22 17:46:24 -0800830 addNetworkStats(tagId, pulledData, stats, false);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800831 } catch (RemoteException e) {
David Chen661f7912018-01-22 17:46:24 -0800832 Slog.e(TAG, "Pulling netstats for wifi bytes has error", e);
833 } finally {
834 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800835 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800836 }
837
Chenjie Yu12e5e672018-09-14 15:54:59 -0700838 private void pullWifiBytesTransferByFgBg(
839 int tagId, long elapsedNanos, long wallClockNanos,
840 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800841 long token = Binder.clearCallingIdentity();
842 try {
843 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
844 String[] ifaces = bs.getWifiIfaces();
845 if (ifaces.length == 0) {
846 return;
847 }
Chenbo Fenge62e2872019-01-11 15:50:17 -0800848 if (mNetworkStatsService == null) {
849 Slog.e(TAG, "NetworkStats Service is not available!");
850 return;
851 }
David Chen661f7912018-01-22 17:46:24 -0800852 NetworkStats stats = rollupNetworkStatsByFGBG(
Chenbo Fenge62e2872019-01-11 15:50:17 -0800853 mNetworkStatsService.getDetailedUidStats(ifaces));
David Chen661f7912018-01-22 17:46:24 -0800854 addNetworkStats(tagId, pulledData, stats, true);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800855 } catch (RemoteException e) {
David Chen661f7912018-01-22 17:46:24 -0800856 Slog.e(TAG, "Pulling netstats for wifi bytes w/ fg/bg has error", e);
857 } finally {
858 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800859 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800860 }
861
Chenjie Yu12e5e672018-09-14 15:54:59 -0700862 private void pullMobileBytesTransfer(
863 int tagId, long elapsedNanos, long wallClockNanos,
864 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800865 long token = Binder.clearCallingIdentity();
866 try {
867 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
868 String[] ifaces = bs.getMobileIfaces();
869 if (ifaces.length == 0) {
870 return;
871 }
Chenbo Fenge62e2872019-01-11 15:50:17 -0800872 if (mNetworkStatsService == null) {
873 Slog.e(TAG, "NetworkStats Service is not available!");
874 return;
875 }
David Chen661f7912018-01-22 17:46:24 -0800876 // Combine all the metrics per Uid into one record.
Chenbo Fenge62e2872019-01-11 15:50:17 -0800877 NetworkStats stats = mNetworkStatsService.getDetailedUidStats(ifaces).groupedByUid();
David Chen661f7912018-01-22 17:46:24 -0800878 addNetworkStats(tagId, pulledData, stats, false);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800879 } catch (RemoteException e) {
David Chen661f7912018-01-22 17:46:24 -0800880 Slog.e(TAG, "Pulling netstats for mobile bytes has error", e);
881 } finally {
882 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800883 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800884 }
885
Chenjie Yu12e5e672018-09-14 15:54:59 -0700886 private void pullBluetoothBytesTransfer(
887 int tagId, long elapsedNanos, long wallClockNanos,
888 List<StatsLogEventWrapper> pulledData) {
Yangster-mac95543242018-10-22 11:44:03 -0700889 BluetoothActivityEnergyInfo info = fetchBluetoothData();
Chenjie Yu9e59f932018-03-30 16:41:38 -0700890 if (info.getUidTraffic() != null) {
891 for (UidTraffic traffic : info.getUidTraffic()) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700892 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
893 wallClockNanos);
Chenjie Yu9e59f932018-03-30 16:41:38 -0700894 e.writeInt(traffic.getUid());
895 e.writeLong(traffic.getRxBytes());
896 e.writeLong(traffic.getTxBytes());
897 pulledData.add(e);
898 }
David Chen661f7912018-01-22 17:46:24 -0800899 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800900 }
901
Chenjie Yu12e5e672018-09-14 15:54:59 -0700902 private void pullMobileBytesTransferByFgBg(
903 int tagId, long elapsedNanos, long wallClockNanos,
904 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800905 long token = Binder.clearCallingIdentity();
906 try {
907 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
908 String[] ifaces = bs.getMobileIfaces();
909 if (ifaces.length == 0) {
910 return;
911 }
Chenbo Fenge62e2872019-01-11 15:50:17 -0800912 if (mNetworkStatsService == null) {
913 Slog.e(TAG, "NetworkStats Service is not available!");
914 return;
915 }
David Chen661f7912018-01-22 17:46:24 -0800916 NetworkStats stats = rollupNetworkStatsByFGBG(
Chenbo Fenge62e2872019-01-11 15:50:17 -0800917 mNetworkStatsService.getDetailedUidStats(ifaces));
David Chen661f7912018-01-22 17:46:24 -0800918 addNetworkStats(tagId, pulledData, stats, true);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800919 } catch (RemoteException e) {
David Chen661f7912018-01-22 17:46:24 -0800920 Slog.e(TAG, "Pulling netstats for mobile bytes w/ fg/bg has error", e);
921 } finally {
922 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800923 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800924 }
925
Chenjie Yu12e5e672018-09-14 15:54:59 -0700926 private void pullCpuTimePerFreq(
927 int tagId, long elapsedNanos, long wallClockNanos,
928 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800929 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
930 long[] clusterTimeMs = mKernelCpuSpeedReaders[cluster].readAbsolute();
931 if (clusterTimeMs != null) {
932 for (int speed = clusterTimeMs.length - 1; speed >= 0; --speed) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700933 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
934 wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -0800935 e.writeInt(cluster);
936 e.writeInt(speed);
937 e.writeLong(clusterTimeMs[speed]);
938 pulledData.add(e);
939 }
940 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800941 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800942 }
943
Chenjie Yu12e5e672018-09-14 15:54:59 -0700944 private void pullKernelUidCpuTime(
945 int tagId, long elapsedNanos, long wallClockNanos,
946 List<StatsLogEventWrapper> pulledData) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800947 mCpuUidUserSysTimeReader.readAbsolute((uid, timesUs) -> {
948 long userTimeUs = timesUs[0], systemTimeUs = timesUs[1];
Chenjie Yu12e5e672018-09-14 15:54:59 -0700949 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Chenjie Yuec676612018-03-07 09:19:17 -0800950 e.writeInt(uid);
951 e.writeLong(userTimeUs);
952 e.writeLong(systemTimeUs);
953 pulledData.add(e);
954 });
955 }
956
Chenjie Yu12e5e672018-09-14 15:54:59 -0700957 private void pullKernelUidCpuFreqTime(
958 int tagId, long elapsedNanos, long wallClockNanos,
959 List<StatsLogEventWrapper> pulledData) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800960 mCpuUidFreqTimeReader.readAbsolute((uid, cpuFreqTimeMs) -> {
Chenjie Yuec676612018-03-07 09:19:17 -0800961 for (int freqIndex = 0; freqIndex < cpuFreqTimeMs.length; ++freqIndex) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700962 if (cpuFreqTimeMs[freqIndex] != 0) {
963 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
964 wallClockNanos);
Chenjie Yu4460e3c2018-03-14 17:12:59 -0700965 e.writeInt(uid);
966 e.writeInt(freqIndex);
967 e.writeLong(cpuFreqTimeMs[freqIndex]);
968 pulledData.add(e);
969 }
Chenjie Yuec676612018-03-07 09:19:17 -0800970 }
971 });
972 }
973
Chenjie Yu12e5e672018-09-14 15:54:59 -0700974 private void pullKernelUidCpuClusterTime(
975 int tagId, long elapsedNanos, long wallClockNanos,
976 List<StatsLogEventWrapper> pulledData) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800977 mCpuUidClusterTimeReader.readAbsolute((uid, cpuClusterTimesMs) -> {
Chenjie Yuec676612018-03-07 09:19:17 -0800978 for (int i = 0; i < cpuClusterTimesMs.length; i++) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700979 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
980 wallClockNanos);
Chenjie Yuec676612018-03-07 09:19:17 -0800981 e.writeInt(uid);
982 e.writeInt(i);
983 e.writeLong(cpuClusterTimesMs[i]);
984 pulledData.add(e);
985 }
986 });
987 }
988
Chenjie Yu12e5e672018-09-14 15:54:59 -0700989 private void pullKernelUidCpuActiveTime(
990 int tagId, long elapsedNanos, long wallClockNanos,
991 List<StatsLogEventWrapper> pulledData) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800992 mCpuUidActiveTimeReader.readAbsolute((uid, cpuActiveTimesMs) -> {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700993 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Chenjie Yuec676612018-03-07 09:19:17 -0800994 e.writeInt(uid);
Chenjie Yu12e5e672018-09-14 15:54:59 -0700995 e.writeLong((long) cpuActiveTimesMs);
Chenjie Yuec676612018-03-07 09:19:17 -0800996 pulledData.add(e);
997 });
998 }
999
Chenjie Yu12e5e672018-09-14 15:54:59 -07001000 private void pullWifiActivityInfo(
1001 int tagId, long elapsedNanos, long wallClockNanos,
1002 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -08001003 long token = Binder.clearCallingIdentity();
Yangster-mac95543242018-10-22 11:44:03 -07001004 synchronized (this) {
1005 if (mWifiManager == null) {
1006 mWifiManager =
1007 IWifiManager.Stub.asInterface(
1008 ServiceManager.getService(Context.WIFI_SERVICE));
1009 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001010 }
David Chen661f7912018-01-22 17:46:24 -08001011 if (mWifiManager != null) {
1012 try {
1013 SynchronousResultReceiver wifiReceiver = new SynchronousResultReceiver("wifi");
1014 mWifiManager.requestActivityInfo(wifiReceiver);
1015 final WifiActivityEnergyInfo wifiInfo = awaitControllerInfo(wifiReceiver);
Chenjie Yu12e5e672018-09-14 15:54:59 -07001016 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1017 wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001018 e.writeLong(wifiInfo.getTimeStamp());
1019 e.writeInt(wifiInfo.getStackState());
1020 e.writeLong(wifiInfo.getControllerTxTimeMillis());
1021 e.writeLong(wifiInfo.getControllerRxTimeMillis());
1022 e.writeLong(wifiInfo.getControllerIdleTimeMillis());
1023 e.writeLong(wifiInfo.getControllerEnergyUsed());
1024 pulledData.add(e);
1025 } catch (RemoteException e) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001026 Slog.e(TAG,
1027 "Pulling wifiManager for wifi controller activity energy info has error",
1028 e);
David Chen661f7912018-01-22 17:46:24 -08001029 } finally {
1030 Binder.restoreCallingIdentity(token);
1031 }
1032 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001033 }
1034
Chenjie Yu12e5e672018-09-14 15:54:59 -07001035 private void pullModemActivityInfo(
1036 int tagId, long elapsedNanos, long wallClockNanos,
1037 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -08001038 long token = Binder.clearCallingIdentity();
Yangster-mac95543242018-10-22 11:44:03 -07001039 synchronized (this) {
1040 if (mTelephony == null) {
1041 mTelephony = TelephonyManager.from(mContext);
1042 }
David Chen661f7912018-01-22 17:46:24 -08001043 }
1044 if (mTelephony != null) {
1045 SynchronousResultReceiver modemReceiver = new SynchronousResultReceiver("telephony");
1046 mTelephony.requestModemActivityInfo(modemReceiver);
1047 final ModemActivityInfo modemInfo = awaitControllerInfo(modemReceiver);
Chenjie Yu12e5e672018-09-14 15:54:59 -07001048 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001049 e.writeLong(modemInfo.getTimestamp());
1050 e.writeLong(modemInfo.getSleepTimeMillis());
1051 e.writeLong(modemInfo.getIdleTimeMillis());
1052 e.writeLong(modemInfo.getTxTimeMillis()[0]);
1053 e.writeLong(modemInfo.getTxTimeMillis()[1]);
1054 e.writeLong(modemInfo.getTxTimeMillis()[2]);
1055 e.writeLong(modemInfo.getTxTimeMillis()[3]);
1056 e.writeLong(modemInfo.getTxTimeMillis()[4]);
1057 e.writeLong(modemInfo.getRxTimeMillis());
1058 e.writeLong(modemInfo.getEnergyUsed());
1059 pulledData.add(e);
1060 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001061 }
1062
Chenjie Yu12e5e672018-09-14 15:54:59 -07001063 private void pullBluetoothActivityInfo(
1064 int tagId, long elapsedNanos, long wallClockNanos,
1065 List<StatsLogEventWrapper> pulledData) {
Yangster-mac95543242018-10-22 11:44:03 -07001066 BluetoothActivityEnergyInfo info = fetchBluetoothData();
Chenjie Yu12e5e672018-09-14 15:54:59 -07001067 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001068 e.writeLong(info.getTimeStamp());
1069 e.writeInt(info.getBluetoothStackState());
1070 e.writeLong(info.getControllerTxTimeMillis());
1071 e.writeLong(info.getControllerRxTimeMillis());
1072 e.writeLong(info.getControllerIdleTimeMillis());
1073 e.writeLong(info.getControllerEnergyUsed());
1074 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001075 }
1076
Yangster-mac95543242018-10-22 11:44:03 -07001077 private synchronized BluetoothActivityEnergyInfo fetchBluetoothData() {
Chenjie Yuc2d65442018-02-01 22:27:17 -08001078 final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
David Chen661f7912018-01-22 17:46:24 -08001079 if (adapter != null) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001080 SynchronousResultReceiver bluetoothReceiver = new SynchronousResultReceiver(
1081 "bluetooth");
David Chen661f7912018-01-22 17:46:24 -08001082 adapter.requestControllerActivityEnergyInfo(bluetoothReceiver);
1083 return awaitControllerInfo(bluetoothReceiver);
1084 } else {
1085 Slog.e(TAG, "Failed to get bluetooth adapter!");
1086 return null;
1087 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001088 }
1089
Chenjie Yu12e5e672018-09-14 15:54:59 -07001090 private void pullSystemElapsedRealtime(
1091 int tagId, long elapsedNanos, long wallClockNanos,
1092 List<StatsLogEventWrapper> pulledData) {
1093 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001094 e.writeLong(SystemClock.elapsedRealtime());
1095 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001096 }
1097
Chenjie Yu12e5e672018-09-14 15:54:59 -07001098 private void pullSystemUpTime(int tagId, long elapsedNanos, long wallClockNanos,
1099 List<StatsLogEventWrapper> pulledData) {
1100 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001101 e.writeLong(SystemClock.uptimeMillis());
1102 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001103 }
1104
Chenjie Yu12e5e672018-09-14 15:54:59 -07001105 private void pullProcessMemoryState(
1106 int tagId, long elapsedNanos, long wallClockNanos,
1107 List<StatsLogEventWrapper> pulledData) {
Rajeev Kumar22d92b72018-02-07 18:38:36 -08001108 List<ProcessMemoryState> processMemoryStates =
Chenjie Yu12e5e672018-09-14 15:54:59 -07001109 LocalServices.getService(
1110 ActivityManagerInternal.class).getMemoryStateForProcesses();
Rajeev Kumar22d92b72018-02-07 18:38:36 -08001111 for (ProcessMemoryState processMemoryState : processMemoryStates) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001112 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Rajeev Kumar22d92b72018-02-07 18:38:36 -08001113 e.writeInt(processMemoryState.uid);
1114 e.writeString(processMemoryState.processName);
1115 e.writeInt(processMemoryState.oomScore);
1116 e.writeLong(processMemoryState.pgfault);
1117 e.writeLong(processMemoryState.pgmajfault);
1118 e.writeLong(processMemoryState.rssInBytes);
1119 e.writeLong(processMemoryState.cacheInBytes);
1120 e.writeLong(processMemoryState.swapInBytes);
Rafal Slawikd03ae422018-11-20 11:27:45 +00001121 e.writeLong(0); // unused
Rafal Slawik272a8162018-11-01 15:12:28 +00001122 e.writeLong(processMemoryState.startTimeNanos);
Rajeev Kumar22d92b72018-02-07 18:38:36 -08001123 pulledData.add(e);
1124 }
1125 }
1126
Rafal Slawik08621582018-10-15 14:53:07 +01001127 private void pullNativeProcessMemoryState(
1128 int tagId, long elapsedNanos, long wallClockNanos,
1129 List<StatsLogEventWrapper> pulledData) {
Rafal Slawik932c71e2018-11-30 16:10:32 +00001130 final List<String> processNames = Arrays.asList(MEMORY_INTERESTING_NATIVE_PROCESSES);
Rafal Slawik3bea8952018-11-15 12:39:33 +00001131 int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
Rafal Slawikc3762622018-11-07 12:07:26 +00001132 for (int i = 0; i < pids.length; i++) {
1133 int pid = pids[i];
1134 MemoryStat memoryStat = readMemoryStatFromProcfs(pid);
1135 if (memoryStat == null) {
1136 continue;
1137 }
1138 int uid = getUidForPid(pid);
1139 String processName = readCmdlineFromProcfs(pid);
Rafal Slawik932c71e2018-11-30 16:10:32 +00001140 // Sometimes we get here processName that is not included in the whitelist. It comes
1141 // from forking the zygote for an app. We can ignore that sample because this process
1142 // is collected by ProcessMemoryState.
1143 if (!processNames.contains(processName)) {
1144 continue;
1145 }
Rafal Slawik08621582018-10-15 14:53:07 +01001146 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Rafal Slawikc3762622018-11-07 12:07:26 +00001147 e.writeInt(uid);
1148 e.writeString(processName);
1149 e.writeLong(memoryStat.pgfault);
1150 e.writeLong(memoryStat.pgmajfault);
1151 e.writeLong(memoryStat.rssInBytes);
Rafal Slawikd03ae422018-11-20 11:27:45 +00001152 e.writeLong(0); // unused
Rafal Slawikc3762622018-11-07 12:07:26 +00001153 e.writeLong(memoryStat.startTimeNanos);
Rafal Slawik08621582018-10-15 14:53:07 +01001154 pulledData.add(e);
1155 }
1156 }
1157
Rafal Slawik3bea8952018-11-15 12:39:33 +00001158 private void pullProcessMemoryHighWaterMark(
1159 int tagId, long elapsedNanos, long wallClockNanos,
1160 List<StatsLogEventWrapper> pulledData) {
1161 List<ProcessMemoryHighWaterMark> results = LocalServices.getService(
1162 ActivityManagerInternal.class).getMemoryHighWaterMarkForProcesses();
1163 for (ProcessMemoryHighWaterMark processMemoryHighWaterMark : results) {
1164 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1165 e.writeInt(processMemoryHighWaterMark.uid);
1166 e.writeString(processMemoryHighWaterMark.processName);
1167 e.writeLong(processMemoryHighWaterMark.rssHighWaterMarkInBytes);
1168 pulledData.add(e);
1169 }
1170 int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
1171 for (int i = 0; i < pids.length; i++) {
1172 final int pid = pids[i];
1173 final int uid = getUidForPid(pid);
1174 final String processName = readCmdlineFromProcfs(pid);
1175 final long rssHighWaterMarkInBytes = readRssHighWaterMarkFromProcfs(pid);
1176 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1177 e.writeInt(uid);
1178 e.writeString(processName);
1179 e.writeLong(rssHighWaterMarkInBytes);
1180 pulledData.add(e);
1181 }
Rafal Slawik44b88142018-12-15 16:48:09 +00001182 // Invoke rss_hwm_reset binary to reset RSS HWM counters for all processes.
1183 SystemProperties.set("sys.rss_hwm_reset.on", "1");
Rafal Slawik3bea8952018-11-15 12:39:33 +00001184 }
1185
Rafal Slawikd4e87572019-03-12 13:08:38 +00001186 private void pullSystemIonHeapSize(
1187 int tagId, long elapsedNanos, long wallClockNanos,
1188 List<StatsLogEventWrapper> pulledData) {
1189 final long systemIonHeapSizeInBytes = readSystemIonHeapSizeFromDebugfs();
1190 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1191 e.writeLong(systemIonHeapSizeInBytes);
1192 pulledData.add(e);
1193 }
1194
Chenjie Yu12e5e672018-09-14 15:54:59 -07001195 private void pullBinderCallsStats(
1196 int tagId, long elapsedNanos, long wallClockNanos,
1197 List<StatsLogEventWrapper> pulledData) {
Olivier Gaillard289ba402018-07-24 18:50:13 +01001198 BinderCallsStatsService.Internal binderStats =
1199 LocalServices.getService(BinderCallsStatsService.Internal.class);
Olivier Gaillard44a60a92018-07-25 22:53:55 +01001200 if (binderStats == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001201 throw new IllegalStateException("binderStats is null");
Olivier Gaillard44a60a92018-07-25 22:53:55 +01001202 }
1203
Olivier Gaillard289ba402018-07-24 18:50:13 +01001204 List<ExportedCallStat> callStats = binderStats.getExportedCallStats();
Olivier Gaillardd25f7a82018-09-12 14:28:48 +01001205 binderStats.reset();
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01001206 for (ExportedCallStat callStat : callStats) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001207 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Olivier Gaillard88de48f2018-10-18 10:21:21 +01001208 e.writeInt(callStat.workSourceUid);
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01001209 e.writeString(callStat.className);
1210 e.writeString(callStat.methodName);
1211 e.writeLong(callStat.callCount);
1212 e.writeLong(callStat.exceptionCount);
1213 e.writeLong(callStat.latencyMicros);
1214 e.writeLong(callStat.maxLatencyMicros);
1215 e.writeLong(callStat.cpuTimeMicros);
1216 e.writeLong(callStat.maxCpuTimeMicros);
1217 e.writeLong(callStat.maxReplySizeBytes);
1218 e.writeLong(callStat.maxRequestSizeBytes);
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001219 e.writeLong(callStat.recordedCallCount);
1220 e.writeInt(callStat.screenInteractive ? 1 : 0);
Olivier Gaillard720ec5b2018-10-30 17:32:56 +00001221 e.writeInt(callStat.callingUid);
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001222 pulledData.add(e);
1223 }
1224 }
1225
Chenjie Yu12e5e672018-09-14 15:54:59 -07001226 private void pullBinderCallsStatsExceptions(
1227 int tagId, long elapsedNanos, long wallClockNanos,
1228 List<StatsLogEventWrapper> pulledData) {
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001229 BinderCallsStatsService.Internal binderStats =
1230 LocalServices.getService(BinderCallsStatsService.Internal.class);
Olivier Gaillard44a60a92018-07-25 22:53:55 +01001231 if (binderStats == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001232 throw new IllegalStateException("binderStats is null");
Olivier Gaillard44a60a92018-07-25 22:53:55 +01001233 }
1234
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001235 ArrayMap<String, Integer> exceptionStats = binderStats.getExportedExceptionStats();
Olivier Gaillardd25f7a82018-09-12 14:28:48 +01001236 // TODO: decouple binder calls exceptions with the rest of the binder calls data so that we
1237 // can reset the exception stats.
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001238 for (Entry<String, Integer> entry : exceptionStats.entrySet()) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001239 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001240 e.writeString(entry.getKey());
1241 e.writeInt(entry.getValue());
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01001242 pulledData.add(e);
1243 }
1244 }
1245
Chenjie Yu12e5e672018-09-14 15:54:59 -07001246 private void pullLooperStats(int tagId, long elapsedNanos, long wallClockNanos,
1247 List<StatsLogEventWrapper> pulledData) {
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001248 LooperStats looperStats = LocalServices.getService(LooperStats.class);
1249 if (looperStats == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001250 throw new IllegalStateException("looperStats null");
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001251 }
1252
1253 List<LooperStats.ExportedEntry> entries = looperStats.getEntries();
Marcin Oczeretko3e6494e2018-09-10 18:06:52 +01001254 looperStats.reset();
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001255 for (LooperStats.ExportedEntry entry : entries) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001256 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Marcin Oczeretkoec758722018-09-12 12:53:47 +01001257 e.writeInt(entry.workSourceUid);
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001258 e.writeString(entry.handlerClassName);
1259 e.writeString(entry.threadName);
1260 e.writeString(entry.messageName);
1261 e.writeLong(entry.messageCount);
1262 e.writeLong(entry.exceptionCount);
1263 e.writeLong(entry.recordedMessageCount);
1264 e.writeLong(entry.totalLatencyMicros);
1265 e.writeLong(entry.cpuUsageMicros);
Marcin Oczeretko3e6494e2018-09-10 18:06:52 +01001266 e.writeBoolean(entry.isInteractive);
Marcin Oczeretkoc06331a2018-10-02 13:00:38 +01001267 e.writeLong(entry.maxCpuUsageMicros);
1268 e.writeLong(entry.maxLatencyMicros);
1269 e.writeLong(entry.recordedDelayMessageCount);
1270 e.writeLong(entry.delayMillis);
1271 e.writeLong(entry.maxDelayMillis);
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001272 pulledData.add(e);
1273 }
1274 }
1275
Chenjie Yu12e5e672018-09-14 15:54:59 -07001276 private void pullDiskStats(int tagId, long elapsedNanos, long wallClockNanos,
1277 List<StatsLogEventWrapper> pulledData) {
Tej Singh86dc9db2018-09-06 00:39:57 +00001278 // Run a quick-and-dirty performance test: write 512 bytes
1279 byte[] junk = new byte[512];
1280 for (int i = 0; i < junk.length; i++) junk[i] = (byte) i; // Write nonzero bytes
1281
1282 File tmp = new File(Environment.getDataDirectory(), "system/statsdperftest.tmp");
1283 FileOutputStream fos = null;
1284 IOException error = null;
1285
1286 long before = SystemClock.elapsedRealtime();
1287 try {
1288 fos = new FileOutputStream(tmp);
1289 fos.write(junk);
1290 } catch (IOException e) {
1291 error = e;
1292 } finally {
1293 try {
1294 if (fos != null) fos.close();
1295 } catch (IOException e) {
1296 // Do nothing.
1297 }
1298 }
1299
1300 long latency = SystemClock.elapsedRealtime() - before;
1301 if (tmp.exists()) tmp.delete();
1302
1303 if (error != null) {
1304 Slog.e(TAG, "Error performing diskstats latency test");
1305 latency = -1;
1306 }
1307 // File based encryption.
1308 boolean fileBased = StorageManager.isFileEncryptedNativeOnly();
1309
1310 //Recent disk write speed. Binder call to storaged.
1311 int writeSpeed = -1;
1312 try {
1313 IBinder binder = ServiceManager.getService("storaged");
1314 if (binder == null) {
1315 Slog.e(TAG, "storaged not found");
1316 }
1317 IStoraged storaged = IStoraged.Stub.asInterface(binder);
1318 writeSpeed = storaged.getRecentPerf();
1319 } catch (RemoteException e) {
1320 Slog.e(TAG, "storaged not found");
1321 }
1322
1323 // Add info pulledData.
Chenjie Yu12e5e672018-09-14 15:54:59 -07001324 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001325 e.writeLong(latency);
1326 e.writeBoolean(fileBased);
1327 e.writeInt(writeSpeed);
1328 pulledData.add(e);
1329 }
1330
Chenjie Yu12e5e672018-09-14 15:54:59 -07001331 private void pullDirectoryUsage(int tagId, long elapsedNanos, long wallClockNanos,
1332 List<StatsLogEventWrapper> pulledData) {
Tej Singh86dc9db2018-09-06 00:39:57 +00001333 StatFs statFsData = new StatFs(Environment.getDataDirectory().getAbsolutePath());
1334 StatFs statFsSystem = new StatFs(Environment.getRootDirectory().getAbsolutePath());
1335 StatFs statFsCache = new StatFs(Environment.getDownloadCacheDirectory().getAbsolutePath());
1336
Chenjie Yu12e5e672018-09-14 15:54:59 -07001337 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001338 e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__DATA);
1339 e.writeLong(statFsData.getAvailableBytes());
1340 e.writeLong(statFsData.getTotalBytes());
1341 pulledData.add(e);
1342
Chenjie Yu12e5e672018-09-14 15:54:59 -07001343 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001344 e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__CACHE);
1345 e.writeLong(statFsCache.getAvailableBytes());
1346 e.writeLong(statFsCache.getTotalBytes());
1347 pulledData.add(e);
1348
Chenjie Yu12e5e672018-09-14 15:54:59 -07001349 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001350 e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__SYSTEM);
1351 e.writeLong(statFsSystem.getAvailableBytes());
1352 e.writeLong(statFsSystem.getTotalBytes());
1353 pulledData.add(e);
1354 }
1355
Chenjie Yu12e5e672018-09-14 15:54:59 -07001356 private void pullAppSize(int tagId, long elapsedNanos, long wallClockNanos,
1357 List<StatsLogEventWrapper> pulledData) {
Tej Singh86dc9db2018-09-06 00:39:57 +00001358 try {
1359 String jsonStr = IoUtils.readFileAsString(DiskStatsLoggingService.DUMPSYS_CACHE_PATH);
1360 JSONObject json = new JSONObject(jsonStr);
1361 long cache_time = json.optLong(DiskStatsFileLogger.LAST_QUERY_TIMESTAMP_KEY, -1L);
1362 JSONArray pkg_names = json.getJSONArray(DiskStatsFileLogger.PACKAGE_NAMES_KEY);
1363 JSONArray app_sizes = json.getJSONArray(DiskStatsFileLogger.APP_SIZES_KEY);
1364 JSONArray app_data_sizes = json.getJSONArray(DiskStatsFileLogger.APP_DATA_KEY);
1365 JSONArray app_cache_sizes = json.getJSONArray(DiskStatsFileLogger.APP_CACHES_KEY);
1366 // Sanity check: Ensure all 4 lists have the same length.
1367 int length = pkg_names.length();
1368 if (app_sizes.length() != length || app_data_sizes.length() != length
1369 || app_cache_sizes.length() != length) {
1370 Slog.e(TAG, "formatting error in diskstats cache file!");
1371 return;
1372 }
1373 for (int i = 0; i < length; i++) {
1374 StatsLogEventWrapper e =
Chenjie Yu12e5e672018-09-14 15:54:59 -07001375 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001376 e.writeString(pkg_names.getString(i));
1377 e.writeLong(app_sizes.optLong(i, -1L));
1378 e.writeLong(app_data_sizes.optLong(i, -1L));
1379 e.writeLong(app_cache_sizes.optLong(i, -1L));
1380 e.writeLong(cache_time);
1381 pulledData.add(e);
1382 }
1383 } catch (IOException | JSONException e) {
1384 Slog.e(TAG, "exception reading diskstats cache file", e);
1385 }
1386 }
1387
Chenjie Yu12e5e672018-09-14 15:54:59 -07001388 private void pullCategorySize(int tagId, long elapsedNanos, long wallClockNanos,
1389 List<StatsLogEventWrapper> pulledData) {
Tej Singh86dc9db2018-09-06 00:39:57 +00001390 try {
1391 String jsonStr = IoUtils.readFileAsString(DiskStatsLoggingService.DUMPSYS_CACHE_PATH);
1392 JSONObject json = new JSONObject(jsonStr);
1393 long cacheTime = json.optLong(DiskStatsFileLogger.LAST_QUERY_TIMESTAMP_KEY, -1L);
1394
Chenjie Yu12e5e672018-09-14 15:54:59 -07001395 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001396 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_SIZE);
1397 e.writeLong(json.optLong(DiskStatsFileLogger.APP_SIZE_AGG_KEY, -1L));
1398 e.writeLong(cacheTime);
1399 pulledData.add(e);
1400
Chenjie Yu12e5e672018-09-14 15:54:59 -07001401 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001402 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_DATA_SIZE);
1403 e.writeLong(json.optLong(DiskStatsFileLogger.APP_DATA_SIZE_AGG_KEY, -1L));
1404 e.writeLong(cacheTime);
1405 pulledData.add(e);
1406
Chenjie Yu12e5e672018-09-14 15:54:59 -07001407 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001408 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_CACHE_SIZE);
1409 e.writeLong(json.optLong(DiskStatsFileLogger.APP_CACHE_AGG_KEY, -1L));
1410 e.writeLong(cacheTime);
1411 pulledData.add(e);
1412
Chenjie Yu12e5e672018-09-14 15:54:59 -07001413 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001414 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__PHOTOS);
1415 e.writeLong(json.optLong(DiskStatsFileLogger.PHOTOS_KEY, -1L));
1416 e.writeLong(cacheTime);
1417 pulledData.add(e);
1418
Chenjie Yu12e5e672018-09-14 15:54:59 -07001419 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001420 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__VIDEOS);
1421 e.writeLong(json.optLong(DiskStatsFileLogger.VIDEOS_KEY, -1L));
1422 e.writeLong(cacheTime);
1423 pulledData.add(e);
1424
Chenjie Yu12e5e672018-09-14 15:54:59 -07001425 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001426 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__AUDIO);
1427 e.writeLong(json.optLong(DiskStatsFileLogger.AUDIO_KEY, -1L));
1428 e.writeLong(cacheTime);
1429 pulledData.add(e);
1430
Chenjie Yu12e5e672018-09-14 15:54:59 -07001431 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001432 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__DOWNLOADS);
1433 e.writeLong(json.optLong(DiskStatsFileLogger.DOWNLOADS_KEY, -1L));
1434 e.writeLong(cacheTime);
1435 pulledData.add(e);
1436
Chenjie Yu12e5e672018-09-14 15:54:59 -07001437 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001438 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__SYSTEM);
1439 e.writeLong(json.optLong(DiskStatsFileLogger.SYSTEM_KEY, -1L));
1440 e.writeLong(cacheTime);
1441 pulledData.add(e);
1442
Chenjie Yu12e5e672018-09-14 15:54:59 -07001443 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001444 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__OTHER);
1445 e.writeLong(json.optLong(DiskStatsFileLogger.MISC_KEY, -1L));
1446 e.writeLong(cacheTime);
1447 pulledData.add(e);
1448 } catch (IOException | JSONException e) {
1449 Slog.e(TAG, "exception reading diskstats cache file", e);
1450 }
1451 }
1452
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001453 private void pullNumBiometricsEnrolled(int modality, int tagId, long elapsedNanos,
1454 long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
Tej Singhd6d6d772018-09-05 17:41:25 -07001455 FingerprintManager fingerprintManager = mContext.getSystemService(FingerprintManager.class);
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001456 FaceManager faceManager = mContext.getSystemService(FaceManager.class);
1457 if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT && fingerprintManager == null) {
1458 return;
1459 }
1460 if (modality == BiometricsProtoEnums.MODALITY_FACE && faceManager == null) {
Tej Singhd6d6d772018-09-05 17:41:25 -07001461 return;
1462 }
1463 UserManager userManager = mContext.getSystemService(UserManager.class);
1464 if (userManager == null) {
1465 return;
1466 }
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001467
Tej Singhd6d6d772018-09-05 17:41:25 -07001468 final long token = Binder.clearCallingIdentity();
Tej Singhd6d6d772018-09-05 17:41:25 -07001469 for (UserInfo user : userManager.getUsers()) {
1470 final int userId = user.getUserHandle().getIdentifier();
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001471 int numEnrolled = 0;
1472 if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT) {
1473 numEnrolled = fingerprintManager.getEnrolledFingerprints(userId).size();
1474 } else if (modality == BiometricsProtoEnums.MODALITY_FACE) {
1475 numEnrolled = faceManager.getEnrolledFaces(userId).size();
1476 } else {
1477 return;
1478 }
Chenjie Yu12e5e672018-09-14 15:54:59 -07001479 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singhd6d6d772018-09-05 17:41:25 -07001480 e.writeInt(userId);
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001481 e.writeInt(numEnrolled);
Tej Singhd6d6d772018-09-05 17:41:25 -07001482 pulledData.add(e);
1483 }
1484 Binder.restoreCallingIdentity(token);
1485 }
1486
Chenjie Yub52779e2018-10-05 12:03:36 -07001487 // read high watermark for section
1488 private long readProcStatsHighWaterMark(int section) {
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001489 try {
Chenjie Yub52779e2018-10-05 12:03:36 -07001490 File[] files = mBaseDir.listFiles((d, name) -> {
1491 return name.toLowerCase().startsWith(String.valueOf(section) + '_');
1492 });
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001493 if (files == null || files.length == 0) {
1494 return 0;
1495 }
1496 if (files.length > 1) {
1497 Log.e(TAG, "Only 1 file expected for high water mark. Found " + files.length);
1498 }
Chenjie Yub52779e2018-10-05 12:03:36 -07001499 return Long.valueOf(files[0].getName().split("_")[1]);
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001500 } catch (SecurityException e) {
1501 Log.e(TAG, "Failed to get procstats high watermark file.", e);
1502 } catch (NumberFormatException e) {
1503 Log.e(TAG, "Failed to parse file name.", e);
1504 }
1505 return 0;
1506 }
1507
1508 private IProcessStats mProcessStats =
1509 IProcessStats.Stub.asInterface(ServiceManager.getService(ProcessStats.SERVICE_NAME));
1510
Chenjie Yub52779e2018-10-05 12:03:36 -07001511 private void pullProcessStats(int section, int tagId, long elapsedNanos, long wallClockNanos,
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001512 List<StatsLogEventWrapper> pulledData) {
Yangster-mac95543242018-10-22 11:44:03 -07001513 synchronized (this) {
1514 try {
1515 long lastHighWaterMark = readProcStatsHighWaterMark(section);
1516 List<ParcelFileDescriptor> statsFiles = new ArrayList<>();
1517 long highWaterMark = mProcessStats.getCommittedStats(
1518 lastHighWaterMark, section, true, statsFiles);
1519 if (statsFiles.size() != 1) {
1520 return;
1521 }
1522 InputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(
1523 statsFiles.get(0));
1524 int[] len = new int[1];
1525 byte[] stats = readFully(stream, len);
1526 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1527 wallClockNanos);
1528 e.writeStorage(Arrays.copyOf(stats, len[0]));
1529 pulledData.add(e);
1530 new File(mBaseDir.getAbsolutePath() + "/" + section + "_"
1531 + lastHighWaterMark).delete();
1532 new File(
1533 mBaseDir.getAbsolutePath() + "/" + section + "_"
1534 + highWaterMark).createNewFile();
1535 } catch (IOException e) {
1536 Log.e(TAG, "Getting procstats failed: ", e);
1537 } catch (RemoteException e) {
1538 Log.e(TAG, "Getting procstats failed: ", e);
1539 } catch (SecurityException e) {
1540 Log.e(TAG, "Getting procstats failed: ", e);
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001541 }
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001542 }
1543 }
1544
1545 static byte[] readFully(InputStream stream, int[] outLen) throws IOException {
1546 int pos = 0;
1547 final int initialAvail = stream.available();
1548 byte[] data = new byte[initialAvail > 0 ? (initialAvail + 1) : 16384];
1549 while (true) {
1550 int amt = stream.read(data, pos, data.length - pos);
1551 if (DEBUG) {
1552 Slog.i(TAG, "Read " + amt + " bytes at " + pos + " of avail " + data.length);
1553 }
1554 if (amt < 0) {
1555 if (DEBUG) {
1556 Slog.i(TAG, "**** FINISHED READING: pos=" + pos + " len=" + data.length);
1557 }
1558 outLen[0] = pos;
1559 return data;
1560 }
1561 pos += amt;
1562 if (pos >= data.length) {
1563 byte[] newData = new byte[pos + 16384];
1564 if (DEBUG) {
1565 Slog.i(TAG, "Copying " + pos + " bytes to new array len " + newData.length);
1566 }
1567 System.arraycopy(data, 0, newData, 0, pos);
1568 data = newData;
1569 }
1570 }
1571 }
1572
Chenjie Yuab530202018-09-26 12:39:20 -07001573 private void pullPowerProfile(
1574 int tagId, long elapsedNanos, long wallClockNanos,
1575 List<StatsLogEventWrapper> pulledData) {
1576 PowerProfile powerProfile = new PowerProfile(mContext);
1577 checkNotNull(powerProfile);
1578
1579 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1580 wallClockNanos);
1581 ProtoOutputStream proto = new ProtoOutputStream();
1582 powerProfile.writeToProto(proto);
1583 proto.flush();
1584 e.writeStorage(proto.getBytes());
1585 pulledData.add(e);
1586 }
1587
Bookatz366a4432018-11-20 09:42:33 -08001588 private void pullBuildInformation(int tagId,
1589 long elapsedNanos, long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1590 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1591 e.writeString(Build.FINGERPRINT);
1592 e.writeString(Build.BRAND);
1593 e.writeString(Build.PRODUCT);
1594 e.writeString(Build.DEVICE);
1595 e.writeString(Build.VERSION.RELEASE);
1596 e.writeString(Build.ID);
1597 e.writeString(Build.VERSION.INCREMENTAL);
1598 e.writeString(Build.TYPE);
1599 e.writeString(Build.TAGS);
1600 pulledData.add(e);
1601 }
1602
Bookatz75ee6042018-11-09 12:27:37 -08001603 private BatteryStatsHelper getBatteryStatsHelper() {
1604 if (mBatteryStatsHelper == null) {
1605 final long callingToken = Binder.clearCallingIdentity();
1606 try {
1607 // clearCallingIdentity required for BatteryStatsHelper.checkWifiOnly().
1608 mBatteryStatsHelper = new BatteryStatsHelper(mContext, false);
1609 } finally {
1610 Binder.restoreCallingIdentity(callingToken);
1611 }
1612 mBatteryStatsHelper.create((Bundle) null);
1613 }
1614 long currentTime = SystemClock.elapsedRealtime();
1615 if (currentTime - mBatteryStatsHelperTimestampMs >= MAX_BATTERY_STATS_HELPER_FREQUENCY_MS) {
1616 // Load BatteryStats and do all the calculations.
1617 mBatteryStatsHelper.refreshStats(BatteryStats.STATS_SINCE_CHARGED, UserHandle.USER_ALL);
1618 // Calculations are done so we don't need to save the raw BatteryStats data in RAM.
1619 mBatteryStatsHelper.clearStats();
1620 mBatteryStatsHelperTimestampMs = currentTime;
1621 }
1622 return mBatteryStatsHelper;
1623 }
1624
Bookatz3dbc13a2018-12-21 12:16:51 -08001625 private long milliAmpHrsToNanoAmpSecs(double mAh) {
1626 final long MILLI_AMP_HR_TO_NANO_AMP_SECS = 1_000_000L * 3600L;
1627 return (long) (mAh * MILLI_AMP_HR_TO_NANO_AMP_SECS + 0.5);
1628 }
1629
Bookatz75ee6042018-11-09 12:27:37 -08001630 private void pullDeviceCalculatedPowerUse(int tagId,
1631 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1632 BatteryStatsHelper bsHelper = getBatteryStatsHelper();
1633 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Bookatz3dbc13a2018-12-21 12:16:51 -08001634 e.writeLong(milliAmpHrsToNanoAmpSecs(bsHelper.getComputedPower()));
Bookatz75ee6042018-11-09 12:27:37 -08001635 pulledData.add(e);
1636 }
1637
1638 private void pullDeviceCalculatedPowerBlameUid(int tagId,
1639 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1640 final List<BatterySipper> sippers = getBatteryStatsHelper().getUsageList();
1641 if (sippers == null) {
1642 return;
1643 }
1644 for (BatterySipper bs : sippers) {
1645 if (bs.drainType != bs.drainType.APP) {
1646 continue;
1647 }
1648 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1649 e.writeInt(bs.uidObj.getUid());
Bookatz3dbc13a2018-12-21 12:16:51 -08001650 e.writeLong(milliAmpHrsToNanoAmpSecs(bs.totalPowerMah));
Bookatz75ee6042018-11-09 12:27:37 -08001651 pulledData.add(e);
1652 }
1653 }
1654
1655 private void pullDeviceCalculatedPowerBlameOther(int tagId,
1656 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1657 final List<BatterySipper> sippers = getBatteryStatsHelper().getUsageList();
1658 if (sippers == null) {
1659 return;
1660 }
1661 for (BatterySipper bs : sippers) {
1662 if (bs.drainType == bs.drainType.APP) {
1663 continue; // This is a separate atom; see pullDeviceCalculatedPowerBlameUid().
1664 }
1665 if (bs.drainType == bs.drainType.USER) {
1666 continue; // This is not supported. We purposefully calculate over USER_ALL.
1667 }
1668 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1669 e.writeInt(bs.drainType.ordinal());
Bookatz3dbc13a2018-12-21 12:16:51 -08001670 e.writeLong(milliAmpHrsToNanoAmpSecs(bs.totalPowerMah));
Bookatz75ee6042018-11-09 12:27:37 -08001671 pulledData.add(e);
1672 }
1673 }
1674
Tej Singhe7726dc2018-09-21 11:42:12 -07001675 private void pullDiskIo(int tagId, long elapsedNanos, final long wallClockNanos,
1676 List<StatsLogEventWrapper> pulledData) {
1677 mStoragedUidIoStatsReader.readAbsolute((uid, fgCharsRead, fgCharsWrite, fgBytesRead,
1678 fgBytesWrite, bgCharsRead, bgCharsWrite, bgBytesRead, bgBytesWrite,
1679 fgFsync, bgFsync) -> {
Chenjie Yuab530202018-09-26 12:39:20 -07001680 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1681 wallClockNanos);
Tej Singhe7726dc2018-09-21 11:42:12 -07001682 e.writeInt(uid);
1683 e.writeLong(fgCharsRead);
1684 e.writeLong(fgCharsWrite);
1685 e.writeLong(fgBytesRead);
1686 e.writeLong(fgBytesWrite);
1687 e.writeLong(bgCharsRead);
1688 e.writeLong(bgCharsWrite);
1689 e.writeLong(bgBytesRead);
1690 e.writeLong(bgBytesWrite);
1691 e.writeLong(fgFsync);
1692 e.writeLong(bgFsync);
1693 pulledData.add(e);
1694 });
1695 }
1696
Yangster-mac308ea0c2018-10-22 13:10:25 -07001697 private void pullProcessCpuTime(int tagId, long elapsedNanos, final long wallClockNanos,
1698 List<StatsLogEventWrapper> pulledData) {
1699 synchronized (this) {
1700 if (mProcessCpuTracker == null) {
1701 mProcessCpuTracker = new ProcessCpuTracker(false);
1702 mProcessCpuTracker.init();
1703 }
1704 mProcessCpuTracker.update();
1705 for (int i = 0; i < mProcessCpuTracker.countStats(); i++) {
1706 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
1707 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1708 wallClockNanos);
1709 e.writeInt(st.uid);
1710 e.writeString(st.name);
1711 e.writeLong(st.base_utime);
1712 e.writeLong(st.base_stime);
1713 pulledData.add(e);
1714 }
1715 }
1716 }
1717
Misha Wagner5a51e002018-10-03 15:04:09 +01001718 private void pullCpuTimePerThreadFreq(int tagId, long elapsedNanos, long wallClockNanos,
1719 List<StatsLogEventWrapper> pulledData) {
1720 if (this.mKernelCpuThreadReader == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001721 throw new IllegalStateException("mKernelCpuThreadReader is null");
Misha Wagner5a51e002018-10-03 15:04:09 +01001722 }
Misha Wagnerdc797542018-10-29 13:21:34 +00001723 ArrayList<KernelCpuThreadReader.ProcessCpuUsage> processCpuUsages =
Misha Wagner3989eb02019-03-19 11:05:37 +00001724 this.mKernelCpuThreadReader.getProcessCpuUsage();
Misha Wagnerdc797542018-10-29 13:21:34 +00001725 if (processCpuUsages == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001726 throw new IllegalStateException("processCpuUsages is null");
Misha Wagner5a51e002018-10-03 15:04:09 +01001727 }
1728 int[] cpuFrequencies = mKernelCpuThreadReader.getCpuFrequenciesKhz();
Misha Wagner4b32c9f2019-01-25 15:30:14 +00001729 if (cpuFrequencies.length > CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001730 String message = "Expected maximum " + CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES
1731 + " frequencies, but got " + cpuFrequencies.length;
1732 Slog.w(TAG, message);
1733 throw new IllegalStateException(message);
Misha Wagnerfde69582018-11-28 13:26:32 +00001734 }
Misha Wagnerdc797542018-10-29 13:21:34 +00001735 for (int i = 0; i < processCpuUsages.size(); i++) {
1736 KernelCpuThreadReader.ProcessCpuUsage processCpuUsage = processCpuUsages.get(i);
1737 ArrayList<KernelCpuThreadReader.ThreadCpuUsage> threadCpuUsages =
1738 processCpuUsage.threadCpuUsages;
1739 for (int j = 0; j < threadCpuUsages.size(); j++) {
1740 KernelCpuThreadReader.ThreadCpuUsage threadCpuUsage = threadCpuUsages.get(j);
1741 if (threadCpuUsage.usageTimesMillis.length != cpuFrequencies.length) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001742 String message = "Unexpected number of usage times,"
Misha Wagnerdc797542018-10-29 13:21:34 +00001743 + " expected " + cpuFrequencies.length
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001744 + " but got " + threadCpuUsage.usageTimesMillis.length;
1745 Slog.w(TAG, message);
1746 throw new IllegalStateException(message);
Misha Wagner5a51e002018-10-03 15:04:09 +01001747 }
1748
Misha Wagnerfde69582018-11-28 13:26:32 +00001749 StatsLogEventWrapper e =
1750 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1751 e.writeInt(processCpuUsage.uid);
1752 e.writeInt(processCpuUsage.processId);
1753 e.writeInt(threadCpuUsage.threadId);
1754 e.writeString(processCpuUsage.processName);
1755 e.writeString(threadCpuUsage.threadName);
Misha Wagner4b32c9f2019-01-25 15:30:14 +00001756 for (int k = 0; k < CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES; k++) {
1757 if (k < cpuFrequencies.length) {
1758 e.writeInt(cpuFrequencies[k]);
1759 e.writeInt(threadCpuUsage.usageTimesMillis[k]);
1760 } else {
1761 // If we have no more frequencies to write, we still must write empty data.
1762 // We know that this data is empty (and not just zero) because all
1763 // frequencies are expected to be greater than zero
1764 e.writeInt(0);
1765 e.writeInt(0);
1766 }
Misha Wagnerdc797542018-10-29 13:21:34 +00001767 }
Misha Wagnerfde69582018-11-28 13:26:32 +00001768 pulledData.add(e);
Misha Wagner5a51e002018-10-03 15:04:09 +01001769 }
1770 }
1771 }
1772
Tej Singh9876a3b2019-01-11 14:28:35 -08001773 private void pullTemperature(int tagId, long elapsedNanos, long wallClockNanos,
1774 List<StatsLogEventWrapper> pulledData) {
1775 long callingToken = Binder.clearCallingIdentity();
1776 try {
1777 List<Temperature> temperatures = sThermalService.getCurrentTemperatures();
1778 for (Temperature temp : temperatures) {
1779 StatsLogEventWrapper e =
1780 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1781 e.writeInt(temp.getType());
1782 e.writeString(temp.getName());
1783 e.writeInt((int) (temp.getValue() * 10));
1784 pulledData.add(e);
1785 }
1786 } catch (RemoteException e) {
1787 // Should not happen.
1788 Slog.e(TAG, "Disconnected from thermal service. Cannot pull temperatures.");
1789 } finally {
1790 Binder.restoreCallingIdentity(callingToken);
1791 }
1792 }
1793
Olivier Gaillard18d452202019-01-22 15:03:41 +00001794 private void pullDebugElapsedClock(int tagId,
1795 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1796 final long elapsedMillis = SystemClock.elapsedRealtime();
1797 final long clockDiffMillis = mDebugElapsedClockPreviousValue == 0
1798 ? 0 : elapsedMillis - mDebugElapsedClockPreviousValue;
1799
1800 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1801 e.writeLong(mDebugElapsedClockPullCount);
1802 e.writeLong(elapsedMillis);
1803 // Log it twice to be able to test multi-value aggregation from ValueMetric.
1804 e.writeLong(elapsedMillis);
1805 e.writeLong(clockDiffMillis);
1806 e.writeInt(1 /* always set */);
1807 pulledData.add(e);
1808
1809 if (mDebugElapsedClockPullCount % 2 == 1) {
1810 StatsLogEventWrapper e2 = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1811 e2.writeLong(mDebugElapsedClockPullCount);
1812 e2.writeLong(elapsedMillis);
1813 // Log it twice to be able to test multi-value aggregation from ValueMetric.
1814 e2.writeLong(elapsedMillis);
1815 e2.writeLong(clockDiffMillis);
1816 e2.writeInt(2 /* set on odd pulls */);
1817 pulledData.add(e2);
1818 }
1819
1820 mDebugElapsedClockPullCount++;
1821 mDebugElapsedClockPreviousValue = elapsedMillis;
1822 }
1823
1824 private void pullDebugFailingElapsedClock(int tagId,
1825 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1826 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1827 final long elapsedMillis = SystemClock.elapsedRealtime();
Olivier Gaillard4f01a372019-02-04 14:25:14 +00001828 // Fails every 5 buckets.
1829 if (mDebugFailingElapsedClockPullCount++ % 5 == 0) {
Olivier Gaillard18d452202019-01-22 15:03:41 +00001830 mDebugFailingElapsedClockPreviousValue = elapsedMillis;
1831 throw new RuntimeException("Failing debug elapsed clock");
1832 }
1833
1834 e.writeLong(mDebugFailingElapsedClockPullCount);
1835 e.writeLong(elapsedMillis);
1836 // Log it twice to be able to test multi-value aggregation from ValueMetric.
1837 e.writeLong(elapsedMillis);
1838 e.writeLong(mDebugFailingElapsedClockPreviousValue == 0
1839 ? 0 : elapsedMillis - mDebugFailingElapsedClockPreviousValue);
1840 mDebugFailingElapsedClockPreviousValue = elapsedMillis;
1841 pulledData.add(e);
1842 }
1843
Philip P. Moltmannf21a3502019-01-30 09:53:04 -08001844 private void pullDangerousPermissionState(long elapsedNanos, final long wallClockNanos,
1845 List<StatsLogEventWrapper> pulledData) {
1846 long token = Binder.clearCallingIdentity();
1847 try {
1848 PackageManager pm = mContext.getPackageManager();
1849
1850 List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
1851
1852 int numUsers = users.size();
1853 for (int userNum = 0; userNum < numUsers; userNum++) {
1854 UserHandle user = users.get(userNum).getUserHandle();
1855
1856 List<PackageInfo> pkgs = pm.getInstalledPackagesAsUser(
1857 PackageManager.GET_PERMISSIONS, user.getIdentifier());
1858
1859 int numPkgs = pkgs.size();
1860 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
1861 PackageInfo pkg = pkgs.get(pkgNum);
1862
1863 if (pkg.requestedPermissions == null) {
1864 continue;
1865 }
1866
1867 int numPerms = pkg.requestedPermissions.length;
1868 for (int permNum = 0; permNum < numPerms; permNum++) {
1869 String permName = pkg.requestedPermissions[permNum];
1870
1871 PermissionInfo permissionInfo;
1872 try {
1873 permissionInfo = pm.getPermissionInfo(permName, 0);
1874 } catch (PackageManager.NameNotFoundException ignored) {
1875 continue;
1876 }
1877
1878 if (permissionInfo.getProtection() != PROTECTION_DANGEROUS) {
1879 continue;
1880 }
1881
1882 StatsLogEventWrapper e = new StatsLogEventWrapper(
1883 StatsLog.DANGEROUS_PERMISSION_STATE, elapsedNanos, wallClockNanos);
1884
1885 e.writeString(permName);
1886 e.writeInt(pkg.applicationInfo.uid);
1887 e.writeString(pkg.packageName);
1888
1889 e.writeBoolean((pkg.requestedPermissionsFlags[permNum]
1890 & REQUESTED_PERMISSION_GRANTED) != 0);
1891
1892 pulledData.add(e);
1893 }
1894 }
1895 }
1896 } catch (Throwable t) {
1897 Log.e(TAG, "Could not read permissions", t);
1898 } finally {
1899 Binder.restoreCallingIdentity(token);
1900 }
1901 }
1902
Chenjie Yu05013b32017-11-21 10:21:41 -08001903 /**
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08001904 * Add a RoleHolder atom for each package that holds a role.
1905 *
1906 * @param elapsedNanos the time since boot
1907 * @param wallClockNanos the time on the clock
1908 * @param pulledData the data sink to write to
1909 */
1910 private void pullRoleHolders(long elapsedNanos, final long wallClockNanos,
1911 @NonNull List<StatsLogEventWrapper> pulledData) {
1912 long callingToken = Binder.clearCallingIdentity();
1913 try {
1914 PackageManager pm = mContext.getPackageManager();
Hai Zhang85fd0622019-02-01 14:06:04 -08001915 RoleManagerInternal rmi = LocalServices.getService(RoleManagerInternal.class);
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08001916
1917 List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
1918
1919 int numUsers = users.size();
1920 for (int userNum = 0; userNum < numUsers; userNum++) {
Hai Zhang85fd0622019-02-01 14:06:04 -08001921 int userId = users.get(userNum).getUserHandle().getIdentifier();
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08001922
Hai Zhang85fd0622019-02-01 14:06:04 -08001923 ArrayMap<String, ArraySet<String>> roles = rmi.getRolesAndHolders(
1924 userId);
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08001925
1926 int numRoles = roles.size();
1927 for (int roleNum = 0; roleNum < numRoles; roleNum++) {
1928 String roleName = roles.keyAt(roleNum);
1929 ArraySet<String> holders = roles.valueAt(roleNum);
1930
1931 int numHolders = holders.size();
1932 for (int holderNum = 0; holderNum < numHolders; holderNum++) {
1933 String holderName = holders.valueAt(holderNum);
1934
1935 PackageInfo pkg;
1936 try {
Hai Zhang85fd0622019-02-01 14:06:04 -08001937 pkg = pm.getPackageInfoAsUser(holderName, 0, userId);
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08001938 } catch (PackageManager.NameNotFoundException e) {
1939 Log.w(TAG, "Role holder " + holderName + " not found");
1940 return;
1941 }
1942
1943 StatsLogEventWrapper e = new StatsLogEventWrapper(StatsLog.ROLE_HOLDER,
1944 elapsedNanos, wallClockNanos);
1945 e.writeInt(pkg.applicationInfo.uid);
1946 e.writeString(holderName);
1947 e.writeString(roleName);
1948 pulledData.add(e);
1949 }
1950 }
1951 }
1952 } finally {
1953 Binder.restoreCallingIdentity(callingToken);
1954 }
1955 }
1956
Neil Fullerdb14b482019-02-05 19:44:44 +00001957 private void pullTimeZoneDataInfo(int tagId,
1958 long elapsedNanos, long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1959 String tzDbVersion = "Unknown";
1960 try {
1961 tzDbVersion = android.icu.util.TimeZone.getTZDataVersion();
1962 } catch (Exception e) {
1963 Log.e(TAG, "Getting tzdb version failed: ", e);
1964 }
1965
1966 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1967 e.writeString(tzDbVersion);
1968 pulledData.add(e);
1969 }
1970
Carmen Agimof35f7f6f2019-02-05 18:19:21 +00001971 private void pullSDCardInfo(int tagId, long elapsedNanos, long wallClockNanos,
1972 List<StatsLogEventWrapper> pulledData) {
1973 StorageManager storageManager = mContext.getSystemService(StorageManager.class);
1974 if (storageManager != null) {
1975 List<VolumeInfo> volumes = storageManager.getVolumes();
1976 for (VolumeInfo vol : volumes) {
1977 final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
1978 final DiskInfo diskInfo = vol.getDisk();
1979 if (diskInfo != null && diskInfo.isSd()) {
1980 if (envState.equals(Environment.MEDIA_MOUNTED)) {
1981 StatsLogEventWrapper e =
1982 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1983 e.writeInt(vol.getType() + 1);
1984 e.writeLong(diskInfo.size);
1985 pulledData.add(e);
1986 }
1987 }
1988 }
1989 }
1990 }
1991
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08001992 /**
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001993 * Pulls various data.
Chenjie Yu05013b32017-11-21 10:21:41 -08001994 */
Bookatzc68a9d22017-09-27 14:09:55 -07001995 @Override // Binder call
Chenjie Yu5305e1d2017-10-31 13:49:36 -07001996 public StatsLogEventWrapper[] pullData(int tagId) {
Bookatzc68a9d22017-09-27 14:09:55 -07001997 enforceCallingPermission();
Chenjie Yu12e5e672018-09-14 15:54:59 -07001998 if (DEBUG) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -07001999 Slog.d(TAG, "Pulling " + tagId);
Chenjie Yu12e5e672018-09-14 15:54:59 -07002000 }
Rajeev Kumar22d92b72018-02-07 18:38:36 -08002001 List<StatsLogEventWrapper> ret = new ArrayList<>();
Chenjie Yu12e5e672018-09-14 15:54:59 -07002002 long elapsedNanos = SystemClock.elapsedRealtimeNanos();
2003 long wallClockNanos = SystemClock.currentTimeMicro() * 1000L;
Chenjie Yu5305e1d2017-10-31 13:49:36 -07002004 switch (tagId) {
Chenjie Yu31d14d72017-12-12 17:54:33 -08002005 case StatsLog.WIFI_BYTES_TRANSFER: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002006 pullWifiBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002007 break;
David Chenc8a43242017-10-17 16:23:28 -07002008 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002009 case StatsLog.MOBILE_BYTES_TRANSFER: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002010 pullMobileBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002011 break;
David Chenc8a43242017-10-17 16:23:28 -07002012 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002013 case StatsLog.WIFI_BYTES_TRANSFER_BY_FG_BG: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002014 pullWifiBytesTransferByFgBg(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002015 break;
David Chenc8a43242017-10-17 16:23:28 -07002016 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002017 case StatsLog.MOBILE_BYTES_TRANSFER_BY_FG_BG: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002018 pullMobileBytesTransferByFgBg(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002019 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002020 }
2021 case StatsLog.BLUETOOTH_BYTES_TRANSFER: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002022 pullBluetoothBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002023 break;
David Chenc8a43242017-10-17 16:23:28 -07002024 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002025 case StatsLog.KERNEL_WAKELOCK: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002026 pullKernelWakelock(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002027 break;
David Chen1481fe12017-10-16 13:16:34 -07002028 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002029 case StatsLog.CPU_TIME_PER_FREQ: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002030 pullCpuTimePerFreq(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002031 break;
Chenjie Yu7f8def92017-11-03 09:33:15 -07002032 }
Chenjie Yuec676612018-03-07 09:19:17 -08002033 case StatsLog.CPU_TIME_PER_UID: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002034 pullKernelUidCpuTime(tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yuec676612018-03-07 09:19:17 -08002035 break;
2036 }
2037 case StatsLog.CPU_TIME_PER_UID_FREQ: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002038 pullKernelUidCpuFreqTime(tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yuec676612018-03-07 09:19:17 -08002039 break;
2040 }
2041 case StatsLog.CPU_CLUSTER_TIME: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002042 pullKernelUidCpuClusterTime(tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yuec676612018-03-07 09:19:17 -08002043 break;
2044 }
2045 case StatsLog.CPU_ACTIVE_TIME: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002046 pullKernelUidCpuActiveTime(tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yuec676612018-03-07 09:19:17 -08002047 break;
2048 }
Chenjie Yu5caaa9d2018-03-06 15:48:54 -08002049 case StatsLog.WIFI_ACTIVITY_INFO: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002050 pullWifiActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002051 break;
Chenjie Yu05013b32017-11-21 10:21:41 -08002052 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002053 case StatsLog.MODEM_ACTIVITY_INFO: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002054 pullModemActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002055 break;
Chenjie Yu05013b32017-11-21 10:21:41 -08002056 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002057 case StatsLog.BLUETOOTH_ACTIVITY_INFO: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002058 pullBluetoothActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002059 break;
Chenjie Yu937d7422018-01-10 16:37:53 -08002060 }
2061 case StatsLog.SYSTEM_UPTIME: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002062 pullSystemUpTime(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002063 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002064 }
2065 case StatsLog.SYSTEM_ELAPSED_REALTIME: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002066 pullSystemElapsedRealtime(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002067 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002068 }
Rajeev Kumar22d92b72018-02-07 18:38:36 -08002069 case StatsLog.PROCESS_MEMORY_STATE: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002070 pullProcessMemoryState(tagId, elapsedNanos, wallClockNanos, ret);
Rajeev Kumar22d92b72018-02-07 18:38:36 -08002071 break;
2072 }
Rafal Slawik08621582018-10-15 14:53:07 +01002073 case StatsLog.NATIVE_PROCESS_MEMORY_STATE: {
2074 pullNativeProcessMemoryState(tagId, elapsedNanos, wallClockNanos, ret);
2075 break;
2076 }
Rafal Slawik3bea8952018-11-15 12:39:33 +00002077 case StatsLog.PROCESS_MEMORY_HIGH_WATER_MARK: {
2078 pullProcessMemoryHighWaterMark(tagId, elapsedNanos, wallClockNanos, ret);
2079 break;
2080 }
Rafal Slawikd4e87572019-03-12 13:08:38 +00002081 case StatsLog.SYSTEM_ION_HEAP_SIZE: {
2082 pullSystemIonHeapSize(tagId, elapsedNanos, wallClockNanos, ret);
2083 break;
2084 }
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01002085 case StatsLog.BINDER_CALLS: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002086 pullBinderCallsStats(tagId, elapsedNanos, wallClockNanos, ret);
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01002087 break;
2088 }
Olivier Gaillard6f52d152018-07-25 12:13:12 +01002089 case StatsLog.BINDER_CALLS_EXCEPTIONS: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002090 pullBinderCallsStatsExceptions(tagId, elapsedNanos, wallClockNanos, ret);
Olivier Gaillard6f52d152018-07-25 12:13:12 +01002091 break;
2092 }
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01002093 case StatsLog.LOOPER_STATS: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002094 pullLooperStats(tagId, elapsedNanos, wallClockNanos, ret);
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01002095 break;
2096 }
Tej Singh86dc9db2018-09-06 00:39:57 +00002097 case StatsLog.DISK_STATS: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002098 pullDiskStats(tagId, elapsedNanos, wallClockNanos, ret);
Tej Singh86dc9db2018-09-06 00:39:57 +00002099 break;
2100 }
2101 case StatsLog.DIRECTORY_USAGE: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002102 pullDirectoryUsage(tagId, elapsedNanos, wallClockNanos, ret);
Tej Singh86dc9db2018-09-06 00:39:57 +00002103 break;
2104 }
2105 case StatsLog.APP_SIZE: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002106 pullAppSize(tagId, elapsedNanos, wallClockNanos, ret);
Tej Singh86dc9db2018-09-06 00:39:57 +00002107 break;
2108 }
2109 case StatsLog.CATEGORY_SIZE: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002110 pullCategorySize(tagId, elapsedNanos, wallClockNanos, ret);
Tej Singh86dc9db2018-09-06 00:39:57 +00002111 break;
2112 }
Kevin Chyn1741a072019-01-17 11:54:40 -08002113 case StatsLog.NUM_FINGERPRINTS_ENROLLED: {
Kevin Chyn6ecc5702019-01-28 12:00:37 -08002114 pullNumBiometricsEnrolled(BiometricsProtoEnums.MODALITY_FINGERPRINT, tagId,
2115 elapsedNanos, wallClockNanos, ret);
2116 break;
2117 }
2118 case StatsLog.NUM_FACES_ENROLLED: {
2119 pullNumBiometricsEnrolled(BiometricsProtoEnums.MODALITY_FACE, tagId, elapsedNanos,
2120 wallClockNanos, ret);
Tej Singhd6d6d772018-09-05 17:41:25 -07002121 break;
2122 }
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002123 case StatsLog.PROC_STATS: {
Yang Lu1587e132018-10-22 16:19:40 +00002124 pullProcessStats(ProcessStats.REPORT_ALL, tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yub52779e2018-10-05 12:03:36 -07002125 break;
2126 }
2127 case StatsLog.PROC_STATS_PKG_PROC: {
2128 pullProcessStats(ProcessStats.REPORT_PKG_PROC_STATS, tagId, elapsedNanos,
2129 wallClockNanos, ret);
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002130 break;
2131 }
Tej Singhe7726dc2018-09-21 11:42:12 -07002132 case StatsLog.DISK_IO: {
2133 pullDiskIo(tagId, elapsedNanos, wallClockNanos, ret);
2134 break;
2135 }
Chenjie Yuab530202018-09-26 12:39:20 -07002136 case StatsLog.POWER_PROFILE: {
2137 pullPowerProfile(tagId, elapsedNanos, wallClockNanos, ret);
2138 break;
2139 }
Bookatz366a4432018-11-20 09:42:33 -08002140 case StatsLog.BUILD_INFORMATION: {
2141 pullBuildInformation(tagId, elapsedNanos, wallClockNanos, ret);
2142 break;
2143 }
Yangster-mac308ea0c2018-10-22 13:10:25 -07002144 case StatsLog.PROCESS_CPU_TIME: {
2145 pullProcessCpuTime(tagId, elapsedNanos, wallClockNanos, ret);
2146 break;
2147 }
Misha Wagner5a51e002018-10-03 15:04:09 +01002148 case StatsLog.CPU_TIME_PER_THREAD_FREQ: {
2149 pullCpuTimePerThreadFreq(tagId, elapsedNanos, wallClockNanos, ret);
2150 break;
2151 }
Bookatz75ee6042018-11-09 12:27:37 -08002152 case StatsLog.DEVICE_CALCULATED_POWER_USE: {
2153 pullDeviceCalculatedPowerUse(tagId, elapsedNanos, wallClockNanos, ret);
2154 break;
2155 }
2156 case StatsLog.DEVICE_CALCULATED_POWER_BLAME_UID: {
2157 pullDeviceCalculatedPowerBlameUid(tagId, elapsedNanos, wallClockNanos, ret);
2158 break;
2159 }
2160 case StatsLog.DEVICE_CALCULATED_POWER_BLAME_OTHER: {
2161 pullDeviceCalculatedPowerBlameOther(tagId, elapsedNanos, wallClockNanos, ret);
2162 break;
2163 }
Tej Singh9876a3b2019-01-11 14:28:35 -08002164 case StatsLog.TEMPERATURE: {
2165 pullTemperature(tagId, elapsedNanos, wallClockNanos, ret);
2166 break;
2167 }
Olivier Gaillard18d452202019-01-22 15:03:41 +00002168 case StatsLog.DEBUG_ELAPSED_CLOCK: {
2169 pullDebugElapsedClock(tagId, elapsedNanos, wallClockNanos, ret);
2170 break;
2171 }
2172 case StatsLog.DEBUG_FAILING_ELAPSED_CLOCK: {
2173 pullDebugFailingElapsedClock(tagId, elapsedNanos, wallClockNanos, ret);
2174 break;
2175 }
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08002176 case StatsLog.ROLE_HOLDER: {
2177 pullRoleHolders(elapsedNanos, wallClockNanos, ret);
2178 break;
2179 }
Philip P. Moltmannf21a3502019-01-30 09:53:04 -08002180 case StatsLog.DANGEROUS_PERMISSION_STATE: {
2181 pullDangerousPermissionState(elapsedNanos, wallClockNanos, ret);
2182 break;
2183 }
Neil Fullerdb14b482019-02-05 19:44:44 +00002184 case StatsLog.TIME_ZONE_DATA_INFO: {
2185 pullTimeZoneDataInfo(tagId, elapsedNanos, wallClockNanos, ret);
2186 break;
2187 }
Carmen Agimof35f7f6f2019-02-05 18:19:21 +00002188 case StatsLog.SDCARD_INFO: {
2189 pullSDCardInfo(tagId, elapsedNanos, wallClockNanos, ret);
2190 break;
2191 }
Bookatzc68a9d22017-09-27 14:09:55 -07002192 default:
Chenjie Yu5305e1d2017-10-31 13:49:36 -07002193 Slog.w(TAG, "No such tagId data as " + tagId);
Bookatzc68a9d22017-09-27 14:09:55 -07002194 return null;
2195 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002196 return ret.toArray(new StatsLogEventWrapper[ret.size()]);
Bookatzc68a9d22017-09-27 14:09:55 -07002197 }
2198
2199 @Override // Binder call
Bookatzb487b552017-09-18 11:26:01 -07002200 public void statsdReady() {
2201 enforceCallingPermission();
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002202 if (DEBUG) {
2203 Slog.d(TAG, "learned that statsdReady");
2204 }
Bookatzb487b552017-09-18 11:26:01 -07002205 sayHiToStatsd(); // tell statsd that we're ready too and link to it
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002206 mContext.sendBroadcastAsUser(new Intent(StatsManager.ACTION_STATSD_STARTED)
Bookatz81784082018-02-09 14:26:42 -08002207 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002208 UserHandle.SYSTEM, android.Manifest.permission.DUMP);
Bookatzb487b552017-09-18 11:26:01 -07002209 }
2210
David Chenc136f452017-11-27 11:52:26 -08002211 @Override
2212 public void triggerUidSnapshot() {
David Chen661f7912018-01-22 17:46:24 -08002213 enforceCallingPermission();
2214 synchronized (sStatsdLock) {
David Chen35045cb2018-03-23 22:21:47 -07002215 final long token = Binder.clearCallingIdentity();
David Chen661f7912018-01-22 17:46:24 -08002216 try {
2217 informAllUidsLocked(mContext);
2218 } catch (RemoteException e) {
2219 Slog.e(TAG, "Failed to trigger uid snapshot.", e);
David Chen35045cb2018-03-23 22:21:47 -07002220 } finally {
2221 restoreCallingIdentity(token);
David Chen661f7912018-01-22 17:46:24 -08002222 }
David Chenc136f452017-11-27 11:52:26 -08002223 }
David Chenc136f452017-11-27 11:52:26 -08002224 }
2225
Bookatz94726412017-08-31 09:26:15 -07002226 private void enforceCallingPermission() {
2227 if (Binder.getCallingPid() == Process.myPid()) {
2228 return;
2229 }
2230 mContext.enforceCallingPermission(android.Manifest.permission.STATSCOMPANION, null);
2231 }
2232
Bookatzb487b552017-09-18 11:26:01 -07002233 // Lifecycle and related code
2234
David Chen1481fe12017-10-16 13:16:34 -07002235 /**
2236 * Fetches the statsd IBinder service
2237 */
Bookatzb487b552017-09-18 11:26:01 -07002238 private static IStatsManager fetchStatsdService() {
2239 return IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
2240 }
2241
2242 public static final class Lifecycle extends SystemService {
2243 private StatsCompanionService mStatsCompanionService;
2244
2245 public Lifecycle(Context context) {
2246 super(context);
2247 }
2248
2249 @Override
2250 public void onStart() {
2251 mStatsCompanionService = new StatsCompanionService(getContext());
2252 try {
Chenjie Yuab530202018-09-26 12:39:20 -07002253 publishBinderService(Context.STATS_COMPANION_SERVICE,
2254 mStatsCompanionService);
Bookatzb487b552017-09-18 11:26:01 -07002255 if (DEBUG) Slog.d(TAG, "Published " + Context.STATS_COMPANION_SERVICE);
2256 } catch (Exception e) {
2257 Slog.e(TAG, "Failed to publishBinderService", e);
2258 }
2259 }
2260
2261 @Override
2262 public void onBootPhase(int phase) {
2263 super.onBootPhase(phase);
2264 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
2265 mStatsCompanionService.systemReady();
2266 }
2267 }
2268 }
2269
David Chen1481fe12017-10-16 13:16:34 -07002270 /**
2271 * Now that the android system is ready, StatsCompanion is ready too, so inform statsd.
2272 */
Bookatzb487b552017-09-18 11:26:01 -07002273 private void systemReady() {
2274 if (DEBUG) Slog.d(TAG, "Learned that systemReady");
2275 sayHiToStatsd();
2276 }
2277
David Chen1481fe12017-10-16 13:16:34 -07002278 /**
Chenjie Yuab530202018-09-26 12:39:20 -07002279 * Tells statsd that statscompanion is ready. If the binder call returns, link to
2280 * statsd.
David Chen1481fe12017-10-16 13:16:34 -07002281 */
Bookatzb487b552017-09-18 11:26:01 -07002282 private void sayHiToStatsd() {
2283 synchronized (sStatsdLock) {
2284 if (sStatsd != null) {
2285 Slog.e(TAG, "Trying to fetch statsd, but it was already fetched",
Chenjie Yuab530202018-09-26 12:39:20 -07002286 new IllegalStateException(
2287 "sStatsd is not null when being fetched"));
Bookatzb487b552017-09-18 11:26:01 -07002288 return;
2289 }
2290 sStatsd = fetchStatsdService();
2291 if (sStatsd == null) {
Chenjie Yuab530202018-09-26 12:39:20 -07002292 Slog.i(TAG,
2293 "Could not yet find statsd to tell it that StatsCompanion is "
2294 + "alive.");
Bookatzb487b552017-09-18 11:26:01 -07002295 return;
2296 }
2297 if (DEBUG) Slog.d(TAG, "Saying hi to statsd");
2298 try {
2299 sStatsd.statsCompanionReady();
2300 // If the statsCompanionReady two-way binder call returns, link to statsd.
2301 try {
2302 sStatsd.asBinder().linkToDeath(new StatsdDeathRecipient(), 0);
2303 } catch (RemoteException e) {
2304 Slog.e(TAG, "linkToDeath(StatsdDeathRecipient) failed", e);
yroe26c97b2018-03-27 10:30:11 -07002305 forgetEverythingLocked();
Bookatzb487b552017-09-18 11:26:01 -07002306 }
yro947fbce2017-11-15 22:50:23 -08002307 // Setup broadcast receiver for updates.
David Chende701692017-10-05 13:16:02 -07002308 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REPLACED);
2309 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
2310 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2311 filter.addDataScheme("package");
Chenjie Yuab530202018-09-26 12:39:20 -07002312 mContext.registerReceiverAsUser(mAppUpdateReceiver, UserHandle.ALL, filter,
2313 null,
David Chen1481fe12017-10-16 13:16:34 -07002314 null);
David Chen47e8f4d2017-10-11 15:34:13 -07002315
Chenjie Yuab530202018-09-26 12:39:20 -07002316 // Setup receiver for user initialize (which happens once for a new user)
2317 // and
David Chen47e8f4d2017-10-11 15:34:13 -07002318 // if a user is removed.
2319 filter = new IntentFilter(Intent.ACTION_USER_INITIALIZE);
2320 filter.addAction(Intent.ACTION_USER_REMOVED);
2321 mContext.registerReceiverAsUser(mUserUpdateReceiver, UserHandle.ALL,
David Chen1481fe12017-10-16 13:16:34 -07002322 filter, null, null);
David Chen47e8f4d2017-10-11 15:34:13 -07002323
yro947fbce2017-11-15 22:50:23 -08002324 // Setup receiver for device reboots or shutdowns.
2325 filter = new IntentFilter(Intent.ACTION_REBOOT);
2326 filter.addAction(Intent.ACTION_SHUTDOWN);
2327 mContext.registerReceiverAsUser(
2328 mShutdownEventReceiver, UserHandle.ALL, filter, null, null);
Yao Chen0f217102018-01-09 10:33:15 -08002329 final long token = Binder.clearCallingIdentity();
2330 try {
Chenjie Yuab530202018-09-26 12:39:20 -07002331 // Pull the latest state of UID->app name, version mapping when
2332 // statsd starts.
Yao Chen0f217102018-01-09 10:33:15 -08002333 informAllUidsLocked(mContext);
2334 } finally {
2335 restoreCallingIdentity(token);
2336 }
Bookatz111ed732018-02-16 15:54:05 -08002337 Slog.i(TAG, "Told statsd that StatsCompanionService is alive.");
Bookatzb487b552017-09-18 11:26:01 -07002338 } catch (RemoteException e) {
2339 Slog.e(TAG, "Failed to inform statsd that statscompanion is ready", e);
yroe26c97b2018-03-27 10:30:11 -07002340 forgetEverythingLocked();
Bookatzb487b552017-09-18 11:26:01 -07002341 }
2342 }
2343 }
2344
2345 private class StatsdDeathRecipient implements IBinder.DeathRecipient {
2346 @Override
2347 public void binderDied() {
2348 Slog.i(TAG, "Statsd is dead - erase all my knowledge.");
yroe26c97b2018-03-27 10:30:11 -07002349 synchronized (sStatsdLock) {
2350 long now = SystemClock.elapsedRealtime();
2351 for (Long timeMillis : mDeathTimeMillis) {
2352 long ageMillis = now - timeMillis;
2353 if (ageMillis > MILLIS_IN_A_DAY) {
2354 mDeathTimeMillis.remove(timeMillis);
2355 }
2356 }
2357 for (Long timeMillis : mDeletedFiles.keySet()) {
2358 long ageMillis = now - timeMillis;
2359 if (ageMillis > MILLIS_IN_A_DAY * 7) {
2360 mDeletedFiles.remove(timeMillis);
2361 }
2362 }
2363 mDeathTimeMillis.add(now);
2364 if (mDeathTimeMillis.size() >= DEATH_THRESHOLD) {
2365 mDeathTimeMillis.clear();
2366 File[] configs = FileUtils.listFilesOrEmpty(new File(CONFIG_DIR));
2367 if (configs.length > 0) {
2368 String fileName = configs[0].getName();
2369 if (configs[0].delete()) {
2370 mDeletedFiles.put(now, fileName);
2371 }
2372 }
2373 }
2374 forgetEverythingLocked();
2375 }
Bookatzb487b552017-09-18 11:26:01 -07002376 }
2377 }
2378
Andreas Gampe29520212018-07-20 12:55:37 -07002379 @GuardedBy("StatsCompanionService.sStatsdLock")
yroe26c97b2018-03-27 10:30:11 -07002380 private void forgetEverythingLocked() {
2381 sStatsd = null;
2382 mContext.unregisterReceiver(mAppUpdateReceiver);
2383 mContext.unregisterReceiver(mUserUpdateReceiver);
2384 mContext.unregisterReceiver(mShutdownEventReceiver);
2385 cancelAnomalyAlarm();
2386 cancelPullingAlarm();
Olivier Gaillard6e725272019-01-15 14:21:57 +00002387
2388 BinderCallsStatsService.Internal binderStats =
2389 LocalServices.getService(BinderCallsStatsService.Internal.class);
2390 if (binderStats != null) {
2391 binderStats.reset();
2392 }
2393
2394 LooperStats looperStats = LocalServices.getService(LooperStats.class);
2395 if (looperStats != null) {
2396 looperStats.reset();
2397 }
yroe26c97b2018-03-27 10:30:11 -07002398 }
2399
2400 @Override
2401 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2402 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
2403
Bookatzb487b552017-09-18 11:26:01 -07002404 synchronized (sStatsdLock) {
Chenjie Yuab530202018-09-26 12:39:20 -07002405 writer.println(
2406 "Number of configuration files deleted: " + mDeletedFiles.size());
yroe26c97b2018-03-27 10:30:11 -07002407 if (mDeletedFiles.size() > 0) {
2408 writer.println(" timestamp, deleted file name");
2409 }
2410 long lastBootMillis =
2411 SystemClock.currentThreadTimeMillis() - SystemClock.elapsedRealtime();
2412 for (Long elapsedMillis : mDeletedFiles.keySet()) {
2413 long deletionMillis = lastBootMillis + elapsedMillis;
Chenjie Yuab530202018-09-26 12:39:20 -07002414 writer.println(
2415 " " + deletionMillis + ", " + mDeletedFiles.get(elapsedMillis));
yroe26c97b2018-03-27 10:30:11 -07002416 }
Bookatzb487b552017-09-18 11:26:01 -07002417 }
2418 }
2419
Yangster-mace16189a2018-08-26 12:20:16 -07002420 // Thermal event received from vendor thermal management subsystem
2421 private static final class ThermalEventListener extends IThermalEventListener.Stub {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002422 @Override
Wei Wangbad7c202018-11-01 11:57:39 -07002423 public void notifyThrottling(Temperature temp) {
2424 boolean isThrottling = temp.getStatus() >= Temperature.THROTTLING_SEVERE;
Yangster-mace16189a2018-08-26 12:20:16 -07002425 StatsLog.write(StatsLog.THERMAL_THROTTLING, temp.getType(),
Tejinder Singh9ee9ba32018-11-08 16:56:16 -08002426 isThrottling ?
2427 StatsLog.THERMAL_THROTTLING_STATE_CHANGED__STATE__START :
2428 StatsLog.THERMAL_THROTTLING_STATE_CHANGED__STATE__STOP,
2429 temp.getValue());
Yangster-mace16189a2018-08-26 12:20:16 -07002430 }
2431 }
Chenjie Yuae9dfac2018-10-25 16:06:56 -07002432
2433 private static final class ConnectivityStatsCallback extends
2434 ConnectivityManager.NetworkCallback {
2435 @Override
2436 public void onAvailable(Network network) {
2437 StatsLog.write(StatsLog.CONNECTIVITY_STATE_CHANGED, network.netId,
2438 StatsLog.CONNECTIVITY_STATE_CHANGED__STATE__CONNECTED);
2439 }
2440
2441 @Override
2442 public void onLost(Network network) {
2443 StatsLog.write(StatsLog.CONNECTIVITY_STATE_CHANGED, network.netId,
2444 StatsLog.CONNECTIVITY_STATE_CHANGED__STATE__DISCONNECTED);
2445 }
2446 }
Bookatz94726412017-08-31 09:26:15 -07002447}