blob: 518a29c2017a157412087b1b8c9e0e2faed3b816 [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
Martijn Coenencd95d462019-04-25 17:09:45 +020018import static android.app.AppOpsManager.OP_FLAGS_ALL_TRUSTED;
Philip P. Moltmannf21a3502019-01-30 09:53:04 -080019import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
20import static android.content.pm.PermissionInfo.PROTECTION_DANGEROUS;
Rafal Slawikc3762622018-11-07 12:07:26 +000021import static android.os.Process.getPidsForCommands;
22import static android.os.Process.getUidForPid;
Carmen Agimof12dec122019-03-06 16:14:38 +000023import static android.os.storage.VolumeInfo.TYPE_PRIVATE;
24import static android.os.storage.VolumeInfo.TYPE_PUBLIC;
Rafal Slawikc3762622018-11-07 12:07:26 +000025
Chenjie Yuab530202018-09-26 12:39:20 -070026import static com.android.internal.util.Preconditions.checkNotNull;
Ioannis Ilkos466ad6c2019-06-18 17:42:00 +010027import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
Rafal Slawik23628e02019-09-11 15:52:09 +010028import static com.android.server.stats.IonMemoryUtil.readProcessSystemIonHeapSizesFromDebugfs;
29import static com.android.server.stats.IonMemoryUtil.readSystemIonHeapSizeFromDebugfs;
Rafal Slawik203c3db2019-09-25 19:53:01 +010030import static com.android.server.stats.ProcfsMemoryUtil.readCmdlineFromProcfs;
Rafal Slawik7efcefb2019-09-20 11:16:20 +010031import static com.android.server.stats.ProcfsMemoryUtil.readMemorySnapshotFromProcfs;
Chenjie Yuab530202018-09-26 12:39:20 -070032
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -080033import android.annotation.NonNull;
Chenjie Yu05013b32017-11-21 10:21:41 -080034import android.annotation.Nullable;
Rajeev Kumar22d92b72018-02-07 18:38:36 -080035import android.app.ActivityManagerInternal;
Bookatz94726412017-08-31 09:26:15 -070036import android.app.AlarmManager;
Bookatz75158ac2018-05-18 15:55:23 -070037import android.app.AlarmManager.OnAlarmListener;
Martijn Coenencd95d462019-04-25 17:09:45 +020038import android.app.AppOpsManager;
39import android.app.AppOpsManager.HistoricalOps;
40import android.app.AppOpsManager.HistoricalOpsRequest;
41import android.app.AppOpsManager.HistoricalPackageOps;
42import android.app.AppOpsManager.HistoricalUidOps;
Rajeev Kumar22d92b72018-02-07 18:38:36 -080043import android.app.ProcessMemoryState;
Bookatzc6977972018-01-16 16:55:05 -080044import android.app.StatsManager;
Chenjie Yu9d7720b2018-01-24 10:34:48 -080045import android.bluetooth.BluetoothActivityEnergyInfo;
46import android.bluetooth.BluetoothAdapter;
47import android.bluetooth.UidTraffic;
Bookatz94726412017-08-31 09:26:15 -070048import android.content.BroadcastReceiver;
49import android.content.Context;
50import android.content.Intent;
David Chende701692017-10-05 13:16:02 -070051import android.content.IntentFilter;
Bookatzc6977972018-01-16 16:55:05 -080052import android.content.IntentSender;
Carmen Agimofa769c152019-03-04 14:39:14 +000053import android.content.pm.ApplicationInfo;
David Chende701692017-10-05 13:16:02 -070054import android.content.pm.PackageInfo;
55import android.content.pm.PackageManager;
Philip P. Moltmannf21a3502019-01-30 09:53:04 -080056import android.content.pm.PermissionInfo;
David Chende701692017-10-05 13:16:02 -070057import android.content.pm.UserInfo;
Kevin Chyn6ecc5702019-01-28 12:00:37 -080058import android.hardware.biometrics.BiometricsProtoEnums;
59import android.hardware.face.FaceManager;
Tej Singhd6d6d772018-09-05 17:41:25 -070060import android.hardware.fingerprint.FingerprintManager;
Chenjie Yuae9dfac2018-10-25 16:06:56 -070061import android.net.ConnectivityManager;
Chenbo Fenge62e2872019-01-11 15:50:17 -080062import android.net.INetworkStatsService;
Chenjie Yuae9dfac2018-10-25 16:06:56 -070063import android.net.Network;
64import android.net.NetworkRequest;
David Chenc8a43242017-10-17 16:23:28 -070065import android.net.NetworkStats;
Chenjie Yu05013b32017-11-21 10:21:41 -080066import android.net.wifi.IWifiManager;
67import android.net.wifi.WifiActivityEnergyInfo;
Bookatz75ee6042018-11-09 12:27:37 -080068import android.os.BatteryStats;
David Chenc8a43242017-10-17 16:23:28 -070069import android.os.BatteryStatsInternal;
Bookatz94726412017-08-31 09:26:15 -070070import android.os.Binder;
Bookatz366a4432018-11-20 09:42:33 -080071import android.os.Build;
David Chende701692017-10-05 13:16:02 -070072import android.os.Bundle;
Maggie White442b6312019-04-05 16:26:44 -070073import android.os.CoolingDevice;
Chenjie Yu937d7422018-01-10 16:37:53 -080074import android.os.Environment;
yroe26c97b2018-03-27 10:30:11 -070075import android.os.FileUtils;
Olivier Gaillard21fb5232018-10-09 13:19:27 +010076import android.os.Handler;
77import android.os.HandlerThread;
Bookatzb487b552017-09-18 11:26:01 -070078import android.os.IBinder;
Bookatz94726412017-08-31 09:26:15 -070079import android.os.IStatsCompanionService;
80import android.os.IStatsManager;
Tej Singh86dc9db2018-09-06 00:39:57 +000081import android.os.IStoraged;
Yangster-mace16189a2018-08-26 12:20:16 -070082import android.os.IThermalEventListener;
83import android.os.IThermalService;
Olivier Gaillard21fb5232018-10-09 13:19:27 +010084import android.os.Looper;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -070085import android.os.ParcelFileDescriptor;
Chenjie Yu05013b32017-11-21 10:21:41 -080086import android.os.Parcelable;
Bookatz94726412017-08-31 09:26:15 -070087import android.os.Process;
Bookatz1b0b1142017-09-08 11:58:42 -070088import android.os.RemoteException;
Bookatz94726412017-08-31 09:26:15 -070089import android.os.ServiceManager;
Chenjie Yu937d7422018-01-10 16:37:53 -080090import android.os.StatFs;
Chenjie Yu9d7720b2018-01-24 10:34:48 -080091import android.os.StatsDimensionsValue;
David Chen1481fe12017-10-16 13:16:34 -070092import android.os.StatsLogEventWrapper;
Chenjie Yu05013b32017-11-21 10:21:41 -080093import android.os.SynchronousResultReceiver;
Chenjie Yu937d7422018-01-10 16:37:53 -080094import android.os.SystemClock;
Rafal Slawik44b88142018-12-15 16:48:09 +000095import android.os.SystemProperties;
Yangster-mace16189a2018-08-26 12:20:16 -070096import android.os.Temperature;
David Chende701692017-10-05 13:16:02 -070097import android.os.UserHandle;
98import android.os.UserManager;
Carmen Agimof35f7f6f2019-02-05 18:19:21 +000099import android.os.storage.DiskInfo;
Tej Singh86dc9db2018-09-06 00:39:57 +0000100import android.os.storage.StorageManager;
Carmen Agimof35f7f6f2019-02-05 18:19:21 +0000101import android.os.storage.VolumeInfo;
joshmccloskey34c1f8e2019-04-11 14:06:43 -0700102import android.provider.Settings;
Carmen Agimof12dec122019-03-06 16:14:38 +0000103import android.stats.storage.StorageEnums;
Chenjie Yu937d7422018-01-10 16:37:53 -0800104import android.telephony.ModemActivityInfo;
105import android.telephony.TelephonyManager;
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +0100106import android.util.ArrayMap;
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -0800107import android.util.ArraySet;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700108import android.util.Log;
Bookatz94726412017-08-31 09:26:15 -0700109import android.util.Slog;
David Chenc8a43242017-10-17 16:23:28 -0700110import android.util.StatsLog;
Chenjie Yuab530202018-09-26 12:39:20 -0700111import android.util.proto.ProtoOutputStream;
Max Dashouk11e0d402019-05-16 16:58:07 -0700112import android.util.proto.ProtoStream;
David Chenc8a43242017-10-17 16:23:28 -0700113
114import com.android.internal.annotations.GuardedBy;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700115import com.android.internal.app.procstats.IProcessStats;
116import com.android.internal.app.procstats.ProcessStats;
Max Dashouk11e0d402019-05-16 16:58:07 -0700117import com.android.internal.os.BackgroundThread;
Bookatz75ee6042018-11-09 12:27:37 -0800118import com.android.internal.os.BatterySipper;
119import com.android.internal.os.BatteryStatsHelper;
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +0100120import com.android.internal.os.BinderCallsStats.ExportedCallStat;
Chenjie Yu937d7422018-01-10 16:37:53 -0800121import com.android.internal.os.KernelCpuSpeedReader;
Misha Wagner5a51e002018-10-03 15:04:09 +0100122import com.android.internal.os.KernelCpuThreadReader;
Misha Wagner2487d3572019-03-18 17:30:14 +0000123import com.android.internal.os.KernelCpuThreadReaderDiff;
Misha Wagner4b32c9f2019-01-25 15:30:14 +0000124import com.android.internal.os.KernelCpuThreadReaderSettingsObserver;
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800125import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidActiveTimeReader;
126import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidClusterTimeReader;
127import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidFreqTimeReader;
128import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidUserSysTimeReader;
David Chenc8a43242017-10-17 16:23:28 -0700129import com.android.internal.os.KernelWakelockReader;
130import com.android.internal.os.KernelWakelockStats;
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +0100131import com.android.internal.os.LooperStats;
Chenjie Yu7f8def92017-11-03 09:33:15 -0700132import com.android.internal.os.PowerProfile;
Yangster-mac308ea0c2018-10-22 13:10:25 -0700133import com.android.internal.os.ProcessCpuTracker;
Tej Singhe7726dc2018-09-21 11:42:12 -0700134import com.android.internal.os.StoragedUidIoStatsReader;
yroe26c97b2018-03-27 10:30:11 -0700135import com.android.internal.util.DumpUtils;
Olivier Gaillard289ba402018-07-24 18:50:13 +0100136import com.android.server.BinderCallsStatsService;
David Chenc8a43242017-10-17 16:23:28 -0700137import com.android.server.LocalServices;
138import com.android.server.SystemService;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700139import com.android.server.SystemServiceManager;
Rafal Slawikc3762622018-11-07 12:07:26 +0000140import com.android.server.am.MemoryStatUtil.MemoryStat;
Hai Zhang85fd0622019-02-01 14:06:04 -0800141import com.android.server.role.RoleManagerInternal;
Rafal Slawik23628e02019-09-11 15:52:09 +0100142import com.android.server.stats.IonMemoryUtil.IonAllocations;
Rafal Slawik7efcefb2019-09-20 11:16:20 +0100143import com.android.server.stats.ProcfsMemoryUtil.MemorySnapshot;
Tej Singh86dc9db2018-09-06 00:39:57 +0000144import com.android.server.storage.DiskStatsFileLogger;
145import com.android.server.storage.DiskStatsLoggingService;
146
147import libcore.io.IoUtils;
148
149import org.json.JSONArray;
150import org.json.JSONException;
151import org.json.JSONObject;
Bookatz94726412017-08-31 09:26:15 -0700152
yroe26c97b2018-03-27 10:30:11 -0700153import java.io.File;
154import java.io.FileDescriptor;
Tej Singh86dc9db2018-09-06 00:39:57 +0000155import java.io.FileOutputStream;
156import java.io.IOException;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700157import java.io.InputStream;
yroe26c97b2018-03-27 10:30:11 -0700158import java.io.PrintWriter;
David Chende701692017-10-05 13:16:02 -0700159import java.util.ArrayList;
Bookatz058d8692018-03-06 09:53:47 -0800160import java.util.Arrays;
yroe26c97b2018-03-27 10:30:11 -0700161import java.util.HashMap;
162import java.util.HashSet;
David Chende701692017-10-05 13:16:02 -0700163import java.util.List;
Bookatzc68a9d22017-09-27 14:09:55 -0700164import java.util.Map;
Olivier Gaillard6f52d152018-07-25 12:13:12 +0100165import java.util.Map.Entry;
Carmen Agimofa769c152019-03-04 14:39:14 +0000166import java.util.UUID;
Martijn Coenencd95d462019-04-25 17:09:45 +0200167import java.util.concurrent.CompletableFuture;
yroe26c97b2018-03-27 10:30:11 -0700168import java.util.concurrent.TimeUnit;
Chenjie Yu05013b32017-11-21 10:21:41 -0800169import java.util.concurrent.TimeoutException;
Bookatzc68a9d22017-09-27 14:09:55 -0700170
Bookatz94726412017-08-31 09:26:15 -0700171/**
172 * Helper service for statsd (the native stats management service in cmds/statsd/).
173 * Used for registering and receiving alarms on behalf of statsd.
David Chen1481fe12017-10-16 13:16:34 -0700174 *
Bookatz6bc51d72017-09-28 16:43:40 -0700175 * @hide
Bookatz94726412017-08-31 09:26:15 -0700176 */
177public class StatsCompanionService extends IStatsCompanionService.Stub {
Chenjie Yu05013b32017-11-21 10:21:41 -0800178 /**
179 * How long to wait on an individual subsystem to return its stats.
180 */
181 private static final long EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS = 2000;
yroe26c97b2018-03-27 10:30:11 -0700182 private static final long MILLIS_IN_A_DAY = TimeUnit.DAYS.toMillis(1);
Chenjie Yu05013b32017-11-21 10:21:41 -0800183
184 public static final String RESULT_RECEIVER_CONTROLLER_KEY = "controller_activity";
yroe26c97b2018-03-27 10:30:11 -0700185 public static final String CONFIG_DIR = "/data/misc/stats-service";
Chenjie Yu05013b32017-11-21 10:21:41 -0800186
Bookatz94726412017-08-31 09:26:15 -0700187 static final String TAG = "StatsCompanionService";
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700188 static final boolean DEBUG = false;
Max Dashouk11e0d402019-05-16 16:58:07 -0700189 /**
190 * Hard coded field ids of frameworks/base/cmds/statsd/src/uid_data.proto
191 * to be used in ProtoOutputStream.
192 */
193 private static final int APPLICATION_INFO_FIELD_ID = 1;
194 private static final int UID_FIELD_ID = 1;
195 private static final int VERSION_FIELD_ID = 2;
196 private static final int VERSION_STRING_FIELD_ID = 3;
197 private static final int PACKAGE_NAME_FIELD_ID = 4;
198 private static final int INSTALLER_FIELD_ID = 5;
Bookatzc6977972018-01-16 16:55:05 -0800199
David Chen661f7912018-01-22 17:46:24 -0800200 public static final int CODE_DATA_BROADCAST = 1;
Bookatzc6977972018-01-16 16:55:05 -0800201 public static final int CODE_SUBSCRIBER_BROADCAST = 1;
Tej Singh6ede28b2019-01-29 17:06:54 -0800202 public static final int CODE_ACTIVE_CONFIGS_BROADCAST = 1;
David Chend37bc232018-04-12 18:05:11 -0700203 /**
204 * The last report time is provided with each intent registered to
205 * StatsManager#setFetchReportsOperation. This allows easy de-duping in the receiver if
206 * statsd is requesting the client to retrieve the same statsd data. The last report time
207 * corresponds to the last_report_elapsed_nanos that will provided in the current
208 * ConfigMetricsReport, and this timestamp also corresponds to the
209 * current_report_elapsed_nanos of the most recently obtained ConfigMetricsReport.
210 */
211 public static final String EXTRA_LAST_REPORT_TIME = "android.app.extra.LAST_REPORT_TIME";
yroe26c97b2018-03-27 10:30:11 -0700212 public static final int DEATH_THRESHOLD = 10;
Rafal Slawik3bea8952018-11-15 12:39:33 +0000213 /**
214 * Which native processes to snapshot memory for.
215 *
216 * <p>Processes are matched by their cmdline in procfs. Example: cat /proc/pid/cmdline returns
217 * /system/bin/statsd for the stats daemon.
218 */
219 private static final String[] MEMORY_INTERESTING_NATIVE_PROCESSES = new String[]{
220 "/system/bin/statsd", // Stats daemon.
221 "/system/bin/surfaceflinger",
222 "/system/bin/apexd", // APEX daemon.
223 "/system/bin/audioserver",
224 "/system/bin/cameraserver",
225 "/system/bin/drmserver",
226 "/system/bin/healthd",
227 "/system/bin/incidentd",
228 "/system/bin/installd",
229 "/system/bin/lmkd", // Low memory killer daemon.
230 "/system/bin/logd",
231 "media.codec",
232 "media.extractor",
233 "media.metrics",
234 "/system/bin/mediadrmserver",
235 "/system/bin/mediaserver",
236 "/system/bin/performanced",
237 "/system/bin/tombstoned",
238 "/system/bin/traced", // Perfetto.
239 "/system/bin/traced_probes", // Perfetto.
240 "webview_zygote",
Rafal Slawik932c71e2018-11-30 16:10:32 +0000241 "zygote",
242 "zygote64",
Rafal Slawik3bea8952018-11-15 12:39:33 +0000243 };
Rafal Slawik21d3f512019-09-24 20:00:18 +0100244 /**
245 * Lowest available uid for apps.
246 *
247 * <p>Used to quickly discard memory snapshots of the zygote forks from native process
248 * measurements.
249 */
250 private static final int MIN_APP_UID = 10_000;
Bookatzc6977972018-01-16 16:55:05 -0800251
Misha Wagner4b32c9f2019-01-25 15:30:14 +0000252 private static final int CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES = 8;
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100253
254 static final class CompanionHandler extends Handler {
255 CompanionHandler(Looper looper) {
256 super(looper);
257 }
258 }
259
Bookatz94726412017-08-31 09:26:15 -0700260 private final Context mContext;
261 private final AlarmManager mAlarmManager;
Chenbo Fenge62e2872019-01-11 15:50:17 -0800262 private final INetworkStatsService mNetworkStatsService;
Bookatzb487b552017-09-18 11:26:01 -0700263 @GuardedBy("sStatsdLock")
Bookatz1b0b1142017-09-08 11:58:42 -0700264 private static IStatsManager sStatsd;
Bookatzb487b552017-09-18 11:26:01 -0700265 private static final Object sStatsdLock = new Object();
Bookatz94726412017-08-31 09:26:15 -0700266
Bookatz75158ac2018-05-18 15:55:23 -0700267 private final OnAlarmListener mAnomalyAlarmListener = new AnomalyAlarmListener();
268 private final OnAlarmListener mPullingAlarmListener = new PullingAlarmListener();
269 private final OnAlarmListener mPeriodicAlarmListener = new PeriodicAlarmListener();
David Chende701692017-10-05 13:16:02 -0700270 private final BroadcastReceiver mAppUpdateReceiver;
David Chen47e8f4d2017-10-11 15:34:13 -0700271 private final BroadcastReceiver mUserUpdateReceiver;
yro947fbce2017-11-15 22:50:23 -0800272 private final ShutdownEventReceiver mShutdownEventReceiver;
Chenjie Yu7f8def92017-11-03 09:33:15 -0700273 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
274 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
Chenjie Yu05013b32017-11-21 10:21:41 -0800275 private IWifiManager mWifiManager = null;
276 private TelephonyManager mTelephony = null;
yroe26c97b2018-03-27 10:30:11 -0700277 @GuardedBy("sStatsdLock")
278 private final HashSet<Long> mDeathTimeMillis = new HashSet<>();
279 @GuardedBy("sStatsdLock")
280 private final HashMap<Long, String> mDeletedFiles = new HashMap<>();
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100281 private final CompanionHandler mHandler;
Bookatz94726412017-08-31 09:26:15 -0700282
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800283 // Disables throttler on CPU time readers.
284 private KernelCpuUidUserSysTimeReader mCpuUidUserSysTimeReader =
285 new KernelCpuUidUserSysTimeReader(false);
Chenjie Yuec676612018-03-07 09:19:17 -0800286 private KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800287 private KernelCpuUidFreqTimeReader mCpuUidFreqTimeReader =
288 new KernelCpuUidFreqTimeReader(false);
289 private KernelCpuUidActiveTimeReader mCpuUidActiveTimeReader =
290 new KernelCpuUidActiveTimeReader(false);
291 private KernelCpuUidClusterTimeReader mCpuUidClusterTimeReader =
292 new KernelCpuUidClusterTimeReader(false);
Tej Singhe7726dc2018-09-21 11:42:12 -0700293 private StoragedUidIoStatsReader mStoragedUidIoStatsReader =
294 new StoragedUidIoStatsReader();
Misha Wagner5a51e002018-10-03 15:04:09 +0100295 @Nullable
Misha Wagner2487d3572019-03-18 17:30:14 +0000296 private final KernelCpuThreadReaderDiff mKernelCpuThreadReader;
Chenjie Yuec676612018-03-07 09:19:17 -0800297
Olivier Gaillard18d452202019-01-22 15:03:41 +0000298 private long mDebugElapsedClockPreviousValue = 0;
299 private long mDebugElapsedClockPullCount = 0;
300 private long mDebugFailingElapsedClockPreviousValue = 0;
301 private long mDebugFailingElapsedClockPullCount = 0;
Bookatz75ee6042018-11-09 12:27:37 -0800302 private BatteryStatsHelper mBatteryStatsHelper = null;
303 private static final int MAX_BATTERY_STATS_HELPER_FREQUENCY_MS = 1000;
304 private long mBatteryStatsHelperTimestampMs = -MAX_BATTERY_STATS_HELPER_FREQUENCY_MS;
305
Yangster-mace16189a2018-08-26 12:20:16 -0700306 private static IThermalService sThermalService;
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700307 private File mBaseDir =
308 new File(SystemServiceManager.ensureSystemDir(), "stats_companion");
Yangster-mac308ea0c2018-10-22 13:10:25 -0700309 @GuardedBy("this")
310 ProcessCpuTracker mProcessCpuTracker = null;
Yangster-mace16189a2018-08-26 12:20:16 -0700311
Bookatz94726412017-08-31 09:26:15 -0700312 public StatsCompanionService(Context context) {
313 super();
314 mContext = context;
315 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800316 mNetworkStatsService = INetworkStatsService.Stub.asInterface(
317 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
Chenjie Yu2c0d83d2018-09-02 06:37:08 -0700318 mBaseDir.mkdirs();
David Chende701692017-10-05 13:16:02 -0700319 mAppUpdateReceiver = new AppUpdateReceiver();
David Chen47e8f4d2017-10-11 15:34:13 -0700320 mUserUpdateReceiver = new BroadcastReceiver() {
321 @Override
322 public void onReceive(Context context, Intent intent) {
323 synchronized (sStatsdLock) {
324 sStatsd = fetchStatsdService();
325 if (sStatsd == null) {
Bookatz111ed732018-02-16 15:54:05 -0800326 Slog.w(TAG, "Could not access statsd for UserUpdateReceiver");
David Chen47e8f4d2017-10-11 15:34:13 -0700327 return;
328 }
329 try {
330 // Pull the latest state of UID->app name, version mapping.
331 // Needed since the new user basically has a version of every app.
332 informAllUidsLocked(context);
333 } catch (RemoteException e) {
David Chen1481fe12017-10-16 13:16:34 -0700334 Slog.e(TAG, "Failed to inform statsd latest update of all apps", e);
yroe26c97b2018-03-27 10:30:11 -0700335 forgetEverythingLocked();
David Chen47e8f4d2017-10-11 15:34:13 -0700336 }
337 }
338 }
339 };
yro947fbce2017-11-15 22:50:23 -0800340 mShutdownEventReceiver = new ShutdownEventReceiver();
Bookatz111ed732018-02-16 15:54:05 -0800341 if (DEBUG) Slog.d(TAG, "Registered receiver for ACTION_PACKAGE_REPLACED and ADDED.");
Chenjie Yu7f8def92017-11-03 09:33:15 -0700342 PowerProfile powerProfile = new PowerProfile(context);
343 final int numClusters = powerProfile.getNumCpuClusters();
344 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
345 int firstCpuOfCluster = 0;
346 for (int i = 0; i < numClusters; i++) {
347 final int numSpeedSteps = powerProfile.getNumSpeedStepsInCpuCluster(i);
348 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
David Chen661f7912018-01-22 17:46:24 -0800349 numSpeedSteps);
Chenjie Yu7f8def92017-11-03 09:33:15 -0700350 firstCpuOfCluster += powerProfile.getNumCoresInCpuCluster(i);
351 }
Yangster-mace16189a2018-08-26 12:20:16 -0700352
353 // Enable push notifications of throttling from vendor thermal
354 // management subsystem via thermalservice.
355 IBinder b = ServiceManager.getService("thermalservice");
356
357 if (b != null) {
358 sThermalService = IThermalService.Stub.asInterface(b);
359 try {
Wei Wangbdaf46e2019-05-16 16:59:53 -0700360 sThermalService.registerThermalEventListener(
361 new ThermalEventListener());
Yangster-mace16189a2018-08-26 12:20:16 -0700362 Slog.i(TAG, "register thermal listener successfully");
363 } catch (RemoteException e) {
364 // Should never happen.
365 Slog.e(TAG, "register thermal listener error");
366 }
367 } else {
368 Slog.e(TAG, "cannot find thermalservice, no throttling push notifications");
369 }
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100370
Chenjie Yuae9dfac2018-10-25 16:06:56 -0700371 // Default NetworkRequest should cover all transport types.
372 final NetworkRequest request = new NetworkRequest.Builder().build();
373 final ConnectivityManager connectivityManager =
374 (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
375 connectivityManager.registerNetworkCallback(request, new ConnectivityStatsCallback());
376
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100377 HandlerThread handlerThread = new HandlerThread(TAG);
378 handlerThread.start();
379 mHandler = new CompanionHandler(handlerThread.getLooper());
380
Misha Wagner4b32c9f2019-01-25 15:30:14 +0000381 mKernelCpuThreadReader =
382 KernelCpuThreadReaderSettingsObserver.getSettingsModifiedReader(mContext);
Bookatz94726412017-08-31 09:26:15 -0700383 }
384
David Chenadaf8b32017-11-03 15:42:08 -0700385 @Override
David Chend37bc232018-04-12 18:05:11 -0700386 public void sendDataBroadcast(IBinder intentSenderBinder, long lastReportTimeNs) {
Bookatz36920822018-01-26 09:18:07 -0800387 enforceCallingPermission();
David Chen661f7912018-01-22 17:46:24 -0800388 IntentSender intentSender = new IntentSender(intentSenderBinder);
389 Intent intent = new Intent();
David Chend37bc232018-04-12 18:05:11 -0700390 intent.putExtra(EXTRA_LAST_REPORT_TIME, lastReportTimeNs);
David Chen661f7912018-01-22 17:46:24 -0800391 try {
392 intentSender.sendIntent(mContext, CODE_DATA_BROADCAST, intent, null, null);
393 } catch (IntentSender.SendIntentException e) {
394 Slog.w(TAG, "Unable to send using IntentSender");
395 }
David Chenadaf8b32017-11-03 15:42:08 -0700396 }
397
Bookatzc6977972018-01-16 16:55:05 -0800398 @Override
Tej Singh6ede28b2019-01-29 17:06:54 -0800399 public void sendActiveConfigsChangedBroadcast(IBinder intentSenderBinder, long[] configIds) {
400 enforceCallingPermission();
401 IntentSender intentSender = new IntentSender(intentSenderBinder);
402 Intent intent = new Intent();
403 intent.putExtra(StatsManager.EXTRA_STATS_ACTIVE_CONFIG_KEYS, configIds);
404 try {
405 intentSender.sendIntent(mContext, CODE_ACTIVE_CONFIGS_BROADCAST, intent, null, null);
406 if (DEBUG) {
407 Slog.d(TAG, "Sent broadcast with config ids " + Arrays.toString(configIds));
408 }
409 } catch (IntentSender.SendIntentException e) {
410 Slog.w(TAG, "Unable to send active configs changed broadcast using IntentSender");
411 }
412 }
413
414 @Override
Bookatzc6977972018-01-16 16:55:05 -0800415 public void sendSubscriberBroadcast(IBinder intentSenderBinder, long configUid, long configKey,
Chenjie Yu12e5e672018-09-14 15:54:59 -0700416 long subscriptionId, long subscriptionRuleId, String[] cookies,
417 StatsDimensionsValue dimensionsValue) {
Bookatzc6977972018-01-16 16:55:05 -0800418 enforceCallingPermission();
419 IntentSender intentSender = new IntentSender(intentSenderBinder);
Chenjie Yu12e5e672018-09-14 15:54:59 -0700420 Intent intent =
421 new Intent()
422 .putExtra(StatsManager.EXTRA_STATS_CONFIG_UID, configUid)
423 .putExtra(StatsManager.EXTRA_STATS_CONFIG_KEY, configKey)
424 .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_ID, subscriptionId)
425 .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_RULE_ID, subscriptionRuleId)
426 .putExtra(StatsManager.EXTRA_STATS_DIMENSIONS_VALUE, dimensionsValue);
Bookatz058d8692018-03-06 09:53:47 -0800427
428 ArrayList<String> cookieList = new ArrayList<>(cookies.length);
Chenjie Yu12e5e672018-09-14 15:54:59 -0700429 for (String cookie : cookies) {
430 cookieList.add(cookie);
431 }
Bookatz058d8692018-03-06 09:53:47 -0800432 intent.putStringArrayListExtra(
433 StatsManager.EXTRA_STATS_BROADCAST_SUBSCRIBER_COOKIES, cookieList);
434
Bookatz1476ef22018-02-13 12:26:01 -0800435 if (DEBUG) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700436 Slog.d(TAG,
437 String.format("Statsd sendSubscriberBroadcast with params {%d %d %d %d %s %s}",
438 configUid, configKey, subscriptionId, subscriptionRuleId,
439 Arrays.toString(cookies),
440 dimensionsValue));
Bookatz1476ef22018-02-13 12:26:01 -0800441 }
Bookatzc6977972018-01-16 16:55:05 -0800442 try {
443 intentSender.sendIntent(mContext, CODE_SUBSCRIBER_BROADCAST, intent, null, null);
444 } catch (IntentSender.SendIntentException e) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700445 Slog.w(TAG,
446 "Unable to send using IntentSender from uid " + configUid
447 + "; presumably it had been cancelled.");
Bookatzc6977972018-01-16 16:55:05 -0800448 }
449 }
450
David Chen1481fe12017-10-16 13:16:34 -0700451 private final static int[] toIntArray(List<Integer> list) {
David Chende701692017-10-05 13:16:02 -0700452 int[] ret = new int[list.size()];
David Chen1481fe12017-10-16 13:16:34 -0700453 for (int i = 0; i < ret.length; i++) {
David Chende701692017-10-05 13:16:02 -0700454 ret[i] = list.get(i);
455 }
456 return ret;
457 }
458
Dianne Hackborn3accca02013-09-20 09:32:11 -0700459 private final static long[] toLongArray(List<Long> list) {
460 long[] ret = new long[list.size()];
461 for (int i = 0; i < ret.length; i++) {
462 ret[i] = list.get(i);
463 }
464 return ret;
465 }
466
David Chende701692017-10-05 13:16:02 -0700467 // Assumes that sStatsdLock is held.
Andreas Gampea36dc622018-02-05 17:19:22 -0800468 @GuardedBy("sStatsdLock")
David Chende701692017-10-05 13:16:02 -0700469 private final void informAllUidsLocked(Context context) throws RemoteException {
470 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
471 PackageManager pm = context.getPackageManager();
472 final List<UserInfo> users = um.getUsers(true);
473 if (DEBUG) {
Bookatz111ed732018-02-16 15:54:05 -0800474 Slog.d(TAG, "Iterating over " + users.size() + " profiles.");
David Chende701692017-10-05 13:16:02 -0700475 }
476
Max Dashouk11e0d402019-05-16 16:58:07 -0700477 ParcelFileDescriptor[] fds;
478 try {
479 fds = ParcelFileDescriptor.createPipe();
480 } catch (IOException e) {
481 Slog.e(TAG, "Failed to create a pipe to send uid map data.", e);
482 return;
483 }
484 sStatsd.informAllUidData(fds[0]);
485 try {
486 fds[0].close();
487 } catch (IOException e) {
488 Slog.e(TAG, "Failed to close the read side of the pipe.", e);
489 }
490 final ParcelFileDescriptor writeFd = fds[1];
491 BackgroundThread.getHandler().post(() -> {
492 FileOutputStream fout = new ParcelFileDescriptor.AutoCloseOutputStream(writeFd);
493 try {
494 ProtoOutputStream output = new ProtoOutputStream(fout);
495 int numRecords = 0;
496 // Add in all the apps for every user/profile.
497 for (UserInfo profile : users) {
498 List<PackageInfo> pi =
Tej Singh74d943e2019-05-29 21:12:11 +0000499 pm.getInstalledPackagesAsUser(PackageManager.MATCH_KNOWN_PACKAGES,
Max Dashouk11e0d402019-05-16 16:58:07 -0700500 profile.id);
501 for (int j = 0; j < pi.size(); j++) {
502 if (pi.get(j).applicationInfo != null) {
503 String installer;
504 try {
505 installer = pm.getInstallerPackageName(pi.get(j).packageName);
506 } catch (IllegalArgumentException e) {
507 installer = "";
508 }
509 long applicationInfoToken =
510 output.start(ProtoStream.FIELD_TYPE_MESSAGE
511 | ProtoStream.FIELD_COUNT_REPEATED
512 | APPLICATION_INFO_FIELD_ID);
513 output.write(ProtoStream.FIELD_TYPE_INT32
514 | ProtoStream.FIELD_COUNT_SINGLE | UID_FIELD_ID,
515 pi.get(j).applicationInfo.uid);
516 output.write(ProtoStream.FIELD_TYPE_INT64
517 | ProtoStream.FIELD_COUNT_SINGLE
518 | VERSION_FIELD_ID, pi.get(j).getLongVersionCode());
519 output.write(ProtoStream.FIELD_TYPE_STRING
520 | ProtoStream.FIELD_COUNT_SINGLE | VERSION_STRING_FIELD_ID,
521 pi.get(j).versionName);
522 output.write(ProtoStream.FIELD_TYPE_STRING
523 | ProtoStream.FIELD_COUNT_SINGLE
524 | PACKAGE_NAME_FIELD_ID, pi.get(j).packageName);
525 output.write(ProtoStream.FIELD_TYPE_STRING
526 | ProtoStream.FIELD_COUNT_SINGLE
527 | INSTALLER_FIELD_ID,
528 installer == null ? "" : installer);
529 numRecords++;
530 output.end(applicationInfoToken);
531 }
dwchen730403e2018-10-29 11:41:56 -0700532 }
David Chen1481fe12017-10-16 13:16:34 -0700533 }
Max Dashouk11e0d402019-05-16 16:58:07 -0700534 output.flush();
535 if (DEBUG) {
536 Slog.d(TAG, "Sent data for " + numRecords + " apps");
537 }
538 } finally {
539 IoUtils.closeQuietly(fout);
David Chen1481fe12017-10-16 13:16:34 -0700540 }
Max Dashouk11e0d402019-05-16 16:58:07 -0700541 });
David Chende701692017-10-05 13:16:02 -0700542 }
543
Bookatz36920822018-01-26 09:18:07 -0800544 private final static class AppUpdateReceiver extends BroadcastReceiver {
David Chende701692017-10-05 13:16:02 -0700545 @Override
546 public void onReceive(Context context, Intent intent) {
David Chen47e8f4d2017-10-11 15:34:13 -0700547 /**
548 * App updates actually consist of REMOVE, ADD, and then REPLACE broadcasts. To avoid
549 * waste, we ignore the REMOVE and ADD broadcasts that contain the replacing flag.
David Chend6896892017-10-25 11:49:03 -0700550 * If we can't find the value for EXTRA_REPLACING, we default to false.
David Chen47e8f4d2017-10-11 15:34:13 -0700551 */
David Chend6896892017-10-25 11:49:03 -0700552 if (!intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)
553 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
David Chen47e8f4d2017-10-11 15:34:13 -0700554 return; // Keep only replacing or normal add and remove.
555 }
Tej Singh90d3aa02018-03-08 19:07:58 -0800556 if (DEBUG) Slog.d(TAG, "StatsCompanionService noticed an app was updated.");
David Chende701692017-10-05 13:16:02 -0700557 synchronized (sStatsdLock) {
558 if (sStatsd == null) {
yrof6d1ca52017-11-15 15:38:34 -0800559 Slog.w(TAG, "Could not access statsd to inform it of an app update");
David Chende701692017-10-05 13:16:02 -0700560 return;
561 }
562 try {
563 if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
564 Bundle b = intent.getExtras();
565 int uid = b.getInt(Intent.EXTRA_UID);
566 boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
567 if (!replacing) {
568 // Don't bother sending an update if we're right about to get another
569 // intent for the new version that's added.
570 PackageManager pm = context.getPackageManager();
571 String app = intent.getData().getSchemeSpecificPart();
572 sStatsd.informOnePackageRemoved(app, uid);
573 }
574 } else {
575 PackageManager pm = context.getPackageManager();
576 Bundle b = intent.getExtras();
577 int uid = b.getInt(Intent.EXTRA_UID);
578 String app = intent.getData().getSchemeSpecificPart();
579 PackageInfo pi = pm.getPackageInfo(app, PackageManager.MATCH_ANY_USER);
dwchen730403e2018-10-29 11:41:56 -0700580 String installer;
581 try {
582 installer = pm.getInstallerPackageName(app);
583 } catch (IllegalArgumentException e) {
584 installer = "";
585 }
Tony Mak535c48f2019-11-04 13:01:11 +0000586 sStatsd.informOnePackage(
587 app,
588 uid,
589 pi.getLongVersionCode(),
590 pi.versionName == null ? "" : pi.versionName,
dwchen730403e2018-10-29 11:41:56 -0700591 installer == null ? "" : installer);
David Chende701692017-10-05 13:16:02 -0700592 }
593 } catch (Exception e) {
594 Slog.w(TAG, "Failed to inform statsd of an app update", e);
595 }
596 }
597 }
David Chen1481fe12017-10-16 13:16:34 -0700598 }
David Chende701692017-10-05 13:16:02 -0700599
Bookatz75158ac2018-05-18 15:55:23 -0700600 public final static class AnomalyAlarmListener implements OnAlarmListener {
Bookatz94726412017-08-31 09:26:15 -0700601 @Override
Bookatz75158ac2018-05-18 15:55:23 -0700602 public void onAlarm() {
Bookatz66fe0612018-02-07 18:51:48 -0800603 Slog.i(TAG, "StatsCompanionService believes an anomaly has occurred at time "
604 + System.currentTimeMillis() + "ms.");
Bookatzb487b552017-09-18 11:26:01 -0700605 synchronized (sStatsdLock) {
606 if (sStatsd == null) {
607 Slog.w(TAG, "Could not access statsd to inform it of anomaly alarm firing");
608 return;
609 }
610 try {
611 // Two-way call to statsd to retain AlarmManager wakelock
612 sStatsd.informAnomalyAlarmFired();
613 } catch (RemoteException e) {
614 Slog.w(TAG, "Failed to inform statsd of anomaly alarm firing", e);
615 }
Bookatz94726412017-08-31 09:26:15 -0700616 }
Bookatzb487b552017-09-18 11:26:01 -0700617 // AlarmManager releases its own wakelock here.
Bookatz94726412017-08-31 09:26:15 -0700618 }
David Chen1481fe12017-10-16 13:16:34 -0700619 }
Bookatzb487b552017-09-18 11:26:01 -0700620
Bookatz75158ac2018-05-18 15:55:23 -0700621 public final static class PullingAlarmListener implements OnAlarmListener {
David Chen661f7912018-01-22 17:46:24 -0800622 @Override
Bookatz75158ac2018-05-18 15:55:23 -0700623 public void onAlarm() {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700624 if (DEBUG) {
David Chen661f7912018-01-22 17:46:24 -0800625 Slog.d(TAG, "Time to poll something.");
Chenjie Yu12e5e672018-09-14 15:54:59 -0700626 }
David Chen661f7912018-01-22 17:46:24 -0800627 synchronized (sStatsdLock) {
628 if (sStatsd == null) {
629 Slog.w(TAG, "Could not access statsd to inform it of pulling alarm firing.");
630 return;
631 }
632 try {
633 // Two-way call to statsd to retain AlarmManager wakelock
634 sStatsd.informPollAlarmFired();
635 } catch (RemoteException e) {
636 Slog.w(TAG, "Failed to inform statsd of pulling alarm firing.", e);
637 }
638 }
Bookatzb487b552017-09-18 11:26:01 -0700639 }
David Chen1481fe12017-10-16 13:16:34 -0700640 }
Bookatz94726412017-08-31 09:26:15 -0700641
Bookatz75158ac2018-05-18 15:55:23 -0700642 public final static class PeriodicAlarmListener implements OnAlarmListener {
Yangster-mac932ecec2018-02-01 10:23:52 -0800643 @Override
Bookatz75158ac2018-05-18 15:55:23 -0700644 public void onAlarm() {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700645 if (DEBUG) {
Yangster-macc04feba2018-04-02 14:37:33 -0700646 Slog.d(TAG, "Time to trigger periodic alarm.");
Chenjie Yu12e5e672018-09-14 15:54:59 -0700647 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800648 synchronized (sStatsdLock) {
649 if (sStatsd == null) {
650 Slog.w(TAG, "Could not access statsd to inform it of periodic alarm firing.");
651 return;
652 }
653 try {
654 // Two-way call to statsd to retain AlarmManager wakelock
655 sStatsd.informAlarmForSubscriberTriggeringFired();
656 } catch (RemoteException e) {
657 Slog.w(TAG, "Failed to inform statsd of periodic alarm firing.", e);
658 }
659 }
660 // AlarmManager releases its own wakelock here.
661 }
662 }
663
664 public final static class ShutdownEventReceiver extends BroadcastReceiver {
yro947fbce2017-11-15 22:50:23 -0800665 @Override
666 public void onReceive(Context context, Intent intent) {
667 /**
668 * Skip immediately if intent is not relevant to device shutdown.
669 */
670 if (!intent.getAction().equals(Intent.ACTION_REBOOT)
David Chen661f7912018-01-22 17:46:24 -0800671 && !(intent.getAction().equals(Intent.ACTION_SHUTDOWN)
672 && (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0)) {
673 return;
yro947fbce2017-11-15 22:50:23 -0800674 }
yrof7a3bcb2018-01-24 17:18:55 -0800675
yro947fbce2017-11-15 22:50:23 -0800676 Slog.i(TAG, "StatsCompanionService noticed a shutdown.");
677 synchronized (sStatsdLock) {
678 if (sStatsd == null) {
679 Slog.w(TAG, "Could not access statsd to inform it of a shutdown event.");
680 return;
681 }
682 try {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700683 sStatsd.informDeviceShutdown();
yro947fbce2017-11-15 22:50:23 -0800684 } catch (Exception e) {
685 Slog.w(TAG, "Failed to inform statsd of a shutdown event.", e);
686 }
687 }
688 }
689 }
690
Bookatz94726412017-08-31 09:26:15 -0700691 @Override // Binder call
692 public void setAnomalyAlarm(long timestampMs) {
693 enforceCallingPermission();
694 if (DEBUG) Slog.d(TAG, "Setting anomaly alarm for " + timestampMs);
695 final long callingToken = Binder.clearCallingIdentity();
696 try {
Yangster-mac330af582018-02-08 15:24:38 -0800697 // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
698 // only fire when it awakens.
Bookatz75158ac2018-05-18 15:55:23 -0700699 // AlarmManager will automatically cancel any previous mAnomalyAlarmListener alarm.
700 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, TAG + ".anomaly",
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100701 mAnomalyAlarmListener, mHandler);
Bookatz94726412017-08-31 09:26:15 -0700702 } finally {
703 Binder.restoreCallingIdentity(callingToken);
704 }
705 }
706
707 @Override // Binder call
708 public void cancelAnomalyAlarm() {
709 enforceCallingPermission();
710 if (DEBUG) Slog.d(TAG, "Cancelling anomaly alarm");
711 final long callingToken = Binder.clearCallingIdentity();
712 try {
Bookatz75158ac2018-05-18 15:55:23 -0700713 mAlarmManager.cancel(mAnomalyAlarmListener);
Bookatz94726412017-08-31 09:26:15 -0700714 } finally {
715 Binder.restoreCallingIdentity(callingToken);
716 }
717 }
718
719 @Override // Binder call
Yangster-mac932ecec2018-02-01 10:23:52 -0800720 public void setAlarmForSubscriberTriggering(long timestampMs) {
721 enforceCallingPermission();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700722 if (DEBUG) {
723 Slog.d(TAG,
724 "Setting periodic alarm in about " + (timestampMs
725 - SystemClock.elapsedRealtime()));
726 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800727 final long callingToken = Binder.clearCallingIdentity();
728 try {
729 // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
730 // only fire when it awakens.
Bookatz75158ac2018-05-18 15:55:23 -0700731 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, TAG + ".periodic",
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100732 mPeriodicAlarmListener, mHandler);
Yangster-mac932ecec2018-02-01 10:23:52 -0800733 } finally {
734 Binder.restoreCallingIdentity(callingToken);
735 }
736 }
737
738 @Override // Binder call
739 public void cancelAlarmForSubscriberTriggering() {
740 enforceCallingPermission();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700741 if (DEBUG) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800742 Slog.d(TAG, "Cancelling periodic alarm");
Chenjie Yu12e5e672018-09-14 15:54:59 -0700743 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800744 final long callingToken = Binder.clearCallingIdentity();
745 try {
Bookatz75158ac2018-05-18 15:55:23 -0700746 mAlarmManager.cancel(mPeriodicAlarmListener);
Yangster-mac932ecec2018-02-01 10:23:52 -0800747 } finally {
748 Binder.restoreCallingIdentity(callingToken);
749 }
750 }
751
752 @Override // Binder call
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700753 public void setPullingAlarm(long nextPullTimeMs) {
Bookatz75158ac2018-05-18 15:55:23 -0700754 enforceCallingPermission();
755 if (DEBUG) {
756 Slog.d(TAG, "Setting pulling alarm in about "
757 + (nextPullTimeMs - SystemClock.elapsedRealtime()));
758 }
759 final long callingToken = Binder.clearCallingIdentity();
760 try {
761 // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
762 // only fire when it awakens.
763 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, nextPullTimeMs, TAG + ".pull",
Olivier Gaillard21fb5232018-10-09 13:19:27 +0100764 mPullingAlarmListener, mHandler);
Bookatz75158ac2018-05-18 15:55:23 -0700765 } finally {
766 Binder.restoreCallingIdentity(callingToken);
767 }
Bookatz94726412017-08-31 09:26:15 -0700768 }
769
770 @Override // Binder call
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700771 public void cancelPullingAlarm() {
Bookatz75158ac2018-05-18 15:55:23 -0700772 enforceCallingPermission();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700773 if (DEBUG) {
Bookatz75158ac2018-05-18 15:55:23 -0700774 Slog.d(TAG, "Cancelling pulling alarm");
Chenjie Yu12e5e672018-09-14 15:54:59 -0700775 }
Bookatz75158ac2018-05-18 15:55:23 -0700776 final long callingToken = Binder.clearCallingIdentity();
777 try {
778 mAlarmManager.cancel(mPullingAlarmListener);
779 } finally {
780 Binder.restoreCallingIdentity(callingToken);
781 }
Bookatz94726412017-08-31 09:26:15 -0700782 }
783
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800784 private void addNetworkStats(
David Chen661f7912018-01-22 17:46:24 -0800785 int tag, List<StatsLogEventWrapper> ret, NetworkStats stats, boolean withFGBG) {
786 int size = stats.size();
Yangster-macc552b352018-02-22 10:00:45 -0800787 long elapsedNanos = SystemClock.elapsedRealtimeNanos();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700788 long wallClockNanos = SystemClock.currentTimeMicro() * 1000L;
David Chen661f7912018-01-22 17:46:24 -0800789 NetworkStats.Entry entry = new NetworkStats.Entry(); // For recycling
790 for (int j = 0; j < size; j++) {
791 stats.getValues(j, entry);
Chenjie Yu12e5e672018-09-14 15:54:59 -0700792 StatsLogEventWrapper e = new StatsLogEventWrapper(tag, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -0800793 e.writeInt(entry.uid);
794 if (withFGBG) {
795 e.writeInt(entry.set);
796 }
797 e.writeLong(entry.rxBytes);
798 e.writeLong(entry.rxPackets);
799 e.writeLong(entry.txBytes);
800 e.writeLong(entry.txPackets);
801 ret.add(e);
David Chenc8a43242017-10-17 16:23:28 -0700802 }
David Chenc8a43242017-10-17 16:23:28 -0700803 }
804
805 /**
806 * Allows rollups per UID but keeping the set (foreground/background) slicing.
807 * Adapted from groupedByUid in frameworks/base/core/java/android/net/NetworkStats.java
808 */
809 private NetworkStats rollupNetworkStatsByFGBG(NetworkStats stats) {
810 final NetworkStats ret = new NetworkStats(stats.getElapsedRealtime(), 1);
811
812 final NetworkStats.Entry entry = new NetworkStats.Entry();
813 entry.iface = NetworkStats.IFACE_ALL;
814 entry.tag = NetworkStats.TAG_NONE;
815 entry.metered = NetworkStats.METERED_ALL;
816 entry.roaming = NetworkStats.ROAMING_ALL;
817
818 int size = stats.size();
819 NetworkStats.Entry recycle = new NetworkStats.Entry(); // Used for retrieving values
820 for (int i = 0; i < size; i++) {
821 stats.getValues(i, recycle);
822
823 // Skip specific tags, since already counted in TAG_NONE
824 if (recycle.tag != NetworkStats.TAG_NONE) continue;
825
826 entry.set = recycle.set; // Allows slicing by background/foreground
827 entry.uid = recycle.uid;
828 entry.rxBytes = recycle.rxBytes;
829 entry.rxPackets = recycle.rxPackets;
830 entry.txBytes = recycle.txBytes;
831 entry.txPackets = recycle.txPackets;
832 // Operations purposefully omitted since we don't use them for statsd.
833 ret.combineValues(entry);
834 }
835 return ret;
836 }
837
Chenjie Yu05013b32017-11-21 10:21:41 -0800838 /**
839 * Helper method to extract the Parcelable controller info from a
840 * SynchronousResultReceiver.
841 */
842 private static <T extends Parcelable> T awaitControllerInfo(
843 @Nullable SynchronousResultReceiver receiver) {
844 if (receiver == null) {
845 return null;
846 }
847
848 try {
849 final SynchronousResultReceiver.Result result =
850 receiver.awaitResult(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS);
851 if (result.bundle != null) {
852 // This is the final destination for the Bundle.
853 result.bundle.setDefusable(true);
854
855 final T data = result.bundle.getParcelable(
856 RESULT_RECEIVER_CONTROLLER_KEY);
857 if (data != null) {
858 return data;
859 }
860 }
861 Slog.e(TAG, "no controller energy info supplied for " + receiver.getName());
862 } catch (TimeoutException e) {
863 Slog.w(TAG, "timeout reading " + receiver.getName() + " stats");
864 }
865 return null;
866 }
867
Chenjie Yu12e5e672018-09-14 15:54:59 -0700868 private void pullKernelWakelock(
869 int tagId, long elapsedNanos, long wallClockNanos,
870 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800871 final KernelWakelockStats wakelockStats =
872 mKernelWakelockReader.readKernelWakelockStats(mTmpWakelockStats);
873 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
874 String name = ent.getKey();
875 KernelWakelockStats.Entry kws = ent.getValue();
Chenjie Yu12e5e672018-09-14 15:54:59 -0700876 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -0800877 e.writeString(name);
878 e.writeInt(kws.mCount);
879 e.writeInt(kws.mVersion);
880 e.writeLong(kws.mTotalTime);
881 pulledData.add(e);
882 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800883 }
884
Chenjie Yu12e5e672018-09-14 15:54:59 -0700885 private void pullWifiBytesTransfer(
886 int tagId, long elapsedNanos, long wallClockNanos,
887 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800888 long token = Binder.clearCallingIdentity();
889 try {
890 // TODO: Consider caching the following call to get BatteryStatsInternal.
891 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
892 String[] ifaces = bs.getWifiIfaces();
893 if (ifaces.length == 0) {
894 return;
895 }
Chenbo Fenge62e2872019-01-11 15:50:17 -0800896 if (mNetworkStatsService == null) {
897 Slog.e(TAG, "NetworkStats Service is not available!");
898 return;
899 }
David Chen661f7912018-01-22 17:46:24 -0800900 // Combine all the metrics per Uid into one record.
Chenbo Fenge62e2872019-01-11 15:50:17 -0800901 NetworkStats stats = mNetworkStatsService.getDetailedUidStats(ifaces).groupedByUid();
David Chen661f7912018-01-22 17:46:24 -0800902 addNetworkStats(tagId, pulledData, stats, false);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800903 } catch (RemoteException e) {
David Chen661f7912018-01-22 17:46:24 -0800904 Slog.e(TAG, "Pulling netstats for wifi bytes has error", e);
905 } finally {
906 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800907 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800908 }
909
Chenjie Yu12e5e672018-09-14 15:54:59 -0700910 private void pullWifiBytesTransferByFgBg(
911 int tagId, long elapsedNanos, long wallClockNanos,
912 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800913 long token = Binder.clearCallingIdentity();
914 try {
915 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
916 String[] ifaces = bs.getWifiIfaces();
917 if (ifaces.length == 0) {
918 return;
919 }
Chenbo Fenge62e2872019-01-11 15:50:17 -0800920 if (mNetworkStatsService == null) {
921 Slog.e(TAG, "NetworkStats Service is not available!");
922 return;
923 }
David Chen661f7912018-01-22 17:46:24 -0800924 NetworkStats stats = rollupNetworkStatsByFGBG(
Chenbo Fenge62e2872019-01-11 15:50:17 -0800925 mNetworkStatsService.getDetailedUidStats(ifaces));
David Chen661f7912018-01-22 17:46:24 -0800926 addNetworkStats(tagId, pulledData, stats, true);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800927 } catch (RemoteException e) {
David Chen661f7912018-01-22 17:46:24 -0800928 Slog.e(TAG, "Pulling netstats for wifi bytes w/ fg/bg has error", e);
929 } finally {
930 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800931 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800932 }
933
Chenjie Yu12e5e672018-09-14 15:54:59 -0700934 private void pullMobileBytesTransfer(
935 int tagId, long elapsedNanos, long wallClockNanos,
936 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800937 long token = Binder.clearCallingIdentity();
938 try {
939 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
940 String[] ifaces = bs.getMobileIfaces();
941 if (ifaces.length == 0) {
942 return;
943 }
Chenbo Fenge62e2872019-01-11 15:50:17 -0800944 if (mNetworkStatsService == null) {
945 Slog.e(TAG, "NetworkStats Service is not available!");
946 return;
947 }
David Chen661f7912018-01-22 17:46:24 -0800948 // Combine all the metrics per Uid into one record.
Chenbo Fenge62e2872019-01-11 15:50:17 -0800949 NetworkStats stats = mNetworkStatsService.getDetailedUidStats(ifaces).groupedByUid();
David Chen661f7912018-01-22 17:46:24 -0800950 addNetworkStats(tagId, pulledData, stats, false);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800951 } catch (RemoteException e) {
David Chen661f7912018-01-22 17:46:24 -0800952 Slog.e(TAG, "Pulling netstats for mobile bytes has error", e);
953 } finally {
954 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800955 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800956 }
957
Chenjie Yu12e5e672018-09-14 15:54:59 -0700958 private void pullBluetoothBytesTransfer(
959 int tagId, long elapsedNanos, long wallClockNanos,
960 List<StatsLogEventWrapper> pulledData) {
Yangster-mac95543242018-10-22 11:44:03 -0700961 BluetoothActivityEnergyInfo info = fetchBluetoothData();
Chenjie Yu9e59f932018-03-30 16:41:38 -0700962 if (info.getUidTraffic() != null) {
963 for (UidTraffic traffic : info.getUidTraffic()) {
Chenjie Yu12e5e672018-09-14 15:54:59 -0700964 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
965 wallClockNanos);
Chenjie Yu9e59f932018-03-30 16:41:38 -0700966 e.writeInt(traffic.getUid());
967 e.writeLong(traffic.getRxBytes());
968 e.writeLong(traffic.getTxBytes());
969 pulledData.add(e);
970 }
David Chen661f7912018-01-22 17:46:24 -0800971 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800972 }
973
Chenjie Yu12e5e672018-09-14 15:54:59 -0700974 private void pullMobileBytesTransferByFgBg(
975 int tagId, long elapsedNanos, long wallClockNanos,
976 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -0800977 long token = Binder.clearCallingIdentity();
978 try {
979 BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
980 String[] ifaces = bs.getMobileIfaces();
981 if (ifaces.length == 0) {
982 return;
983 }
Chenbo Fenge62e2872019-01-11 15:50:17 -0800984 if (mNetworkStatsService == null) {
985 Slog.e(TAG, "NetworkStats Service is not available!");
986 return;
987 }
David Chen661f7912018-01-22 17:46:24 -0800988 NetworkStats stats = rollupNetworkStatsByFGBG(
Chenbo Fenge62e2872019-01-11 15:50:17 -0800989 mNetworkStatsService.getDetailedUidStats(ifaces));
David Chen661f7912018-01-22 17:46:24 -0800990 addNetworkStats(tagId, pulledData, stats, true);
Chenbo Fenge62e2872019-01-11 15:50:17 -0800991 } catch (RemoteException e) {
David Chen661f7912018-01-22 17:46:24 -0800992 Slog.e(TAG, "Pulling netstats for mobile bytes w/ fg/bg has error", e);
993 } finally {
994 Binder.restoreCallingIdentity(token);
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800995 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -0800996 }
997
Chenjie Yu12e5e672018-09-14 15:54:59 -0700998 private void pullCpuTimePerFreq(
999 int tagId, long elapsedNanos, long wallClockNanos,
1000 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -08001001 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
1002 long[] clusterTimeMs = mKernelCpuSpeedReaders[cluster].readAbsolute();
1003 if (clusterTimeMs != null) {
1004 for (int speed = clusterTimeMs.length - 1; speed >= 0; --speed) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001005 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1006 wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001007 e.writeInt(cluster);
1008 e.writeInt(speed);
1009 e.writeLong(clusterTimeMs[speed]);
1010 pulledData.add(e);
1011 }
1012 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001013 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001014 }
1015
Chenjie Yu12e5e672018-09-14 15:54:59 -07001016 private void pullKernelUidCpuTime(
1017 int tagId, long elapsedNanos, long wallClockNanos,
1018 List<StatsLogEventWrapper> pulledData) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -08001019 mCpuUidUserSysTimeReader.readAbsolute((uid, timesUs) -> {
1020 long userTimeUs = timesUs[0], systemTimeUs = timesUs[1];
Chenjie Yu12e5e672018-09-14 15:54:59 -07001021 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Chenjie Yuec676612018-03-07 09:19:17 -08001022 e.writeInt(uid);
1023 e.writeLong(userTimeUs);
1024 e.writeLong(systemTimeUs);
1025 pulledData.add(e);
1026 });
1027 }
1028
Chenjie Yu12e5e672018-09-14 15:54:59 -07001029 private void pullKernelUidCpuFreqTime(
1030 int tagId, long elapsedNanos, long wallClockNanos,
1031 List<StatsLogEventWrapper> pulledData) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -08001032 mCpuUidFreqTimeReader.readAbsolute((uid, cpuFreqTimeMs) -> {
Chenjie Yuec676612018-03-07 09:19:17 -08001033 for (int freqIndex = 0; freqIndex < cpuFreqTimeMs.length; ++freqIndex) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001034 if (cpuFreqTimeMs[freqIndex] != 0) {
1035 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1036 wallClockNanos);
Chenjie Yu4460e3c2018-03-14 17:12:59 -07001037 e.writeInt(uid);
1038 e.writeInt(freqIndex);
1039 e.writeLong(cpuFreqTimeMs[freqIndex]);
1040 pulledData.add(e);
1041 }
Chenjie Yuec676612018-03-07 09:19:17 -08001042 }
1043 });
1044 }
1045
Chenjie Yu12e5e672018-09-14 15:54:59 -07001046 private void pullKernelUidCpuClusterTime(
1047 int tagId, long elapsedNanos, long wallClockNanos,
1048 List<StatsLogEventWrapper> pulledData) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -08001049 mCpuUidClusterTimeReader.readAbsolute((uid, cpuClusterTimesMs) -> {
Chenjie Yuec676612018-03-07 09:19:17 -08001050 for (int i = 0; i < cpuClusterTimesMs.length; i++) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001051 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1052 wallClockNanos);
Chenjie Yuec676612018-03-07 09:19:17 -08001053 e.writeInt(uid);
1054 e.writeInt(i);
1055 e.writeLong(cpuClusterTimesMs[i]);
1056 pulledData.add(e);
1057 }
1058 });
1059 }
1060
Chenjie Yu12e5e672018-09-14 15:54:59 -07001061 private void pullKernelUidCpuActiveTime(
1062 int tagId, long elapsedNanos, long wallClockNanos,
1063 List<StatsLogEventWrapper> pulledData) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -08001064 mCpuUidActiveTimeReader.readAbsolute((uid, cpuActiveTimesMs) -> {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001065 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Chenjie Yuec676612018-03-07 09:19:17 -08001066 e.writeInt(uid);
Chenjie Yu12e5e672018-09-14 15:54:59 -07001067 e.writeLong((long) cpuActiveTimesMs);
Chenjie Yuec676612018-03-07 09:19:17 -08001068 pulledData.add(e);
1069 });
1070 }
1071
Chenjie Yu12e5e672018-09-14 15:54:59 -07001072 private void pullWifiActivityInfo(
1073 int tagId, long elapsedNanos, long wallClockNanos,
1074 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -08001075 long token = Binder.clearCallingIdentity();
Yangster-mac95543242018-10-22 11:44:03 -07001076 synchronized (this) {
1077 if (mWifiManager == null) {
1078 mWifiManager =
1079 IWifiManager.Stub.asInterface(
1080 ServiceManager.getService(Context.WIFI_SERVICE));
1081 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001082 }
David Chen661f7912018-01-22 17:46:24 -08001083 if (mWifiManager != null) {
1084 try {
1085 SynchronousResultReceiver wifiReceiver = new SynchronousResultReceiver("wifi");
1086 mWifiManager.requestActivityInfo(wifiReceiver);
1087 final WifiActivityEnergyInfo wifiInfo = awaitControllerInfo(wifiReceiver);
Chenjie Yu12e5e672018-09-14 15:54:59 -07001088 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1089 wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001090 e.writeLong(wifiInfo.getTimeStamp());
1091 e.writeInt(wifiInfo.getStackState());
1092 e.writeLong(wifiInfo.getControllerTxTimeMillis());
1093 e.writeLong(wifiInfo.getControllerRxTimeMillis());
1094 e.writeLong(wifiInfo.getControllerIdleTimeMillis());
1095 e.writeLong(wifiInfo.getControllerEnergyUsed());
1096 pulledData.add(e);
1097 } catch (RemoteException e) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001098 Slog.e(TAG,
1099 "Pulling wifiManager for wifi controller activity energy info has error",
1100 e);
David Chen661f7912018-01-22 17:46:24 -08001101 } finally {
1102 Binder.restoreCallingIdentity(token);
1103 }
1104 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001105 }
1106
Chenjie Yu12e5e672018-09-14 15:54:59 -07001107 private void pullModemActivityInfo(
1108 int tagId, long elapsedNanos, long wallClockNanos,
1109 List<StatsLogEventWrapper> pulledData) {
David Chen661f7912018-01-22 17:46:24 -08001110 long token = Binder.clearCallingIdentity();
Yangster-mac95543242018-10-22 11:44:03 -07001111 synchronized (this) {
1112 if (mTelephony == null) {
1113 mTelephony = TelephonyManager.from(mContext);
1114 }
David Chen661f7912018-01-22 17:46:24 -08001115 }
1116 if (mTelephony != null) {
1117 SynchronousResultReceiver modemReceiver = new SynchronousResultReceiver("telephony");
1118 mTelephony.requestModemActivityInfo(modemReceiver);
1119 final ModemActivityInfo modemInfo = awaitControllerInfo(modemReceiver);
Chenjie Yu12e5e672018-09-14 15:54:59 -07001120 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001121 e.writeLong(modemInfo.getTimestamp());
1122 e.writeLong(modemInfo.getSleepTimeMillis());
1123 e.writeLong(modemInfo.getIdleTimeMillis());
Chen Xu7322e4a2019-09-07 15:51:22 -07001124 e.writeLong(modemInfo.getTransmitPowerInfo().get(0).getTimeInMillis());
1125 e.writeLong(modemInfo.getTransmitPowerInfo().get(1).getTimeInMillis());
1126 e.writeLong(modemInfo.getTransmitPowerInfo().get(2).getTimeInMillis());
1127 e.writeLong(modemInfo.getTransmitPowerInfo().get(3).getTimeInMillis());
1128 e.writeLong(modemInfo.getTransmitPowerInfo().get(4).getTimeInMillis());
1129 e.writeLong(modemInfo.getReceiveTimeMillis());
David Chen661f7912018-01-22 17:46:24 -08001130 pulledData.add(e);
1131 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001132 }
1133
Chenjie Yu12e5e672018-09-14 15:54:59 -07001134 private void pullBluetoothActivityInfo(
1135 int tagId, long elapsedNanos, long wallClockNanos,
1136 List<StatsLogEventWrapper> pulledData) {
Yangster-mac95543242018-10-22 11:44:03 -07001137 BluetoothActivityEnergyInfo info = fetchBluetoothData();
Chenjie Yu12e5e672018-09-14 15:54:59 -07001138 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001139 e.writeLong(info.getTimeStamp());
1140 e.writeInt(info.getBluetoothStackState());
1141 e.writeLong(info.getControllerTxTimeMillis());
1142 e.writeLong(info.getControllerRxTimeMillis());
1143 e.writeLong(info.getControllerIdleTimeMillis());
1144 e.writeLong(info.getControllerEnergyUsed());
1145 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001146 }
1147
Yangster-mac95543242018-10-22 11:44:03 -07001148 private synchronized BluetoothActivityEnergyInfo fetchBluetoothData() {
Chenjie Yuc2d65442018-02-01 22:27:17 -08001149 final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
David Chen661f7912018-01-22 17:46:24 -08001150 if (adapter != null) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001151 SynchronousResultReceiver bluetoothReceiver = new SynchronousResultReceiver(
1152 "bluetooth");
David Chen661f7912018-01-22 17:46:24 -08001153 adapter.requestControllerActivityEnergyInfo(bluetoothReceiver);
1154 return awaitControllerInfo(bluetoothReceiver);
1155 } else {
1156 Slog.e(TAG, "Failed to get bluetooth adapter!");
1157 return null;
1158 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001159 }
1160
Chenjie Yu12e5e672018-09-14 15:54:59 -07001161 private void pullSystemElapsedRealtime(
1162 int tagId, long elapsedNanos, long wallClockNanos,
1163 List<StatsLogEventWrapper> pulledData) {
1164 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001165 e.writeLong(SystemClock.elapsedRealtime());
1166 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001167 }
1168
Chenjie Yu12e5e672018-09-14 15:54:59 -07001169 private void pullSystemUpTime(int tagId, long elapsedNanos, long wallClockNanos,
1170 List<StatsLogEventWrapper> pulledData) {
1171 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
David Chen661f7912018-01-22 17:46:24 -08001172 e.writeLong(SystemClock.uptimeMillis());
1173 pulledData.add(e);
Chenjie Yu9d7720b2018-01-24 10:34:48 -08001174 }
1175
Chenjie Yu12e5e672018-09-14 15:54:59 -07001176 private void pullProcessMemoryState(
1177 int tagId, long elapsedNanos, long wallClockNanos,
1178 List<StatsLogEventWrapper> pulledData) {
Rajeev Kumar22d92b72018-02-07 18:38:36 -08001179 List<ProcessMemoryState> processMemoryStates =
Chenjie Yu12e5e672018-09-14 15:54:59 -07001180 LocalServices.getService(
1181 ActivityManagerInternal.class).getMemoryStateForProcesses();
Rajeev Kumar22d92b72018-02-07 18:38:36 -08001182 for (ProcessMemoryState processMemoryState : processMemoryStates) {
Ioannis Ilkos466ad6c2019-06-18 17:42:00 +01001183 final MemoryStat memoryStat = readMemoryStatFromFilesystem(processMemoryState.uid,
1184 processMemoryState.pid);
1185 if (memoryStat == null) {
1186 continue;
1187 }
Chenjie Yu12e5e672018-09-14 15:54:59 -07001188 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Rajeev Kumar22d92b72018-02-07 18:38:36 -08001189 e.writeInt(processMemoryState.uid);
1190 e.writeString(processMemoryState.processName);
1191 e.writeInt(processMemoryState.oomScore);
Ioannis Ilkos466ad6c2019-06-18 17:42:00 +01001192 e.writeLong(memoryStat.pgfault);
1193 e.writeLong(memoryStat.pgmajfault);
1194 e.writeLong(memoryStat.rssInBytes);
1195 e.writeLong(memoryStat.cacheInBytes);
1196 e.writeLong(memoryStat.swapInBytes);
Rafal Slawik203c3db2019-09-25 19:53:01 +01001197 e.writeLong(-1); // unused
1198 e.writeLong(-1); // unused
1199 e.writeInt(-1); // unsed
Rajeev Kumar22d92b72018-02-07 18:38:36 -08001200 pulledData.add(e);
1201 }
1202 }
1203
Rafal Slawik3bea8952018-11-15 12:39:33 +00001204 private void pullProcessMemoryHighWaterMark(
1205 int tagId, long elapsedNanos, long wallClockNanos,
1206 List<StatsLogEventWrapper> pulledData) {
Ioannis Ilkos466ad6c2019-06-18 17:42:00 +01001207 List<ProcessMemoryState> managedProcessList =
1208 LocalServices.getService(
1209 ActivityManagerInternal.class).getMemoryStateForProcesses();
1210 for (ProcessMemoryState managedProcess : managedProcessList) {
Rafal Slawik21d3f512019-09-24 20:00:18 +01001211 final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(managedProcess.pid);
1212 if (snapshot == null) {
Ioannis Ilkos466ad6c2019-06-18 17:42:00 +01001213 continue;
1214 }
Rafal Slawik3bea8952018-11-15 12:39:33 +00001215 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Ioannis Ilkos466ad6c2019-06-18 17:42:00 +01001216 e.writeInt(managedProcess.uid);
1217 e.writeString(managedProcess.processName);
Rafal Slawik239b6802019-09-09 18:46:01 +01001218 // RSS high-water mark in bytes.
Rafal Slawik21d3f512019-09-24 20:00:18 +01001219 e.writeLong((long) snapshot.rssHighWaterMarkInKilobytes * 1024L);
1220 e.writeInt(snapshot.rssHighWaterMarkInKilobytes);
Rafal Slawik3bea8952018-11-15 12:39:33 +00001221 pulledData.add(e);
1222 }
1223 int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
Rafal Slawik21d3f512019-09-24 20:00:18 +01001224 for (int pid : pids) {
Rafal Slawik3bea8952018-11-15 12:39:33 +00001225 final String processName = readCmdlineFromProcfs(pid);
Rafal Slawik21d3f512019-09-24 20:00:18 +01001226 final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(pid);
1227 if (snapshot == null) {
1228 continue;
1229 }
1230 // Sometimes we get here a process that is not included in the whitelist. It comes
1231 // from forking the zygote for an app. We can ignore that sample because this process
1232 // is collected by ProcessMemoryState.
1233 if (isAppUid(snapshot.uid)) {
Rafal Slawik239b6802019-09-09 18:46:01 +01001234 continue;
1235 }
Rafal Slawik3bea8952018-11-15 12:39:33 +00001236 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Rafal Slawik21d3f512019-09-24 20:00:18 +01001237 e.writeInt(snapshot.uid);
Rafal Slawik3bea8952018-11-15 12:39:33 +00001238 e.writeString(processName);
Rafal Slawik239b6802019-09-09 18:46:01 +01001239 // RSS high-water mark in bytes.
Rafal Slawik21d3f512019-09-24 20:00:18 +01001240 e.writeLong((long) snapshot.rssHighWaterMarkInKilobytes * 1024L);
1241 e.writeInt(snapshot.rssHighWaterMarkInKilobytes);
Rafal Slawik3bea8952018-11-15 12:39:33 +00001242 pulledData.add(e);
1243 }
Rafal Slawik44b88142018-12-15 16:48:09 +00001244 // Invoke rss_hwm_reset binary to reset RSS HWM counters for all processes.
1245 SystemProperties.set("sys.rss_hwm_reset.on", "1");
Rafal Slawik3bea8952018-11-15 12:39:33 +00001246 }
1247
Rafal Slawik7efcefb2019-09-20 11:16:20 +01001248 private void pullProcessMemorySnapshot(
1249 int tagId, long elapsedNanos, long wallClockNanos,
1250 List<StatsLogEventWrapper> pulledData) {
1251 List<ProcessMemoryState> managedProcessList =
1252 LocalServices.getService(
1253 ActivityManagerInternal.class).getMemoryStateForProcesses();
1254 for (ProcessMemoryState managedProcess : managedProcessList) {
Rafal Slawik21d3f512019-09-24 20:00:18 +01001255 final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(managedProcess.pid);
1256 if (snapshot == null) {
1257 continue;
1258 }
Rafal Slawik7efcefb2019-09-20 11:16:20 +01001259 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1260 e.writeInt(managedProcess.uid);
1261 e.writeString(managedProcess.processName);
1262 e.writeInt(managedProcess.pid);
1263 e.writeInt(managedProcess.oomScore);
Rafal Slawik7efcefb2019-09-20 11:16:20 +01001264 e.writeInt(snapshot.rssInKilobytes);
1265 e.writeInt(snapshot.anonRssInKilobytes);
1266 e.writeInt(snapshot.swapInKilobytes);
1267 e.writeInt(snapshot.anonRssInKilobytes + snapshot.swapInKilobytes);
1268 pulledData.add(e);
1269 }
1270 int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
1271 for (int pid : pids) {
Rafal Slawik21d3f512019-09-24 20:00:18 +01001272 final String processName = readCmdlineFromProcfs(pid);
Rafal Slawik7efcefb2019-09-20 11:16:20 +01001273 final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(pid);
Rafal Slawik21d3f512019-09-24 20:00:18 +01001274 if (snapshot == null) {
Rafal Slawik7efcefb2019-09-20 11:16:20 +01001275 continue;
1276 }
Rafal Slawik21d3f512019-09-24 20:00:18 +01001277 // Sometimes we get here a process that is not included in the whitelist. It comes
1278 // from forking the zygote for an app. We can ignore that sample because this process
1279 // is collected by ProcessMemoryState.
1280 if (isAppUid(snapshot.uid)) {
1281 continue;
1282 }
1283 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1284 e.writeInt(snapshot.uid);
1285 e.writeString(processName);
1286 e.writeInt(pid);
1287 e.writeInt(-1001); // Placeholder for native processes, OOM_SCORE_ADJ_MIN - 1.
Rafal Slawik7efcefb2019-09-20 11:16:20 +01001288 e.writeInt(snapshot.rssInKilobytes);
1289 e.writeInt(snapshot.anonRssInKilobytes);
1290 e.writeInt(snapshot.swapInKilobytes);
1291 e.writeInt(snapshot.anonRssInKilobytes + snapshot.swapInKilobytes);
1292 pulledData.add(e);
1293 }
1294 }
1295
Rafal Slawik21d3f512019-09-24 20:00:18 +01001296 private static boolean isAppUid(int uid) {
1297 return uid >= MIN_APP_UID;
1298 }
1299
Rafal Slawikd4e87572019-03-12 13:08:38 +00001300 private void pullSystemIonHeapSize(
1301 int tagId, long elapsedNanos, long wallClockNanos,
1302 List<StatsLogEventWrapper> pulledData) {
1303 final long systemIonHeapSizeInBytes = readSystemIonHeapSizeFromDebugfs();
1304 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1305 e.writeLong(systemIonHeapSizeInBytes);
1306 pulledData.add(e);
1307 }
1308
Rafal Slawik77987ed2019-06-17 12:28:23 +01001309 private void pullProcessSystemIonHeapSize(
1310 int tagId, long elapsedNanos, long wallClockNanos,
1311 List<StatsLogEventWrapper> pulledData) {
Rafal Slawik5fe706c2019-06-19 17:59:50 +01001312 List<IonAllocations> result = readProcessSystemIonHeapSizesFromDebugfs();
1313 for (IonAllocations allocations : result) {
1314 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1315 e.writeInt(getUidForPid(allocations.pid));
1316 e.writeString(readCmdlineFromProcfs(allocations.pid));
1317 e.writeInt((int) (allocations.totalSizeInBytes / 1024));
1318 e.writeInt(allocations.count);
1319 e.writeInt((int) (allocations.maxSizeInBytes / 1024));
1320 pulledData.add(e);
1321 }
Rafal Slawik77987ed2019-06-17 12:28:23 +01001322 }
1323
Chenjie Yu12e5e672018-09-14 15:54:59 -07001324 private void pullBinderCallsStats(
1325 int tagId, long elapsedNanos, long wallClockNanos,
1326 List<StatsLogEventWrapper> pulledData) {
Olivier Gaillard289ba402018-07-24 18:50:13 +01001327 BinderCallsStatsService.Internal binderStats =
1328 LocalServices.getService(BinderCallsStatsService.Internal.class);
Olivier Gaillard44a60a92018-07-25 22:53:55 +01001329 if (binderStats == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001330 throw new IllegalStateException("binderStats is null");
Olivier Gaillard44a60a92018-07-25 22:53:55 +01001331 }
1332
Olivier Gaillard289ba402018-07-24 18:50:13 +01001333 List<ExportedCallStat> callStats = binderStats.getExportedCallStats();
Olivier Gaillardd25f7a82018-09-12 14:28:48 +01001334 binderStats.reset();
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01001335 for (ExportedCallStat callStat : callStats) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001336 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Olivier Gaillard88de48f2018-10-18 10:21:21 +01001337 e.writeInt(callStat.workSourceUid);
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01001338 e.writeString(callStat.className);
1339 e.writeString(callStat.methodName);
1340 e.writeLong(callStat.callCount);
1341 e.writeLong(callStat.exceptionCount);
1342 e.writeLong(callStat.latencyMicros);
1343 e.writeLong(callStat.maxLatencyMicros);
1344 e.writeLong(callStat.cpuTimeMicros);
1345 e.writeLong(callStat.maxCpuTimeMicros);
1346 e.writeLong(callStat.maxReplySizeBytes);
1347 e.writeLong(callStat.maxRequestSizeBytes);
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001348 e.writeLong(callStat.recordedCallCount);
1349 e.writeInt(callStat.screenInteractive ? 1 : 0);
Olivier Gaillard720ec5b2018-10-30 17:32:56 +00001350 e.writeInt(callStat.callingUid);
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001351 pulledData.add(e);
1352 }
1353 }
1354
Chenjie Yu12e5e672018-09-14 15:54:59 -07001355 private void pullBinderCallsStatsExceptions(
1356 int tagId, long elapsedNanos, long wallClockNanos,
1357 List<StatsLogEventWrapper> pulledData) {
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001358 BinderCallsStatsService.Internal binderStats =
1359 LocalServices.getService(BinderCallsStatsService.Internal.class);
Olivier Gaillard44a60a92018-07-25 22:53:55 +01001360 if (binderStats == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001361 throw new IllegalStateException("binderStats is null");
Olivier Gaillard44a60a92018-07-25 22:53:55 +01001362 }
1363
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001364 ArrayMap<String, Integer> exceptionStats = binderStats.getExportedExceptionStats();
Olivier Gaillardd25f7a82018-09-12 14:28:48 +01001365 // TODO: decouple binder calls exceptions with the rest of the binder calls data so that we
1366 // can reset the exception stats.
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001367 for (Entry<String, Integer> entry : exceptionStats.entrySet()) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001368 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Olivier Gaillard6f52d152018-07-25 12:13:12 +01001369 e.writeString(entry.getKey());
1370 e.writeInt(entry.getValue());
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01001371 pulledData.add(e);
1372 }
1373 }
1374
Chenjie Yu12e5e672018-09-14 15:54:59 -07001375 private void pullLooperStats(int tagId, long elapsedNanos, long wallClockNanos,
1376 List<StatsLogEventWrapper> pulledData) {
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001377 LooperStats looperStats = LocalServices.getService(LooperStats.class);
1378 if (looperStats == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001379 throw new IllegalStateException("looperStats null");
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001380 }
1381
1382 List<LooperStats.ExportedEntry> entries = looperStats.getEntries();
Marcin Oczeretko3e6494e2018-09-10 18:06:52 +01001383 looperStats.reset();
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001384 for (LooperStats.ExportedEntry entry : entries) {
Chenjie Yu12e5e672018-09-14 15:54:59 -07001385 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Marcin Oczeretkoec758722018-09-12 12:53:47 +01001386 e.writeInt(entry.workSourceUid);
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001387 e.writeString(entry.handlerClassName);
1388 e.writeString(entry.threadName);
1389 e.writeString(entry.messageName);
1390 e.writeLong(entry.messageCount);
1391 e.writeLong(entry.exceptionCount);
1392 e.writeLong(entry.recordedMessageCount);
1393 e.writeLong(entry.totalLatencyMicros);
1394 e.writeLong(entry.cpuUsageMicros);
Marcin Oczeretko3e6494e2018-09-10 18:06:52 +01001395 e.writeBoolean(entry.isInteractive);
Marcin Oczeretkoc06331a2018-10-02 13:00:38 +01001396 e.writeLong(entry.maxCpuUsageMicros);
1397 e.writeLong(entry.maxLatencyMicros);
1398 e.writeLong(entry.recordedDelayMessageCount);
1399 e.writeLong(entry.delayMillis);
1400 e.writeLong(entry.maxDelayMillis);
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01001401 pulledData.add(e);
1402 }
1403 }
1404
Chenjie Yu12e5e672018-09-14 15:54:59 -07001405 private void pullDiskStats(int tagId, long elapsedNanos, long wallClockNanos,
1406 List<StatsLogEventWrapper> pulledData) {
Tej Singh86dc9db2018-09-06 00:39:57 +00001407 // Run a quick-and-dirty performance test: write 512 bytes
1408 byte[] junk = new byte[512];
1409 for (int i = 0; i < junk.length; i++) junk[i] = (byte) i; // Write nonzero bytes
1410
1411 File tmp = new File(Environment.getDataDirectory(), "system/statsdperftest.tmp");
1412 FileOutputStream fos = null;
1413 IOException error = null;
1414
1415 long before = SystemClock.elapsedRealtime();
1416 try {
1417 fos = new FileOutputStream(tmp);
1418 fos.write(junk);
1419 } catch (IOException e) {
1420 error = e;
1421 } finally {
1422 try {
1423 if (fos != null) fos.close();
1424 } catch (IOException e) {
1425 // Do nothing.
1426 }
1427 }
1428
1429 long latency = SystemClock.elapsedRealtime() - before;
1430 if (tmp.exists()) tmp.delete();
1431
1432 if (error != null) {
1433 Slog.e(TAG, "Error performing diskstats latency test");
1434 latency = -1;
1435 }
1436 // File based encryption.
1437 boolean fileBased = StorageManager.isFileEncryptedNativeOnly();
1438
1439 //Recent disk write speed. Binder call to storaged.
1440 int writeSpeed = -1;
1441 try {
1442 IBinder binder = ServiceManager.getService("storaged");
1443 if (binder == null) {
1444 Slog.e(TAG, "storaged not found");
1445 }
1446 IStoraged storaged = IStoraged.Stub.asInterface(binder);
1447 writeSpeed = storaged.getRecentPerf();
1448 } catch (RemoteException e) {
1449 Slog.e(TAG, "storaged not found");
1450 }
1451
1452 // Add info pulledData.
Chenjie Yu12e5e672018-09-14 15:54:59 -07001453 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001454 e.writeLong(latency);
1455 e.writeBoolean(fileBased);
1456 e.writeInt(writeSpeed);
1457 pulledData.add(e);
1458 }
1459
Chenjie Yu12e5e672018-09-14 15:54:59 -07001460 private void pullDirectoryUsage(int tagId, long elapsedNanos, long wallClockNanos,
1461 List<StatsLogEventWrapper> pulledData) {
Tej Singh86dc9db2018-09-06 00:39:57 +00001462 StatFs statFsData = new StatFs(Environment.getDataDirectory().getAbsolutePath());
1463 StatFs statFsSystem = new StatFs(Environment.getRootDirectory().getAbsolutePath());
1464 StatFs statFsCache = new StatFs(Environment.getDownloadCacheDirectory().getAbsolutePath());
1465
Chenjie Yu12e5e672018-09-14 15:54:59 -07001466 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001467 e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__DATA);
1468 e.writeLong(statFsData.getAvailableBytes());
1469 e.writeLong(statFsData.getTotalBytes());
1470 pulledData.add(e);
1471
Chenjie Yu12e5e672018-09-14 15:54:59 -07001472 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001473 e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__CACHE);
1474 e.writeLong(statFsCache.getAvailableBytes());
1475 e.writeLong(statFsCache.getTotalBytes());
1476 pulledData.add(e);
1477
Chenjie Yu12e5e672018-09-14 15:54:59 -07001478 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001479 e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__SYSTEM);
1480 e.writeLong(statFsSystem.getAvailableBytes());
1481 e.writeLong(statFsSystem.getTotalBytes());
1482 pulledData.add(e);
1483 }
1484
Chenjie Yu12e5e672018-09-14 15:54:59 -07001485 private void pullAppSize(int tagId, long elapsedNanos, long wallClockNanos,
1486 List<StatsLogEventWrapper> pulledData) {
Tej Singh86dc9db2018-09-06 00:39:57 +00001487 try {
1488 String jsonStr = IoUtils.readFileAsString(DiskStatsLoggingService.DUMPSYS_CACHE_PATH);
1489 JSONObject json = new JSONObject(jsonStr);
1490 long cache_time = json.optLong(DiskStatsFileLogger.LAST_QUERY_TIMESTAMP_KEY, -1L);
1491 JSONArray pkg_names = json.getJSONArray(DiskStatsFileLogger.PACKAGE_NAMES_KEY);
1492 JSONArray app_sizes = json.getJSONArray(DiskStatsFileLogger.APP_SIZES_KEY);
1493 JSONArray app_data_sizes = json.getJSONArray(DiskStatsFileLogger.APP_DATA_KEY);
1494 JSONArray app_cache_sizes = json.getJSONArray(DiskStatsFileLogger.APP_CACHES_KEY);
1495 // Sanity check: Ensure all 4 lists have the same length.
1496 int length = pkg_names.length();
1497 if (app_sizes.length() != length || app_data_sizes.length() != length
1498 || app_cache_sizes.length() != length) {
1499 Slog.e(TAG, "formatting error in diskstats cache file!");
1500 return;
1501 }
1502 for (int i = 0; i < length; i++) {
1503 StatsLogEventWrapper e =
Chenjie Yu12e5e672018-09-14 15:54:59 -07001504 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001505 e.writeString(pkg_names.getString(i));
1506 e.writeLong(app_sizes.optLong(i, -1L));
1507 e.writeLong(app_data_sizes.optLong(i, -1L));
1508 e.writeLong(app_cache_sizes.optLong(i, -1L));
1509 e.writeLong(cache_time);
1510 pulledData.add(e);
1511 }
1512 } catch (IOException | JSONException e) {
1513 Slog.e(TAG, "exception reading diskstats cache file", e);
1514 }
1515 }
1516
Chenjie Yu12e5e672018-09-14 15:54:59 -07001517 private void pullCategorySize(int tagId, long elapsedNanos, long wallClockNanos,
1518 List<StatsLogEventWrapper> pulledData) {
Tej Singh86dc9db2018-09-06 00:39:57 +00001519 try {
1520 String jsonStr = IoUtils.readFileAsString(DiskStatsLoggingService.DUMPSYS_CACHE_PATH);
1521 JSONObject json = new JSONObject(jsonStr);
1522 long cacheTime = json.optLong(DiskStatsFileLogger.LAST_QUERY_TIMESTAMP_KEY, -1L);
1523
Chenjie Yu12e5e672018-09-14 15:54:59 -07001524 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001525 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_SIZE);
1526 e.writeLong(json.optLong(DiskStatsFileLogger.APP_SIZE_AGG_KEY, -1L));
1527 e.writeLong(cacheTime);
1528 pulledData.add(e);
1529
Chenjie Yu12e5e672018-09-14 15:54:59 -07001530 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001531 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_DATA_SIZE);
1532 e.writeLong(json.optLong(DiskStatsFileLogger.APP_DATA_SIZE_AGG_KEY, -1L));
1533 e.writeLong(cacheTime);
1534 pulledData.add(e);
1535
Chenjie Yu12e5e672018-09-14 15:54:59 -07001536 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001537 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_CACHE_SIZE);
1538 e.writeLong(json.optLong(DiskStatsFileLogger.APP_CACHE_AGG_KEY, -1L));
1539 e.writeLong(cacheTime);
1540 pulledData.add(e);
1541
Chenjie Yu12e5e672018-09-14 15:54:59 -07001542 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001543 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__PHOTOS);
1544 e.writeLong(json.optLong(DiskStatsFileLogger.PHOTOS_KEY, -1L));
1545 e.writeLong(cacheTime);
1546 pulledData.add(e);
1547
Chenjie Yu12e5e672018-09-14 15:54:59 -07001548 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001549 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__VIDEOS);
1550 e.writeLong(json.optLong(DiskStatsFileLogger.VIDEOS_KEY, -1L));
1551 e.writeLong(cacheTime);
1552 pulledData.add(e);
1553
Chenjie Yu12e5e672018-09-14 15:54:59 -07001554 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001555 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__AUDIO);
1556 e.writeLong(json.optLong(DiskStatsFileLogger.AUDIO_KEY, -1L));
1557 e.writeLong(cacheTime);
1558 pulledData.add(e);
1559
Chenjie Yu12e5e672018-09-14 15:54:59 -07001560 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001561 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__DOWNLOADS);
1562 e.writeLong(json.optLong(DiskStatsFileLogger.DOWNLOADS_KEY, -1L));
1563 e.writeLong(cacheTime);
1564 pulledData.add(e);
1565
Chenjie Yu12e5e672018-09-14 15:54:59 -07001566 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001567 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__SYSTEM);
1568 e.writeLong(json.optLong(DiskStatsFileLogger.SYSTEM_KEY, -1L));
1569 e.writeLong(cacheTime);
1570 pulledData.add(e);
1571
Chenjie Yu12e5e672018-09-14 15:54:59 -07001572 e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singh86dc9db2018-09-06 00:39:57 +00001573 e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__OTHER);
1574 e.writeLong(json.optLong(DiskStatsFileLogger.MISC_KEY, -1L));
1575 e.writeLong(cacheTime);
1576 pulledData.add(e);
1577 } catch (IOException | JSONException e) {
1578 Slog.e(TAG, "exception reading diskstats cache file", e);
1579 }
1580 }
1581
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001582 private void pullNumBiometricsEnrolled(int modality, int tagId, long elapsedNanos,
1583 long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
Kevin Chynb602c452019-04-10 14:05:54 -07001584 final PackageManager pm = mContext.getPackageManager();
1585 FingerprintManager fingerprintManager = null;
1586 FaceManager faceManager = null;
1587
1588 if (pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
1589 fingerprintManager = mContext.getSystemService(
1590 FingerprintManager.class);
1591 }
1592 if (pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
1593 faceManager = mContext.getSystemService(FaceManager.class);
1594 }
1595
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001596 if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT && fingerprintManager == null) {
1597 return;
1598 }
1599 if (modality == BiometricsProtoEnums.MODALITY_FACE && faceManager == null) {
Tej Singhd6d6d772018-09-05 17:41:25 -07001600 return;
1601 }
1602 UserManager userManager = mContext.getSystemService(UserManager.class);
1603 if (userManager == null) {
1604 return;
1605 }
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001606
Tej Singhd6d6d772018-09-05 17:41:25 -07001607 final long token = Binder.clearCallingIdentity();
Tej Singhd6d6d772018-09-05 17:41:25 -07001608 for (UserInfo user : userManager.getUsers()) {
1609 final int userId = user.getUserHandle().getIdentifier();
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001610 int numEnrolled = 0;
1611 if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT) {
1612 numEnrolled = fingerprintManager.getEnrolledFingerprints(userId).size();
1613 } else if (modality == BiometricsProtoEnums.MODALITY_FACE) {
1614 numEnrolled = faceManager.getEnrolledFaces(userId).size();
1615 } else {
1616 return;
1617 }
Chenjie Yu12e5e672018-09-14 15:54:59 -07001618 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Tej Singhd6d6d772018-09-05 17:41:25 -07001619 e.writeInt(userId);
Kevin Chyn6ecc5702019-01-28 12:00:37 -08001620 e.writeInt(numEnrolled);
Tej Singhd6d6d772018-09-05 17:41:25 -07001621 pulledData.add(e);
1622 }
1623 Binder.restoreCallingIdentity(token);
1624 }
1625
Chenjie Yub52779e2018-10-05 12:03:36 -07001626 // read high watermark for section
1627 private long readProcStatsHighWaterMark(int section) {
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001628 try {
Chenjie Yub52779e2018-10-05 12:03:36 -07001629 File[] files = mBaseDir.listFiles((d, name) -> {
1630 return name.toLowerCase().startsWith(String.valueOf(section) + '_');
1631 });
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001632 if (files == null || files.length == 0) {
1633 return 0;
1634 }
1635 if (files.length > 1) {
1636 Log.e(TAG, "Only 1 file expected for high water mark. Found " + files.length);
1637 }
Chenjie Yub52779e2018-10-05 12:03:36 -07001638 return Long.valueOf(files[0].getName().split("_")[1]);
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001639 } catch (SecurityException e) {
1640 Log.e(TAG, "Failed to get procstats high watermark file.", e);
1641 } catch (NumberFormatException e) {
1642 Log.e(TAG, "Failed to parse file name.", e);
1643 }
1644 return 0;
1645 }
1646
1647 private IProcessStats mProcessStats =
1648 IProcessStats.Stub.asInterface(ServiceManager.getService(ProcessStats.SERVICE_NAME));
1649
Chenjie Yub52779e2018-10-05 12:03:36 -07001650 private void pullProcessStats(int section, int tagId, long elapsedNanos, long wallClockNanos,
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001651 List<StatsLogEventWrapper> pulledData) {
Yangster-mac95543242018-10-22 11:44:03 -07001652 synchronized (this) {
1653 try {
1654 long lastHighWaterMark = readProcStatsHighWaterMark(section);
1655 List<ParcelFileDescriptor> statsFiles = new ArrayList<>();
1656 long highWaterMark = mProcessStats.getCommittedStats(
1657 lastHighWaterMark, section, true, statsFiles);
1658 if (statsFiles.size() != 1) {
1659 return;
1660 }
1661 InputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(
1662 statsFiles.get(0));
1663 int[] len = new int[1];
1664 byte[] stats = readFully(stream, len);
1665 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1666 wallClockNanos);
1667 e.writeStorage(Arrays.copyOf(stats, len[0]));
1668 pulledData.add(e);
1669 new File(mBaseDir.getAbsolutePath() + "/" + section + "_"
1670 + lastHighWaterMark).delete();
1671 new File(
1672 mBaseDir.getAbsolutePath() + "/" + section + "_"
1673 + highWaterMark).createNewFile();
1674 } catch (IOException e) {
1675 Log.e(TAG, "Getting procstats failed: ", e);
1676 } catch (RemoteException e) {
1677 Log.e(TAG, "Getting procstats failed: ", e);
1678 } catch (SecurityException e) {
1679 Log.e(TAG, "Getting procstats failed: ", e);
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001680 }
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07001681 }
1682 }
1683
1684 static byte[] readFully(InputStream stream, int[] outLen) throws IOException {
1685 int pos = 0;
1686 final int initialAvail = stream.available();
1687 byte[] data = new byte[initialAvail > 0 ? (initialAvail + 1) : 16384];
1688 while (true) {
1689 int amt = stream.read(data, pos, data.length - pos);
1690 if (DEBUG) {
1691 Slog.i(TAG, "Read " + amt + " bytes at " + pos + " of avail " + data.length);
1692 }
1693 if (amt < 0) {
1694 if (DEBUG) {
1695 Slog.i(TAG, "**** FINISHED READING: pos=" + pos + " len=" + data.length);
1696 }
1697 outLen[0] = pos;
1698 return data;
1699 }
1700 pos += amt;
1701 if (pos >= data.length) {
1702 byte[] newData = new byte[pos + 16384];
1703 if (DEBUG) {
1704 Slog.i(TAG, "Copying " + pos + " bytes to new array len " + newData.length);
1705 }
1706 System.arraycopy(data, 0, newData, 0, pos);
1707 data = newData;
1708 }
1709 }
1710 }
1711
Chenjie Yuab530202018-09-26 12:39:20 -07001712 private void pullPowerProfile(
1713 int tagId, long elapsedNanos, long wallClockNanos,
1714 List<StatsLogEventWrapper> pulledData) {
1715 PowerProfile powerProfile = new PowerProfile(mContext);
1716 checkNotNull(powerProfile);
1717
1718 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1719 wallClockNanos);
1720 ProtoOutputStream proto = new ProtoOutputStream();
1721 powerProfile.writeToProto(proto);
1722 proto.flush();
1723 e.writeStorage(proto.getBytes());
1724 pulledData.add(e);
1725 }
1726
Bookatz366a4432018-11-20 09:42:33 -08001727 private void pullBuildInformation(int tagId,
1728 long elapsedNanos, long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1729 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1730 e.writeString(Build.FINGERPRINT);
1731 e.writeString(Build.BRAND);
1732 e.writeString(Build.PRODUCT);
1733 e.writeString(Build.DEVICE);
1734 e.writeString(Build.VERSION.RELEASE);
1735 e.writeString(Build.ID);
1736 e.writeString(Build.VERSION.INCREMENTAL);
1737 e.writeString(Build.TYPE);
1738 e.writeString(Build.TAGS);
1739 pulledData.add(e);
1740 }
1741
Bookatz75ee6042018-11-09 12:27:37 -08001742 private BatteryStatsHelper getBatteryStatsHelper() {
1743 if (mBatteryStatsHelper == null) {
1744 final long callingToken = Binder.clearCallingIdentity();
1745 try {
1746 // clearCallingIdentity required for BatteryStatsHelper.checkWifiOnly().
1747 mBatteryStatsHelper = new BatteryStatsHelper(mContext, false);
1748 } finally {
1749 Binder.restoreCallingIdentity(callingToken);
1750 }
1751 mBatteryStatsHelper.create((Bundle) null);
1752 }
1753 long currentTime = SystemClock.elapsedRealtime();
1754 if (currentTime - mBatteryStatsHelperTimestampMs >= MAX_BATTERY_STATS_HELPER_FREQUENCY_MS) {
1755 // Load BatteryStats and do all the calculations.
1756 mBatteryStatsHelper.refreshStats(BatteryStats.STATS_SINCE_CHARGED, UserHandle.USER_ALL);
1757 // Calculations are done so we don't need to save the raw BatteryStats data in RAM.
1758 mBatteryStatsHelper.clearStats();
1759 mBatteryStatsHelperTimestampMs = currentTime;
1760 }
1761 return mBatteryStatsHelper;
1762 }
1763
Bookatz3dbc13a2018-12-21 12:16:51 -08001764 private long milliAmpHrsToNanoAmpSecs(double mAh) {
1765 final long MILLI_AMP_HR_TO_NANO_AMP_SECS = 1_000_000L * 3600L;
1766 return (long) (mAh * MILLI_AMP_HR_TO_NANO_AMP_SECS + 0.5);
1767 }
1768
Bookatz75ee6042018-11-09 12:27:37 -08001769 private void pullDeviceCalculatedPowerUse(int tagId,
1770 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1771 BatteryStatsHelper bsHelper = getBatteryStatsHelper();
1772 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Bookatz3dbc13a2018-12-21 12:16:51 -08001773 e.writeLong(milliAmpHrsToNanoAmpSecs(bsHelper.getComputedPower()));
Bookatz75ee6042018-11-09 12:27:37 -08001774 pulledData.add(e);
1775 }
1776
1777 private void pullDeviceCalculatedPowerBlameUid(int tagId,
1778 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1779 final List<BatterySipper> sippers = getBatteryStatsHelper().getUsageList();
1780 if (sippers == null) {
1781 return;
1782 }
1783 for (BatterySipper bs : sippers) {
1784 if (bs.drainType != bs.drainType.APP) {
1785 continue;
1786 }
1787 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1788 e.writeInt(bs.uidObj.getUid());
Bookatz3dbc13a2018-12-21 12:16:51 -08001789 e.writeLong(milliAmpHrsToNanoAmpSecs(bs.totalPowerMah));
Bookatz75ee6042018-11-09 12:27:37 -08001790 pulledData.add(e);
1791 }
1792 }
1793
1794 private void pullDeviceCalculatedPowerBlameOther(int tagId,
1795 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1796 final List<BatterySipper> sippers = getBatteryStatsHelper().getUsageList();
1797 if (sippers == null) {
1798 return;
1799 }
1800 for (BatterySipper bs : sippers) {
1801 if (bs.drainType == bs.drainType.APP) {
1802 continue; // This is a separate atom; see pullDeviceCalculatedPowerBlameUid().
1803 }
1804 if (bs.drainType == bs.drainType.USER) {
1805 continue; // This is not supported. We purposefully calculate over USER_ALL.
1806 }
1807 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1808 e.writeInt(bs.drainType.ordinal());
Bookatz3dbc13a2018-12-21 12:16:51 -08001809 e.writeLong(milliAmpHrsToNanoAmpSecs(bs.totalPowerMah));
Bookatz75ee6042018-11-09 12:27:37 -08001810 pulledData.add(e);
1811 }
1812 }
1813
Tej Singhe7726dc2018-09-21 11:42:12 -07001814 private void pullDiskIo(int tagId, long elapsedNanos, final long wallClockNanos,
1815 List<StatsLogEventWrapper> pulledData) {
1816 mStoragedUidIoStatsReader.readAbsolute((uid, fgCharsRead, fgCharsWrite, fgBytesRead,
1817 fgBytesWrite, bgCharsRead, bgCharsWrite, bgBytesRead, bgBytesWrite,
1818 fgFsync, bgFsync) -> {
Chenjie Yuab530202018-09-26 12:39:20 -07001819 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1820 wallClockNanos);
Tej Singhe7726dc2018-09-21 11:42:12 -07001821 e.writeInt(uid);
1822 e.writeLong(fgCharsRead);
1823 e.writeLong(fgCharsWrite);
1824 e.writeLong(fgBytesRead);
1825 e.writeLong(fgBytesWrite);
1826 e.writeLong(bgCharsRead);
1827 e.writeLong(bgCharsWrite);
1828 e.writeLong(bgBytesRead);
1829 e.writeLong(bgBytesWrite);
1830 e.writeLong(fgFsync);
1831 e.writeLong(bgFsync);
1832 pulledData.add(e);
1833 });
1834 }
1835
Yangster-mac308ea0c2018-10-22 13:10:25 -07001836 private void pullProcessCpuTime(int tagId, long elapsedNanos, final long wallClockNanos,
1837 List<StatsLogEventWrapper> pulledData) {
1838 synchronized (this) {
1839 if (mProcessCpuTracker == null) {
1840 mProcessCpuTracker = new ProcessCpuTracker(false);
1841 mProcessCpuTracker.init();
1842 }
1843 mProcessCpuTracker.update();
1844 for (int i = 0; i < mProcessCpuTracker.countStats(); i++) {
1845 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
1846 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
1847 wallClockNanos);
1848 e.writeInt(st.uid);
1849 e.writeString(st.name);
1850 e.writeLong(st.base_utime);
1851 e.writeLong(st.base_stime);
1852 pulledData.add(e);
1853 }
1854 }
1855 }
1856
Misha Wagner5a51e002018-10-03 15:04:09 +01001857 private void pullCpuTimePerThreadFreq(int tagId, long elapsedNanos, long wallClockNanos,
1858 List<StatsLogEventWrapper> pulledData) {
1859 if (this.mKernelCpuThreadReader == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001860 throw new IllegalStateException("mKernelCpuThreadReader is null");
Misha Wagner5a51e002018-10-03 15:04:09 +01001861 }
Misha Wagnerdc797542018-10-29 13:21:34 +00001862 ArrayList<KernelCpuThreadReader.ProcessCpuUsage> processCpuUsages =
Misha Wagner2487d3572019-03-18 17:30:14 +00001863 this.mKernelCpuThreadReader.getProcessCpuUsageDiffed();
Misha Wagnerdc797542018-10-29 13:21:34 +00001864 if (processCpuUsages == null) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001865 throw new IllegalStateException("processCpuUsages is null");
Misha Wagner5a51e002018-10-03 15:04:09 +01001866 }
1867 int[] cpuFrequencies = mKernelCpuThreadReader.getCpuFrequenciesKhz();
Misha Wagner4b32c9f2019-01-25 15:30:14 +00001868 if (cpuFrequencies.length > CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001869 String message = "Expected maximum " + CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES
1870 + " frequencies, but got " + cpuFrequencies.length;
1871 Slog.w(TAG, message);
1872 throw new IllegalStateException(message);
Misha Wagnerfde69582018-11-28 13:26:32 +00001873 }
Misha Wagnerdc797542018-10-29 13:21:34 +00001874 for (int i = 0; i < processCpuUsages.size(); i++) {
1875 KernelCpuThreadReader.ProcessCpuUsage processCpuUsage = processCpuUsages.get(i);
1876 ArrayList<KernelCpuThreadReader.ThreadCpuUsage> threadCpuUsages =
1877 processCpuUsage.threadCpuUsages;
1878 for (int j = 0; j < threadCpuUsages.size(); j++) {
1879 KernelCpuThreadReader.ThreadCpuUsage threadCpuUsage = threadCpuUsages.get(j);
1880 if (threadCpuUsage.usageTimesMillis.length != cpuFrequencies.length) {
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001881 String message = "Unexpected number of usage times,"
Misha Wagnerdc797542018-10-29 13:21:34 +00001882 + " expected " + cpuFrequencies.length
Olivier Gaillard59ed8d12019-02-08 09:52:35 +00001883 + " but got " + threadCpuUsage.usageTimesMillis.length;
1884 Slog.w(TAG, message);
1885 throw new IllegalStateException(message);
Misha Wagner5a51e002018-10-03 15:04:09 +01001886 }
1887
Misha Wagnerfde69582018-11-28 13:26:32 +00001888 StatsLogEventWrapper e =
1889 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1890 e.writeInt(processCpuUsage.uid);
1891 e.writeInt(processCpuUsage.processId);
1892 e.writeInt(threadCpuUsage.threadId);
1893 e.writeString(processCpuUsage.processName);
1894 e.writeString(threadCpuUsage.threadName);
Misha Wagner4b32c9f2019-01-25 15:30:14 +00001895 for (int k = 0; k < CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES; k++) {
1896 if (k < cpuFrequencies.length) {
1897 e.writeInt(cpuFrequencies[k]);
1898 e.writeInt(threadCpuUsage.usageTimesMillis[k]);
1899 } else {
1900 // If we have no more frequencies to write, we still must write empty data.
1901 // We know that this data is empty (and not just zero) because all
1902 // frequencies are expected to be greater than zero
1903 e.writeInt(0);
1904 e.writeInt(0);
1905 }
Misha Wagnerdc797542018-10-29 13:21:34 +00001906 }
Misha Wagnerfde69582018-11-28 13:26:32 +00001907 pulledData.add(e);
Misha Wagner5a51e002018-10-03 15:04:09 +01001908 }
1909 }
1910 }
1911
Tej Singh9876a3b2019-01-11 14:28:35 -08001912 private void pullTemperature(int tagId, long elapsedNanos, long wallClockNanos,
1913 List<StatsLogEventWrapper> pulledData) {
1914 long callingToken = Binder.clearCallingIdentity();
1915 try {
1916 List<Temperature> temperatures = sThermalService.getCurrentTemperatures();
1917 for (Temperature temp : temperatures) {
1918 StatsLogEventWrapper e =
1919 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1920 e.writeInt(temp.getType());
1921 e.writeString(temp.getName());
1922 e.writeInt((int) (temp.getValue() * 10));
Maggie White442b6312019-04-05 16:26:44 -07001923 e.writeInt(temp.getStatus());
1924 pulledData.add(e);
1925 }
1926 } catch (RemoteException e) {
1927 // Should not happen.
1928 Slog.e(TAG, "Disconnected from thermal service. Cannot pull temperatures.");
1929 } finally {
1930 Binder.restoreCallingIdentity(callingToken);
1931 }
1932 }
1933
1934 private void pullCoolingDevices(int tagId, long elapsedNanos, long wallClockNanos,
1935 List<StatsLogEventWrapper> pulledData) {
1936 long callingToken = Binder.clearCallingIdentity();
1937 try {
1938 List<CoolingDevice> devices = sThermalService.getCurrentCoolingDevices();
1939 for (CoolingDevice device : devices) {
1940 StatsLogEventWrapper e =
1941 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1942 e.writeInt(device.getType());
1943 e.writeString(device.getName());
1944 e.writeInt((int) (device.getValue()));
Tej Singh9876a3b2019-01-11 14:28:35 -08001945 pulledData.add(e);
1946 }
1947 } catch (RemoteException e) {
1948 // Should not happen.
1949 Slog.e(TAG, "Disconnected from thermal service. Cannot pull temperatures.");
1950 } finally {
1951 Binder.restoreCallingIdentity(callingToken);
1952 }
1953 }
1954
Olivier Gaillard18d452202019-01-22 15:03:41 +00001955 private void pullDebugElapsedClock(int tagId,
1956 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1957 final long elapsedMillis = SystemClock.elapsedRealtime();
1958 final long clockDiffMillis = mDebugElapsedClockPreviousValue == 0
1959 ? 0 : elapsedMillis - mDebugElapsedClockPreviousValue;
1960
1961 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1962 e.writeLong(mDebugElapsedClockPullCount);
1963 e.writeLong(elapsedMillis);
1964 // Log it twice to be able to test multi-value aggregation from ValueMetric.
1965 e.writeLong(elapsedMillis);
1966 e.writeLong(clockDiffMillis);
1967 e.writeInt(1 /* always set */);
1968 pulledData.add(e);
1969
1970 if (mDebugElapsedClockPullCount % 2 == 1) {
1971 StatsLogEventWrapper e2 = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1972 e2.writeLong(mDebugElapsedClockPullCount);
1973 e2.writeLong(elapsedMillis);
1974 // Log it twice to be able to test multi-value aggregation from ValueMetric.
1975 e2.writeLong(elapsedMillis);
1976 e2.writeLong(clockDiffMillis);
1977 e2.writeInt(2 /* set on odd pulls */);
1978 pulledData.add(e2);
1979 }
1980
1981 mDebugElapsedClockPullCount++;
1982 mDebugElapsedClockPreviousValue = elapsedMillis;
1983 }
1984
1985 private void pullDebugFailingElapsedClock(int tagId,
1986 long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
1987 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
1988 final long elapsedMillis = SystemClock.elapsedRealtime();
Olivier Gaillard4f01a372019-02-04 14:25:14 +00001989 // Fails every 5 buckets.
1990 if (mDebugFailingElapsedClockPullCount++ % 5 == 0) {
Olivier Gaillard18d452202019-01-22 15:03:41 +00001991 mDebugFailingElapsedClockPreviousValue = elapsedMillis;
1992 throw new RuntimeException("Failing debug elapsed clock");
1993 }
1994
1995 e.writeLong(mDebugFailingElapsedClockPullCount);
1996 e.writeLong(elapsedMillis);
1997 // Log it twice to be able to test multi-value aggregation from ValueMetric.
1998 e.writeLong(elapsedMillis);
1999 e.writeLong(mDebugFailingElapsedClockPreviousValue == 0
2000 ? 0 : elapsedMillis - mDebugFailingElapsedClockPreviousValue);
2001 mDebugFailingElapsedClockPreviousValue = elapsedMillis;
2002 pulledData.add(e);
2003 }
2004
Philip P. Moltmannf21a3502019-01-30 09:53:04 -08002005 private void pullDangerousPermissionState(long elapsedNanos, final long wallClockNanos,
2006 List<StatsLogEventWrapper> pulledData) {
2007 long token = Binder.clearCallingIdentity();
2008 try {
2009 PackageManager pm = mContext.getPackageManager();
2010
2011 List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
2012
2013 int numUsers = users.size();
2014 for (int userNum = 0; userNum < numUsers; userNum++) {
2015 UserHandle user = users.get(userNum).getUserHandle();
2016
2017 List<PackageInfo> pkgs = pm.getInstalledPackagesAsUser(
2018 PackageManager.GET_PERMISSIONS, user.getIdentifier());
2019
2020 int numPkgs = pkgs.size();
2021 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
2022 PackageInfo pkg = pkgs.get(pkgNum);
2023
2024 if (pkg.requestedPermissions == null) {
2025 continue;
2026 }
2027
2028 int numPerms = pkg.requestedPermissions.length;
2029 for (int permNum = 0; permNum < numPerms; permNum++) {
2030 String permName = pkg.requestedPermissions[permNum];
2031
2032 PermissionInfo permissionInfo;
Stanislav Zholnin75c3fd12019-05-21 13:10:51 +01002033 int permissionFlags = 0;
Philip P. Moltmannf21a3502019-01-30 09:53:04 -08002034 try {
2035 permissionInfo = pm.getPermissionInfo(permName, 0);
Stanislav Zholnin75c3fd12019-05-21 13:10:51 +01002036 permissionFlags =
2037 pm.getPermissionFlags(permName, pkg.packageName, user);
2038
Philip P. Moltmannf21a3502019-01-30 09:53:04 -08002039 } catch (PackageManager.NameNotFoundException ignored) {
2040 continue;
2041 }
2042
2043 if (permissionInfo.getProtection() != PROTECTION_DANGEROUS) {
2044 continue;
2045 }
2046
2047 StatsLogEventWrapper e = new StatsLogEventWrapper(
2048 StatsLog.DANGEROUS_PERMISSION_STATE, elapsedNanos, wallClockNanos);
2049
2050 e.writeString(permName);
2051 e.writeInt(pkg.applicationInfo.uid);
2052 e.writeString(pkg.packageName);
Philip P. Moltmannf21a3502019-01-30 09:53:04 -08002053 e.writeBoolean((pkg.requestedPermissionsFlags[permNum]
2054 & REQUESTED_PERMISSION_GRANTED) != 0);
Summer Jianga652e272019-06-19 16:12:38 -07002055 e.writeInt(permissionFlags);
Philip P. Moltmannf21a3502019-01-30 09:53:04 -08002056
2057 pulledData.add(e);
2058 }
2059 }
2060 }
2061 } catch (Throwable t) {
2062 Log.e(TAG, "Could not read permissions", t);
2063 } finally {
2064 Binder.restoreCallingIdentity(token);
2065 }
2066 }
2067
Martijn Coenencd95d462019-04-25 17:09:45 +02002068 private void pullAppOps(long elapsedNanos, final long wallClockNanos,
2069 List<StatsLogEventWrapper> pulledData) {
2070 long token = Binder.clearCallingIdentity();
2071 try {
2072 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
2073
2074 CompletableFuture<HistoricalOps> ops = new CompletableFuture<>();
2075 HistoricalOpsRequest histOpsRequest =
Stanislav Zholnina822bc12019-10-28 12:28:12 +00002076 new HistoricalOpsRequest.Builder(0, Long.MAX_VALUE).build();
Martijn Coenencd95d462019-04-25 17:09:45 +02002077 appOps.getHistoricalOps(histOpsRequest, mContext.getMainExecutor(), ops::complete);
2078
2079 HistoricalOps histOps = ops.get(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS,
2080 TimeUnit.MILLISECONDS);
2081
Martijn Coenencd95d462019-04-25 17:09:45 +02002082 for (int uidIdx = 0; uidIdx < histOps.getUidCount(); uidIdx++) {
2083 final HistoricalUidOps uidOps = histOps.getUidOpsAt(uidIdx);
2084 final int uid = uidOps.getUid();
2085 for (int pkgIdx = 0; pkgIdx < uidOps.getPackageCount(); pkgIdx++) {
2086 final HistoricalPackageOps packageOps = uidOps.getPackageOpsAt(pkgIdx);
2087 for (int opIdx = 0; opIdx < packageOps.getOpCount(); opIdx++) {
2088 final AppOpsManager.HistoricalOp op = packageOps.getOpAt(opIdx);
Stanislav Zholnina700d282019-10-02 17:14:10 +01002089 StatsLogEventWrapper e = new StatsLogEventWrapper(StatsLog.APP_OPS,
2090 elapsedNanos, wallClockNanos);
2091
Martijn Coenencd95d462019-04-25 17:09:45 +02002092 e.writeInt(uid);
2093 e.writeString(packageOps.getPackageName());
2094 e.writeInt(op.getOpCode());
2095 e.writeLong(op.getForegroundAccessCount(OP_FLAGS_ALL_TRUSTED));
2096 e.writeLong(op.getBackgroundAccessCount(OP_FLAGS_ALL_TRUSTED));
2097 e.writeLong(op.getForegroundRejectCount(OP_FLAGS_ALL_TRUSTED));
2098 e.writeLong(op.getBackgroundRejectCount(OP_FLAGS_ALL_TRUSTED));
2099 e.writeLong(op.getForegroundAccessDuration(OP_FLAGS_ALL_TRUSTED));
2100 e.writeLong(op.getBackgroundAccessDuration(OP_FLAGS_ALL_TRUSTED));
2101 pulledData.add(e);
2102 }
2103 }
2104 }
2105 } catch (Throwable t) {
2106 Log.e(TAG, "Could not read appops", t);
2107 } finally {
2108 Binder.restoreCallingIdentity(token);
2109 }
2110 }
2111
2112
Chenjie Yu05013b32017-11-21 10:21:41 -08002113 /**
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08002114 * Add a RoleHolder atom for each package that holds a role.
2115 *
2116 * @param elapsedNanos the time since boot
2117 * @param wallClockNanos the time on the clock
2118 * @param pulledData the data sink to write to
2119 */
2120 private void pullRoleHolders(long elapsedNanos, final long wallClockNanos,
2121 @NonNull List<StatsLogEventWrapper> pulledData) {
2122 long callingToken = Binder.clearCallingIdentity();
2123 try {
2124 PackageManager pm = mContext.getPackageManager();
Hai Zhang85fd0622019-02-01 14:06:04 -08002125 RoleManagerInternal rmi = LocalServices.getService(RoleManagerInternal.class);
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08002126
2127 List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
2128
2129 int numUsers = users.size();
2130 for (int userNum = 0; userNum < numUsers; userNum++) {
Hai Zhang85fd0622019-02-01 14:06:04 -08002131 int userId = users.get(userNum).getUserHandle().getIdentifier();
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08002132
Hai Zhang85fd0622019-02-01 14:06:04 -08002133 ArrayMap<String, ArraySet<String>> roles = rmi.getRolesAndHolders(
2134 userId);
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08002135
2136 int numRoles = roles.size();
2137 for (int roleNum = 0; roleNum < numRoles; roleNum++) {
2138 String roleName = roles.keyAt(roleNum);
2139 ArraySet<String> holders = roles.valueAt(roleNum);
2140
2141 int numHolders = holders.size();
2142 for (int holderNum = 0; holderNum < numHolders; holderNum++) {
2143 String holderName = holders.valueAt(holderNum);
2144
2145 PackageInfo pkg;
2146 try {
Hai Zhang85fd0622019-02-01 14:06:04 -08002147 pkg = pm.getPackageInfoAsUser(holderName, 0, userId);
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08002148 } catch (PackageManager.NameNotFoundException e) {
2149 Log.w(TAG, "Role holder " + holderName + " not found");
2150 return;
2151 }
2152
2153 StatsLogEventWrapper e = new StatsLogEventWrapper(StatsLog.ROLE_HOLDER,
2154 elapsedNanos, wallClockNanos);
2155 e.writeInt(pkg.applicationInfo.uid);
2156 e.writeString(holderName);
2157 e.writeString(roleName);
2158 pulledData.add(e);
2159 }
2160 }
2161 }
2162 } finally {
2163 Binder.restoreCallingIdentity(callingToken);
2164 }
2165 }
2166
Neil Fullerdb14b482019-02-05 19:44:44 +00002167 private void pullTimeZoneDataInfo(int tagId,
2168 long elapsedNanos, long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
2169 String tzDbVersion = "Unknown";
2170 try {
2171 tzDbVersion = android.icu.util.TimeZone.getTZDataVersion();
2172 } catch (Exception e) {
2173 Log.e(TAG, "Getting tzdb version failed: ", e);
2174 }
2175
2176 StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
2177 e.writeString(tzDbVersion);
2178 pulledData.add(e);
2179 }
2180
Carmen Agimof12dec122019-03-06 16:14:38 +00002181 private void pullExternalStorageInfo(int tagId, long elapsedNanos, long wallClockNanos,
Carmen Agimof35f7f6f2019-02-05 18:19:21 +00002182 List<StatsLogEventWrapper> pulledData) {
2183 StorageManager storageManager = mContext.getSystemService(StorageManager.class);
2184 if (storageManager != null) {
2185 List<VolumeInfo> volumes = storageManager.getVolumes();
2186 for (VolumeInfo vol : volumes) {
2187 final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
2188 final DiskInfo diskInfo = vol.getDisk();
Carmen Agimof12dec122019-03-06 16:14:38 +00002189 if (diskInfo != null) {
Carmen Agimof35f7f6f2019-02-05 18:19:21 +00002190 if (envState.equals(Environment.MEDIA_MOUNTED)) {
Carmen Agimof12dec122019-03-06 16:14:38 +00002191 // Get the type of the volume, if it is adoptable or portable.
2192 int volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__OTHER;
2193 if (vol.getType() == TYPE_PUBLIC) {
2194 volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__PUBLIC;
2195 } else if (vol.getType() == TYPE_PRIVATE) {
2196 volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__PRIVATE;
2197 }
2198 // Get the type of external storage inserted in the device (sd cards,
2199 // usb, etc)
2200 int externalStorageType;
2201 if (diskInfo.isSd()) {
2202 externalStorageType = StorageEnums.SD_CARD;
2203 } else if (diskInfo.isUsb()) {
2204 externalStorageType = StorageEnums.USB;
2205 } else {
2206 externalStorageType = StorageEnums.OTHER;
2207 }
Carmen Agimof35f7f6f2019-02-05 18:19:21 +00002208 StatsLogEventWrapper e =
2209 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
Carmen Agimof12dec122019-03-06 16:14:38 +00002210 e.writeInt(externalStorageType);
2211 e.writeInt(volumeType);
Carmen Agimof35f7f6f2019-02-05 18:19:21 +00002212 e.writeLong(diskInfo.size);
2213 pulledData.add(e);
2214 }
2215 }
2216 }
2217 }
2218 }
2219
Carmen Agimofa769c152019-03-04 14:39:14 +00002220 private void pullAppsOnExternalStorageInfo(int tagId, long elapsedNanos, long wallClockNanos,
2221 List<StatsLogEventWrapper> pulledData) {
2222 PackageManager pm = mContext.getPackageManager();
2223 StorageManager storage = mContext.getSystemService(StorageManager.class);
2224 List<ApplicationInfo> apps = pm.getInstalledApplications(/* flags = */ 0);
2225 for (ApplicationInfo appInfo : apps) {
2226 UUID storageUuid = appInfo.storageUuid;
2227 if (storageUuid != null) {
2228 VolumeInfo volumeInfo = storage.findVolumeByUuid(appInfo.storageUuid.toString());
2229 if (volumeInfo != null) {
2230 DiskInfo diskInfo = volumeInfo.getDisk();
2231 if (diskInfo != null) {
2232 int externalStorageType = -1;
2233 if (diskInfo.isSd()) {
2234 externalStorageType = StorageEnums.SD_CARD;
2235 } else if (diskInfo.isUsb()) {
2236 externalStorageType = StorageEnums.USB;
2237 } else if (appInfo.isExternal()) {
2238 externalStorageType = StorageEnums.OTHER;
2239 }
2240 // App is installed on external storage.
2241 if (externalStorageType != -1) {
2242 StatsLogEventWrapper e =
2243 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
2244 e.writeInt(externalStorageType);
2245 e.writeString(appInfo.packageName);
2246 pulledData.add(e);
2247 }
2248 }
2249 }
2250 }
2251 }
2252 }
2253
joshmccloskey34c1f8e2019-04-11 14:06:43 -07002254 private void pullFaceSettings(int tagId, long elapsedNanos, long wallClockNanos,
2255 List<StatsLogEventWrapper> pulledData) {
2256 long callingToken = Binder.clearCallingIdentity();
2257 try {
2258 List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
2259 int numUsers = users.size();
2260 for (int userNum = 0; userNum < numUsers; userNum++) {
2261 int userId = users.get(userNum).getUserHandle().getIdentifier();
2262
2263 StatsLogEventWrapper e =
2264 new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
2265 e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
2266 Settings.Secure.FACE_UNLOCK_KEYGUARD_ENABLED, 1,
2267 userId) != 0);
2268 e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
2269 Settings.Secure.FACE_UNLOCK_DISMISSES_KEYGUARD,
2270 0, userId) != 0);
2271 e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
2272 Settings.Secure.FACE_UNLOCK_ATTENTION_REQUIRED, 1,
2273 userId) != 0);
2274 e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
2275 Settings.Secure.FACE_UNLOCK_APP_ENABLED, 1,
2276 userId) != 0);
2277 e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
2278 Settings.Secure.FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION, 0,
2279 userId) != 0);
Kevin Chync78071f2019-04-15 14:11:58 -07002280 e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
2281 Settings.Secure.FACE_UNLOCK_DIVERSITY_REQUIRED, 1,
2282 userId) != 0);
joshmccloskey34c1f8e2019-04-11 14:06:43 -07002283
2284 pulledData.add(e);
2285 }
2286 } finally {
2287 Binder.restoreCallingIdentity(callingToken);
2288 }
2289 }
2290
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08002291 /**
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002292 * Pulls various data.
Chenjie Yu05013b32017-11-21 10:21:41 -08002293 */
Bookatzc68a9d22017-09-27 14:09:55 -07002294 @Override // Binder call
Chenjie Yu5305e1d2017-10-31 13:49:36 -07002295 public StatsLogEventWrapper[] pullData(int tagId) {
Bookatzc68a9d22017-09-27 14:09:55 -07002296 enforceCallingPermission();
Chenjie Yu12e5e672018-09-14 15:54:59 -07002297 if (DEBUG) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -07002298 Slog.d(TAG, "Pulling " + tagId);
Chenjie Yu12e5e672018-09-14 15:54:59 -07002299 }
Rajeev Kumar22d92b72018-02-07 18:38:36 -08002300 List<StatsLogEventWrapper> ret = new ArrayList<>();
Chenjie Yu12e5e672018-09-14 15:54:59 -07002301 long elapsedNanos = SystemClock.elapsedRealtimeNanos();
2302 long wallClockNanos = SystemClock.currentTimeMicro() * 1000L;
Chenjie Yu5305e1d2017-10-31 13:49:36 -07002303 switch (tagId) {
Chenjie Yu31d14d72017-12-12 17:54:33 -08002304 case StatsLog.WIFI_BYTES_TRANSFER: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002305 pullWifiBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002306 break;
David Chenc8a43242017-10-17 16:23:28 -07002307 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002308 case StatsLog.MOBILE_BYTES_TRANSFER: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002309 pullMobileBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002310 break;
David Chenc8a43242017-10-17 16:23:28 -07002311 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002312 case StatsLog.WIFI_BYTES_TRANSFER_BY_FG_BG: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002313 pullWifiBytesTransferByFgBg(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002314 break;
David Chenc8a43242017-10-17 16:23:28 -07002315 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002316 case StatsLog.MOBILE_BYTES_TRANSFER_BY_FG_BG: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002317 pullMobileBytesTransferByFgBg(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002318 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002319 }
2320 case StatsLog.BLUETOOTH_BYTES_TRANSFER: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002321 pullBluetoothBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002322 break;
David Chenc8a43242017-10-17 16:23:28 -07002323 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002324 case StatsLog.KERNEL_WAKELOCK: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002325 pullKernelWakelock(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002326 break;
David Chen1481fe12017-10-16 13:16:34 -07002327 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002328 case StatsLog.CPU_TIME_PER_FREQ: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002329 pullCpuTimePerFreq(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002330 break;
Chenjie Yu7f8def92017-11-03 09:33:15 -07002331 }
Chenjie Yuec676612018-03-07 09:19:17 -08002332 case StatsLog.CPU_TIME_PER_UID: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002333 pullKernelUidCpuTime(tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yuec676612018-03-07 09:19:17 -08002334 break;
2335 }
2336 case StatsLog.CPU_TIME_PER_UID_FREQ: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002337 pullKernelUidCpuFreqTime(tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yuec676612018-03-07 09:19:17 -08002338 break;
2339 }
2340 case StatsLog.CPU_CLUSTER_TIME: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002341 pullKernelUidCpuClusterTime(tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yuec676612018-03-07 09:19:17 -08002342 break;
2343 }
2344 case StatsLog.CPU_ACTIVE_TIME: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002345 pullKernelUidCpuActiveTime(tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yuec676612018-03-07 09:19:17 -08002346 break;
2347 }
Chenjie Yu5caaa9d2018-03-06 15:48:54 -08002348 case StatsLog.WIFI_ACTIVITY_INFO: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002349 pullWifiActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002350 break;
Chenjie Yu05013b32017-11-21 10:21:41 -08002351 }
Chenjie Yu31d14d72017-12-12 17:54:33 -08002352 case StatsLog.MODEM_ACTIVITY_INFO: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002353 pullModemActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002354 break;
Chenjie Yu05013b32017-11-21 10:21:41 -08002355 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002356 case StatsLog.BLUETOOTH_ACTIVITY_INFO: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002357 pullBluetoothActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002358 break;
Chenjie Yu937d7422018-01-10 16:37:53 -08002359 }
2360 case StatsLog.SYSTEM_UPTIME: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002361 pullSystemUpTime(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002362 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002363 }
2364 case StatsLog.SYSTEM_ELAPSED_REALTIME: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002365 pullSystemElapsedRealtime(tagId, elapsedNanos, wallClockNanos, ret);
David Chen661f7912018-01-22 17:46:24 -08002366 break;
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002367 }
Rajeev Kumar22d92b72018-02-07 18:38:36 -08002368 case StatsLog.PROCESS_MEMORY_STATE: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002369 pullProcessMemoryState(tagId, elapsedNanos, wallClockNanos, ret);
Rajeev Kumar22d92b72018-02-07 18:38:36 -08002370 break;
2371 }
Rafal Slawik3bea8952018-11-15 12:39:33 +00002372 case StatsLog.PROCESS_MEMORY_HIGH_WATER_MARK: {
2373 pullProcessMemoryHighWaterMark(tagId, elapsedNanos, wallClockNanos, ret);
2374 break;
2375 }
Rafal Slawik7efcefb2019-09-20 11:16:20 +01002376 case StatsLog.PROCESS_MEMORY_SNAPSHOT: {
2377 pullProcessMemorySnapshot(tagId, elapsedNanos, wallClockNanos, ret);
2378 break;
2379 }
Rafal Slawikd4e87572019-03-12 13:08:38 +00002380 case StatsLog.SYSTEM_ION_HEAP_SIZE: {
2381 pullSystemIonHeapSize(tagId, elapsedNanos, wallClockNanos, ret);
2382 break;
2383 }
Rafal Slawik77987ed2019-06-17 12:28:23 +01002384 case StatsLog.PROCESS_SYSTEM_ION_HEAP_SIZE: {
2385 pullProcessSystemIonHeapSize(tagId, elapsedNanos, wallClockNanos, ret);
2386 break;
2387 }
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01002388 case StatsLog.BINDER_CALLS: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002389 pullBinderCallsStats(tagId, elapsedNanos, wallClockNanos, ret);
Olivier Gaillard00bfb1b2018-07-10 11:25:09 +01002390 break;
2391 }
Olivier Gaillard6f52d152018-07-25 12:13:12 +01002392 case StatsLog.BINDER_CALLS_EXCEPTIONS: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002393 pullBinderCallsStatsExceptions(tagId, elapsedNanos, wallClockNanos, ret);
Olivier Gaillard6f52d152018-07-25 12:13:12 +01002394 break;
2395 }
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01002396 case StatsLog.LOOPER_STATS: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002397 pullLooperStats(tagId, elapsedNanos, wallClockNanos, ret);
Marcin Oczeretkod8cc8592018-08-22 16:07:36 +01002398 break;
2399 }
Tej Singh86dc9db2018-09-06 00:39:57 +00002400 case StatsLog.DISK_STATS: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002401 pullDiskStats(tagId, elapsedNanos, wallClockNanos, ret);
Tej Singh86dc9db2018-09-06 00:39:57 +00002402 break;
2403 }
2404 case StatsLog.DIRECTORY_USAGE: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002405 pullDirectoryUsage(tagId, elapsedNanos, wallClockNanos, ret);
Tej Singh86dc9db2018-09-06 00:39:57 +00002406 break;
2407 }
2408 case StatsLog.APP_SIZE: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002409 pullAppSize(tagId, elapsedNanos, wallClockNanos, ret);
Tej Singh86dc9db2018-09-06 00:39:57 +00002410 break;
2411 }
2412 case StatsLog.CATEGORY_SIZE: {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002413 pullCategorySize(tagId, elapsedNanos, wallClockNanos, ret);
Tej Singh86dc9db2018-09-06 00:39:57 +00002414 break;
2415 }
Kevin Chyn1741a072019-01-17 11:54:40 -08002416 case StatsLog.NUM_FINGERPRINTS_ENROLLED: {
Kevin Chyn6ecc5702019-01-28 12:00:37 -08002417 pullNumBiometricsEnrolled(BiometricsProtoEnums.MODALITY_FINGERPRINT, tagId,
2418 elapsedNanos, wallClockNanos, ret);
2419 break;
2420 }
2421 case StatsLog.NUM_FACES_ENROLLED: {
2422 pullNumBiometricsEnrolled(BiometricsProtoEnums.MODALITY_FACE, tagId, elapsedNanos,
2423 wallClockNanos, ret);
Tej Singhd6d6d772018-09-05 17:41:25 -07002424 break;
2425 }
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002426 case StatsLog.PROC_STATS: {
Yang Lu1587e132018-10-22 16:19:40 +00002427 pullProcessStats(ProcessStats.REPORT_ALL, tagId, elapsedNanos, wallClockNanos, ret);
Chenjie Yub52779e2018-10-05 12:03:36 -07002428 break;
2429 }
2430 case StatsLog.PROC_STATS_PKG_PROC: {
2431 pullProcessStats(ProcessStats.REPORT_PKG_PROC_STATS, tagId, elapsedNanos,
2432 wallClockNanos, ret);
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002433 break;
2434 }
Tej Singhe7726dc2018-09-21 11:42:12 -07002435 case StatsLog.DISK_IO: {
2436 pullDiskIo(tagId, elapsedNanos, wallClockNanos, ret);
2437 break;
2438 }
Chenjie Yuab530202018-09-26 12:39:20 -07002439 case StatsLog.POWER_PROFILE: {
2440 pullPowerProfile(tagId, elapsedNanos, wallClockNanos, ret);
2441 break;
2442 }
Bookatz366a4432018-11-20 09:42:33 -08002443 case StatsLog.BUILD_INFORMATION: {
2444 pullBuildInformation(tagId, elapsedNanos, wallClockNanos, ret);
2445 break;
2446 }
Yangster-mac308ea0c2018-10-22 13:10:25 -07002447 case StatsLog.PROCESS_CPU_TIME: {
2448 pullProcessCpuTime(tagId, elapsedNanos, wallClockNanos, ret);
2449 break;
2450 }
Misha Wagner5a51e002018-10-03 15:04:09 +01002451 case StatsLog.CPU_TIME_PER_THREAD_FREQ: {
2452 pullCpuTimePerThreadFreq(tagId, elapsedNanos, wallClockNanos, ret);
2453 break;
2454 }
Bookatz75ee6042018-11-09 12:27:37 -08002455 case StatsLog.DEVICE_CALCULATED_POWER_USE: {
2456 pullDeviceCalculatedPowerUse(tagId, elapsedNanos, wallClockNanos, ret);
2457 break;
2458 }
2459 case StatsLog.DEVICE_CALCULATED_POWER_BLAME_UID: {
2460 pullDeviceCalculatedPowerBlameUid(tagId, elapsedNanos, wallClockNanos, ret);
2461 break;
2462 }
2463 case StatsLog.DEVICE_CALCULATED_POWER_BLAME_OTHER: {
2464 pullDeviceCalculatedPowerBlameOther(tagId, elapsedNanos, wallClockNanos, ret);
2465 break;
2466 }
Tej Singh9876a3b2019-01-11 14:28:35 -08002467 case StatsLog.TEMPERATURE: {
2468 pullTemperature(tagId, elapsedNanos, wallClockNanos, ret);
2469 break;
2470 }
Maggie White442b6312019-04-05 16:26:44 -07002471 case StatsLog.COOLING_DEVICE: {
2472 pullCoolingDevices(tagId, elapsedNanos, wallClockNanos, ret);
2473 break;
2474 }
Olivier Gaillard18d452202019-01-22 15:03:41 +00002475 case StatsLog.DEBUG_ELAPSED_CLOCK: {
2476 pullDebugElapsedClock(tagId, elapsedNanos, wallClockNanos, ret);
2477 break;
2478 }
2479 case StatsLog.DEBUG_FAILING_ELAPSED_CLOCK: {
2480 pullDebugFailingElapsedClock(tagId, elapsedNanos, wallClockNanos, ret);
2481 break;
2482 }
Philip P. Moltmann70b42ae2019-01-29 16:24:19 -08002483 case StatsLog.ROLE_HOLDER: {
2484 pullRoleHolders(elapsedNanos, wallClockNanos, ret);
2485 break;
2486 }
Philip P. Moltmannf21a3502019-01-30 09:53:04 -08002487 case StatsLog.DANGEROUS_PERMISSION_STATE: {
2488 pullDangerousPermissionState(elapsedNanos, wallClockNanos, ret);
2489 break;
2490 }
Neil Fullerdb14b482019-02-05 19:44:44 +00002491 case StatsLog.TIME_ZONE_DATA_INFO: {
2492 pullTimeZoneDataInfo(tagId, elapsedNanos, wallClockNanos, ret);
2493 break;
2494 }
Carmen Agimof12dec122019-03-06 16:14:38 +00002495 case StatsLog.EXTERNAL_STORAGE_INFO: {
2496 pullExternalStorageInfo(tagId, elapsedNanos, wallClockNanos, ret);
Carmen Agimof35f7f6f2019-02-05 18:19:21 +00002497 break;
2498 }
Carmen Agimofa769c152019-03-04 14:39:14 +00002499 case StatsLog.APPS_ON_EXTERNAL_STORAGE_INFO: {
2500 pullAppsOnExternalStorageInfo(tagId, elapsedNanos, wallClockNanos, ret);
2501 break;
2502 }
joshmccloskey34c1f8e2019-04-11 14:06:43 -07002503 case StatsLog.FACE_SETTINGS: {
2504 pullFaceSettings(tagId, elapsedNanos, wallClockNanos, ret);
2505 break;
2506 }
Martijn Coenencd95d462019-04-25 17:09:45 +02002507 case StatsLog.APP_OPS: {
2508 pullAppOps(elapsedNanos, wallClockNanos, ret);
2509 break;
2510 }
Bookatzc68a9d22017-09-27 14:09:55 -07002511 default:
Chenjie Yu5305e1d2017-10-31 13:49:36 -07002512 Slog.w(TAG, "No such tagId data as " + tagId);
Bookatzc68a9d22017-09-27 14:09:55 -07002513 return null;
2514 }
Chenjie Yu9d7720b2018-01-24 10:34:48 -08002515 return ret.toArray(new StatsLogEventWrapper[ret.size()]);
Bookatzc68a9d22017-09-27 14:09:55 -07002516 }
2517
2518 @Override // Binder call
Bookatzb487b552017-09-18 11:26:01 -07002519 public void statsdReady() {
2520 enforceCallingPermission();
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002521 if (DEBUG) {
2522 Slog.d(TAG, "learned that statsdReady");
2523 }
Bookatzb487b552017-09-18 11:26:01 -07002524 sayHiToStatsd(); // tell statsd that we're ready too and link to it
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002525 mContext.sendBroadcastAsUser(new Intent(StatsManager.ACTION_STATSD_STARTED)
Bookatz81784082018-02-09 14:26:42 -08002526 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
Chenjie Yu2c0d83d2018-09-02 06:37:08 -07002527 UserHandle.SYSTEM, android.Manifest.permission.DUMP);
Bookatzb487b552017-09-18 11:26:01 -07002528 }
2529
David Chenc136f452017-11-27 11:52:26 -08002530 @Override
2531 public void triggerUidSnapshot() {
David Chen661f7912018-01-22 17:46:24 -08002532 enforceCallingPermission();
2533 synchronized (sStatsdLock) {
David Chen35045cb2018-03-23 22:21:47 -07002534 final long token = Binder.clearCallingIdentity();
David Chen661f7912018-01-22 17:46:24 -08002535 try {
2536 informAllUidsLocked(mContext);
2537 } catch (RemoteException e) {
2538 Slog.e(TAG, "Failed to trigger uid snapshot.", e);
David Chen35045cb2018-03-23 22:21:47 -07002539 } finally {
2540 restoreCallingIdentity(token);
David Chen661f7912018-01-22 17:46:24 -08002541 }
David Chenc136f452017-11-27 11:52:26 -08002542 }
David Chenc136f452017-11-27 11:52:26 -08002543 }
2544
Bookatz94726412017-08-31 09:26:15 -07002545 private void enforceCallingPermission() {
2546 if (Binder.getCallingPid() == Process.myPid()) {
2547 return;
2548 }
2549 mContext.enforceCallingPermission(android.Manifest.permission.STATSCOMPANION, null);
2550 }
2551
Bookatzb487b552017-09-18 11:26:01 -07002552 // Lifecycle and related code
2553
David Chen1481fe12017-10-16 13:16:34 -07002554 /**
2555 * Fetches the statsd IBinder service
2556 */
Bookatzb487b552017-09-18 11:26:01 -07002557 private static IStatsManager fetchStatsdService() {
2558 return IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
2559 }
2560
2561 public static final class Lifecycle extends SystemService {
2562 private StatsCompanionService mStatsCompanionService;
2563
2564 public Lifecycle(Context context) {
2565 super(context);
2566 }
2567
2568 @Override
2569 public void onStart() {
2570 mStatsCompanionService = new StatsCompanionService(getContext());
2571 try {
Chenjie Yuab530202018-09-26 12:39:20 -07002572 publishBinderService(Context.STATS_COMPANION_SERVICE,
2573 mStatsCompanionService);
Bookatzb487b552017-09-18 11:26:01 -07002574 if (DEBUG) Slog.d(TAG, "Published " + Context.STATS_COMPANION_SERVICE);
2575 } catch (Exception e) {
2576 Slog.e(TAG, "Failed to publishBinderService", e);
2577 }
2578 }
2579
2580 @Override
2581 public void onBootPhase(int phase) {
2582 super.onBootPhase(phase);
Tej Singh74d943e2019-05-29 21:12:11 +00002583 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Bookatzb487b552017-09-18 11:26:01 -07002584 mStatsCompanionService.systemReady();
2585 }
2586 }
2587 }
2588
David Chen1481fe12017-10-16 13:16:34 -07002589 /**
2590 * Now that the android system is ready, StatsCompanion is ready too, so inform statsd.
2591 */
Bookatzb487b552017-09-18 11:26:01 -07002592 private void systemReady() {
2593 if (DEBUG) Slog.d(TAG, "Learned that systemReady");
2594 sayHiToStatsd();
2595 }
2596
David Chen1481fe12017-10-16 13:16:34 -07002597 /**
Chenjie Yuab530202018-09-26 12:39:20 -07002598 * Tells statsd that statscompanion is ready. If the binder call returns, link to
2599 * statsd.
David Chen1481fe12017-10-16 13:16:34 -07002600 */
Bookatzb487b552017-09-18 11:26:01 -07002601 private void sayHiToStatsd() {
2602 synchronized (sStatsdLock) {
2603 if (sStatsd != null) {
2604 Slog.e(TAG, "Trying to fetch statsd, but it was already fetched",
Chenjie Yuab530202018-09-26 12:39:20 -07002605 new IllegalStateException(
2606 "sStatsd is not null when being fetched"));
Bookatzb487b552017-09-18 11:26:01 -07002607 return;
2608 }
2609 sStatsd = fetchStatsdService();
2610 if (sStatsd == null) {
Chenjie Yuab530202018-09-26 12:39:20 -07002611 Slog.i(TAG,
2612 "Could not yet find statsd to tell it that StatsCompanion is "
2613 + "alive.");
Bookatzb487b552017-09-18 11:26:01 -07002614 return;
2615 }
2616 if (DEBUG) Slog.d(TAG, "Saying hi to statsd");
2617 try {
2618 sStatsd.statsCompanionReady();
2619 // If the statsCompanionReady two-way binder call returns, link to statsd.
2620 try {
2621 sStatsd.asBinder().linkToDeath(new StatsdDeathRecipient(), 0);
2622 } catch (RemoteException e) {
2623 Slog.e(TAG, "linkToDeath(StatsdDeathRecipient) failed", e);
yroe26c97b2018-03-27 10:30:11 -07002624 forgetEverythingLocked();
Bookatzb487b552017-09-18 11:26:01 -07002625 }
yro947fbce2017-11-15 22:50:23 -08002626 // Setup broadcast receiver for updates.
David Chende701692017-10-05 13:16:02 -07002627 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REPLACED);
2628 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
2629 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2630 filter.addDataScheme("package");
Chenjie Yuab530202018-09-26 12:39:20 -07002631 mContext.registerReceiverAsUser(mAppUpdateReceiver, UserHandle.ALL, filter,
2632 null,
David Chen1481fe12017-10-16 13:16:34 -07002633 null);
David Chen47e8f4d2017-10-11 15:34:13 -07002634
Chenjie Yuab530202018-09-26 12:39:20 -07002635 // Setup receiver for user initialize (which happens once for a new user)
2636 // and
David Chen47e8f4d2017-10-11 15:34:13 -07002637 // if a user is removed.
2638 filter = new IntentFilter(Intent.ACTION_USER_INITIALIZE);
2639 filter.addAction(Intent.ACTION_USER_REMOVED);
2640 mContext.registerReceiverAsUser(mUserUpdateReceiver, UserHandle.ALL,
David Chen1481fe12017-10-16 13:16:34 -07002641 filter, null, null);
David Chen47e8f4d2017-10-11 15:34:13 -07002642
yro947fbce2017-11-15 22:50:23 -08002643 // Setup receiver for device reboots or shutdowns.
2644 filter = new IntentFilter(Intent.ACTION_REBOOT);
2645 filter.addAction(Intent.ACTION_SHUTDOWN);
2646 mContext.registerReceiverAsUser(
2647 mShutdownEventReceiver, UserHandle.ALL, filter, null, null);
Yao Chen0f217102018-01-09 10:33:15 -08002648 final long token = Binder.clearCallingIdentity();
2649 try {
Chenjie Yuab530202018-09-26 12:39:20 -07002650 // Pull the latest state of UID->app name, version mapping when
2651 // statsd starts.
Yao Chen0f217102018-01-09 10:33:15 -08002652 informAllUidsLocked(mContext);
2653 } finally {
2654 restoreCallingIdentity(token);
2655 }
Bookatz111ed732018-02-16 15:54:05 -08002656 Slog.i(TAG, "Told statsd that StatsCompanionService is alive.");
Bookatzb487b552017-09-18 11:26:01 -07002657 } catch (RemoteException e) {
2658 Slog.e(TAG, "Failed to inform statsd that statscompanion is ready", e);
yroe26c97b2018-03-27 10:30:11 -07002659 forgetEverythingLocked();
Bookatzb487b552017-09-18 11:26:01 -07002660 }
2661 }
2662 }
2663
2664 private class StatsdDeathRecipient implements IBinder.DeathRecipient {
2665 @Override
2666 public void binderDied() {
2667 Slog.i(TAG, "Statsd is dead - erase all my knowledge.");
yroe26c97b2018-03-27 10:30:11 -07002668 synchronized (sStatsdLock) {
2669 long now = SystemClock.elapsedRealtime();
2670 for (Long timeMillis : mDeathTimeMillis) {
2671 long ageMillis = now - timeMillis;
2672 if (ageMillis > MILLIS_IN_A_DAY) {
2673 mDeathTimeMillis.remove(timeMillis);
2674 }
2675 }
2676 for (Long timeMillis : mDeletedFiles.keySet()) {
2677 long ageMillis = now - timeMillis;
2678 if (ageMillis > MILLIS_IN_A_DAY * 7) {
2679 mDeletedFiles.remove(timeMillis);
2680 }
2681 }
2682 mDeathTimeMillis.add(now);
2683 if (mDeathTimeMillis.size() >= DEATH_THRESHOLD) {
2684 mDeathTimeMillis.clear();
2685 File[] configs = FileUtils.listFilesOrEmpty(new File(CONFIG_DIR));
2686 if (configs.length > 0) {
2687 String fileName = configs[0].getName();
2688 if (configs[0].delete()) {
2689 mDeletedFiles.put(now, fileName);
2690 }
2691 }
2692 }
2693 forgetEverythingLocked();
2694 }
Bookatzb487b552017-09-18 11:26:01 -07002695 }
2696 }
2697
Andreas Gampe29520212018-07-20 12:55:37 -07002698 @GuardedBy("StatsCompanionService.sStatsdLock")
yroe26c97b2018-03-27 10:30:11 -07002699 private void forgetEverythingLocked() {
2700 sStatsd = null;
2701 mContext.unregisterReceiver(mAppUpdateReceiver);
2702 mContext.unregisterReceiver(mUserUpdateReceiver);
2703 mContext.unregisterReceiver(mShutdownEventReceiver);
2704 cancelAnomalyAlarm();
2705 cancelPullingAlarm();
Olivier Gaillard6e725272019-01-15 14:21:57 +00002706
2707 BinderCallsStatsService.Internal binderStats =
2708 LocalServices.getService(BinderCallsStatsService.Internal.class);
2709 if (binderStats != null) {
2710 binderStats.reset();
2711 }
2712
2713 LooperStats looperStats = LocalServices.getService(LooperStats.class);
2714 if (looperStats != null) {
2715 looperStats.reset();
2716 }
yroe26c97b2018-03-27 10:30:11 -07002717 }
2718
2719 @Override
2720 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2721 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
2722
Bookatzb487b552017-09-18 11:26:01 -07002723 synchronized (sStatsdLock) {
Chenjie Yuab530202018-09-26 12:39:20 -07002724 writer.println(
2725 "Number of configuration files deleted: " + mDeletedFiles.size());
yroe26c97b2018-03-27 10:30:11 -07002726 if (mDeletedFiles.size() > 0) {
2727 writer.println(" timestamp, deleted file name");
2728 }
2729 long lastBootMillis =
2730 SystemClock.currentThreadTimeMillis() - SystemClock.elapsedRealtime();
2731 for (Long elapsedMillis : mDeletedFiles.keySet()) {
2732 long deletionMillis = lastBootMillis + elapsedMillis;
Chenjie Yuab530202018-09-26 12:39:20 -07002733 writer.println(
2734 " " + deletionMillis + ", " + mDeletedFiles.get(elapsedMillis));
yroe26c97b2018-03-27 10:30:11 -07002735 }
Bookatzb487b552017-09-18 11:26:01 -07002736 }
2737 }
2738
Yangster-mace16189a2018-08-26 12:20:16 -07002739 // Thermal event received from vendor thermal management subsystem
2740 private static final class ThermalEventListener extends IThermalEventListener.Stub {
Chenjie Yu12e5e672018-09-14 15:54:59 -07002741 @Override
Wei Wangbad7c202018-11-01 11:57:39 -07002742 public void notifyThrottling(Temperature temp) {
Tej Singha72344992019-04-17 18:55:08 -07002743 StatsLog.write(StatsLog.THERMAL_THROTTLING_SEVERITY_STATE_CHANGED, temp.getType(),
2744 temp.getName(), (int) (temp.getValue() * 10), temp.getStatus());
Yangster-mace16189a2018-08-26 12:20:16 -07002745 }
2746 }
Chenjie Yuae9dfac2018-10-25 16:06:56 -07002747
2748 private static final class ConnectivityStatsCallback extends
2749 ConnectivityManager.NetworkCallback {
2750 @Override
2751 public void onAvailable(Network network) {
2752 StatsLog.write(StatsLog.CONNECTIVITY_STATE_CHANGED, network.netId,
2753 StatsLog.CONNECTIVITY_STATE_CHANGED__STATE__CONNECTED);
2754 }
2755
2756 @Override
2757 public void onLost(Network network) {
2758 StatsLog.write(StatsLog.CONNECTIVITY_STATE_CHANGED, network.netId,
2759 StatsLog.CONNECTIVITY_STATE_CHANGED__STATE__DISCONNECTED);
2760 }
2761 }
Bookatz94726412017-08-31 09:26:15 -07002762}