blob: 8a8c1e6ff0ac0c2e52cd287a1c0cbf3d62793a56 [file] [log] [blame]
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001/*
yro0feae942017-11-15 14:38:48 -08002 * Copyright (C) 2017 The Android Open Source Project
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Tej Singh484524a2018-02-01 15:10:05 -080017#define DEBUG false // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070019
20#include "StatsService.h"
Yangster-mac330af582018-02-08 15:24:38 -080021#include "stats_log_util.h"
Yao Chen8d9989b2017-11-18 18:54:50 -080022#include "android-base/stringprintf.h"
David Chenadaf8b32017-11-03 15:42:08 -070023#include "config/ConfigKey.h"
24#include "config/ConfigManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080025#include "guardrail/StatsdStats.h"
yro947fbce2017-11-15 22:50:23 -080026#include "storage/StorageManager.h"
Bookatzc6977972018-01-16 16:55:05 -080027#include "subscriber/SubscriberReporter.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070028
David Chen0656b7a2017-09-13 15:53:39 -070029#include <android-base/file.h>
Tej Singh53f9dee2019-04-30 17:45:54 -070030#include <android-base/strings.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070031#include <binder/IPCThreadState.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060032#include <binder/PermissionController.h>
Chenjie Yu6b1667c2019-01-18 10:09:33 -080033#include <cutils/multiuser.h>
David Chen0656b7a2017-09-13 15:53:39 -070034#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Max Dashouk11e0d402019-05-16 16:58:07 -070035#include <frameworks/base/cmds/statsd/src/uid_data.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070036#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080037#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070038#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070039#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070040#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070041#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070042#include <utils/String16.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070043
44using namespace android;
45
Jeff Sharkey6b649252018-04-16 09:50:22 -060046using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070047using android::util::FIELD_COUNT_REPEATED;
48using android::util::FIELD_TYPE_MESSAGE;
Jeff Sharkey6b649252018-04-16 09:50:22 -060049
Bookatz906a35c2017-09-20 15:26:44 -070050namespace android {
51namespace os {
52namespace statsd {
53
David Chenadaf8b32017-11-03 15:42:08 -070054constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060055constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
56
57constexpr const char* kOpUsage = "android:get_usage_stats";
58
yro03faf092017-12-12 00:17:50 -080059#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070060
Bookatzff71cad2018-09-20 17:17:49 -070061// for StatsDataDumpProto
62const int FIELD_ID_REPORTS_LIST = 1;
63
Jeff Sharkey6b649252018-04-16 09:50:22 -060064static binder::Status ok() {
65 return binder::Status::ok();
66}
67
68static binder::Status exception(uint32_t code, const std::string& msg) {
69 ALOGE("%s (%d)", msg.c_str(), code);
70 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
71}
72
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080073
74static bool checkPermission(const char* permission) {
75 sp<IStatsCompanionService> scs = getStatsCompanionService();
76 if (scs == nullptr) {
77 return false;
78 }
79
80 bool success;
81 pid_t pid = IPCThreadState::self()->getCallingPid();
82 uid_t uid = IPCThreadState::self()->getCallingUid();
83
84 binder::Status status = scs->checkPermission(String16(permission), pid, uid, &success);
85 if (!status.isOk()) {
86 return false;
87 }
88 return success;
89}
90
91
Jeff Sharkey6b649252018-04-16 09:50:22 -060092binder::Status checkUid(uid_t expectedUid) {
93 uid_t uid = IPCThreadState::self()->getCallingUid();
94 if (uid == expectedUid || uid == AID_ROOT) {
95 return ok();
96 } else {
97 return exception(binder::Status::EX_SECURITY,
98 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
99 }
100}
101
102binder::Status checkDumpAndUsageStats(const String16& packageName) {
103 pid_t pid = IPCThreadState::self()->getCallingPid();
104 uid_t uid = IPCThreadState::self()->getCallingUid();
105
106 // Root, system, and shell always have access
107 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
108 return ok();
109 }
110
111 // Caller must be granted these permissions
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800112 if (!checkPermission(kPermissionDump)) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600113 return exception(binder::Status::EX_SECURITY,
114 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
115 }
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800116 if (!checkPermission(kPermissionUsage)) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600117 return exception(binder::Status::EX_SECURITY,
118 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
119 }
120
121 // Caller must also have usage stats op granted
122 PermissionController pc;
123 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
124 case PermissionController::MODE_ALLOWED:
125 case PermissionController::MODE_DEFAULT:
126 return ok();
127 default:
128 return exception(binder::Status::EX_SECURITY,
129 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
130 }
131}
132
133#define ENFORCE_UID(uid) { \
134 binder::Status status = checkUid((uid)); \
135 if (!status.isOk()) { \
136 return status; \
137 } \
138}
139
140#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
141 binder::Status status = checkDumpAndUsageStats(packageName); \
142 if (!status.isOk()) { \
143 return status; \
144 } \
145}
146
Yao Chen0f861862019-03-27 11:51:15 -0700147StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
148 : mAnomalyAlarmMonitor(new AlarmMonitor(
149 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
150 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
151 if (sc != nullptr) {
152 sc->setAnomalyAlarm(timeMillis);
153 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
154 }
155 },
156 [](const sp<IStatsCompanionService>& sc) {
157 if (sc != nullptr) {
158 sc->cancelAnomalyAlarm();
159 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
160 }
161 })),
162 mPeriodicAlarmMonitor(new AlarmMonitor(
163 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
164 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
165 if (sc != nullptr) {
166 sc->setAlarmForSubscriberTriggering(timeMillis);
167 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
168 }
169 },
170 [](const sp<IStatsCompanionService>& sc) {
171 if (sc != nullptr) {
172 sc->cancelAlarmForSubscriberTriggering();
173 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
174 }
175 })),
176 mEventQueue(queue) {
Yao Chen4ce07292019-02-13 13:06:36 -0800177 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700178 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800179 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700180 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700181 mProcessor = new StatsLogProcessor(
182 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800183 getElapsedRealtimeNs(),
184 [this](const ConfigKey& key) {
Jeffrey Huangad213742019-12-16 13:50:06 -0800185 sp<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
186 if (receiver == nullptr) {
187 VLOG("Could not find a broadcast receiver for %s",
188 key.ToString().c_str());
Chenjie Yue2219202018-06-08 10:07:51 -0700189 return false;
Jeffrey Huangad213742019-12-16 13:50:06 -0800190 } else if (receiver->sendDataBroadcast(
191 mProcessor->getLastReportTimeNs(key)).isOk()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700192 return true;
Jeffrey Huangad213742019-12-16 13:50:06 -0800193 } else {
194 VLOG("Failed to send a broadcast for receiver %s",
195 key.ToString().c_str());
196 return false;
Chenjie Yue2219202018-06-08 10:07:51 -0700197 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800198 },
199 [this](const int& uid, const vector<int64_t>& activeConfigs) {
Jeffrey Huang47537a12020-01-06 15:35:34 -0800200 sp<IPendingIntentRef> receiver =
201 mConfigManager->GetActiveConfigsChangedReceiver(uid);
202 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800203 VLOG("Could not find receiver for uid %d", uid);
204 return false;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800205 } else if (receiver->sendActiveConfigsChangedBroadcast(activeConfigs).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800206 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
207 return true;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800208 } else {
209 VLOG("StatsService::active configs broadcast failed for uid %d" , uid);
210 return false;
Tej Singh6ede28b2019-01-29 17:06:54 -0800211 }
Chenjie Yue2219202018-06-08 10:07:51 -0700212 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700213
Tej Singh9ec159a2019-11-14 11:59:48 -0800214 mUidMap->setListener(mProcessor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700215 mConfigManager->AddListener(mProcessor);
216
217 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700218
219 if (mEventQueue != nullptr) {
220 std::thread pushedEventThread([this] { readLogs(); });
221 pushedEventThread.detach();
222 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700223}
224
Yao Chenef99c4f2017-09-22 16:26:54 -0700225StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700226}
227
Yao Chen0f861862019-03-27 11:51:15 -0700228/* Runs on a dedicated thread to process pushed events. */
229void StatsService::readLogs() {
230 // Read forever..... long live statsd
231 while (1) {
232 // Block until an event is available.
233 auto event = mEventQueue->waitPop();
234 // Pass it to StatsLogProcess to all configs/metrics
235 // At this point, the LogEventQueue is not blocked, so that the socketListener
236 // can read events from the socket and write to buffer to avoid data drop.
237 mProcessor->OnLogEvent(event.get());
238 // The ShellSubscriber is only used by shell for local debugging.
239 if (mShellSubscriber != nullptr) {
240 mShellSubscriber->onLogEvent(*event);
241 }
242 }
243}
244
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700245void StatsService::init_system_properties() {
246 mEngBuild = false;
247 const prop_info* buildType = __system_property_find("ro.build.type");
248 if (buildType != NULL) {
249 __system_property_read_callback(buildType, init_build_type_callback, this);
250 }
David Chen0656b7a2017-09-13 15:53:39 -0700251}
252
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700253void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
254 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700255 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700256 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
257 }
258}
259
260/**
261 * Implement our own because the default binder implementation isn't
262 * properly handling SHELL_COMMAND_TRANSACTION.
263 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700264status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
265 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700266 switch (code) {
267 case SHELL_COMMAND_TRANSACTION: {
268 int in = data.readFileDescriptor();
269 int out = data.readFileDescriptor();
270 int err = data.readFileDescriptor();
271 int argc = data.readInt32();
272 Vector<String8> args;
273 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
274 args.add(String8(data.readString16()));
275 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700276 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
277 sp<IResultReceiver> resultReceiver =
278 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700279
Yao Chena80e5c02018-09-04 13:55:29 -0700280 err = command(in, out, err, args, resultReceiver);
Tej Singhc9250ce2019-09-20 19:28:53 -0700281 if (resultReceiver != nullptr) {
282 resultReceiver->send(err);
283 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700284 return NO_ERROR;
285 }
Jeffrey Huang161c0752019-12-11 14:47:32 -0800286 default: { return BnStatsd::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700287 }
288}
289
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700290/**
Bookatzff71cad2018-09-20 17:17:49 -0700291 * Write data from statsd.
292 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
293 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
294 * Anything ending in --proto will be in proto format.
295 * Anything without --metadata as the first argument will be report information.
296 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
297 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700298 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700299status_t StatsService::dump(int fd, const Vector<String16>& args) {
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800300 if (!checkPermission(kPermissionDump)) {
Tej Singhdd83d702018-04-10 17:24:50 -0700301 return PERMISSION_DENIED;
302 }
Bookatzff71cad2018-09-20 17:17:49 -0700303 int lastArg = args.size() - 1;
304 bool asProto = false;
305 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
306 asProto = true;
307 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800308 }
Bookatzff71cad2018-09-20 17:17:49 -0700309 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
310 // Request is to dump statsd stats.
311 bool verbose = false;
312 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
313 verbose = true;
314 lastArg--;
315 }
316 dumpStatsdStats(fd, verbose, asProto);
317 } else {
318 // Request is to dump statsd report data.
319 if (asProto) {
320 dumpIncidentSection(fd);
321 } else {
322 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
323 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700324 }
Yao Chen884c8c12018-01-26 10:36:25 -0800325
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700326 return NO_ERROR;
327}
328
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700329/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700330 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700331 */
Bookatzff71cad2018-09-20 17:17:49 -0700332void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700333 if (proto) {
334 vector<uint8_t> data;
335 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
336 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700337 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700338 }
339 } else {
340 StatsdStats::getInstance().dumpStats(out);
341 mProcessor->dumpStates(out, verbose);
342 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700343}
344
345/**
Bookatzff71cad2018-09-20 17:17:49 -0700346 * Write stats report data in StatsDataDumpProto incident section format.
347 */
348void StatsService::dumpIncidentSection(int out) {
349 ProtoOutputStream proto;
350 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
351 uint64_t reportsListToken =
352 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
353 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
354 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000355 ADB_DUMP,
356 FAST,
357 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700358 proto.end(reportsListToken);
359 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800360 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700361 }
362}
363
364/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700365 * Implementation of the adb shell cmd stats command.
366 */
Yao Chena80e5c02018-09-04 13:55:29 -0700367status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
368 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600369 uid_t uid = IPCThreadState::self()->getCallingUid();
370 if (uid != AID_ROOT && uid != AID_SHELL) {
371 return PERMISSION_DENIED;
372 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700373
374 const int argCount = args.size();
375 if (argCount >= 1) {
376 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700377 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700378 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700379 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700380
David Chende701692017-10-05 13:16:02 -0700381 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800382 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700383 }
Yao Chen729093d2017-10-16 10:33:26 -0700384
385 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700386 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700387 }
David Chen1481fe12017-10-16 13:16:34 -0700388
389 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
390 return cmd_print_pulled_metrics(out, args);
391 }
David Chenadaf8b32017-11-03 15:42:08 -0700392
393 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800394 return cmd_trigger_broadcast(out, args);
395 }
396
397 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800398 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700399 }
yro87d983c2017-11-14 21:31:43 -0800400
Yao Chen8d9989b2017-11-18 18:54:50 -0800401 if (!args[0].compare(String8("meminfo"))) {
402 return cmd_dump_memory_info(out);
403 }
yro947fbce2017-11-15 22:50:23 -0800404
405 if (!args[0].compare(String8("write-to-disk"))) {
406 return cmd_write_data_to_disk(out);
407 }
Bookatzb223c4e2018-02-01 15:35:04 -0800408
David Chen0b5c90c2018-01-25 16:51:49 -0800409 if (!args[0].compare(String8("log-app-breadcrumb"))) {
410 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800411 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800412
Tej Singh53f9dee2019-04-30 17:45:54 -0700413 if (!args[0].compare(String8("log-binary-push"))) {
414 return cmd_log_binary_push(out, args);
415 }
416
Chenjie Yufa22d652018-02-05 14:37:48 -0800417 if (!args[0].compare(String8("clear-puller-cache"))) {
418 return cmd_clear_puller_cache(out);
419 }
Yao Chen876889c2018-05-02 11:16:16 -0700420
421 if (!args[0].compare(String8("print-logs"))) {
422 return cmd_print_logs(out, args);
423 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800424 if (!args[0].compare(String8("send-active-configs"))) {
425 return cmd_trigger_active_config_broadcast(out, args);
426 }
Yao Chena80e5c02018-09-04 13:55:29 -0700427 if (!args[0].compare(String8("data-subscribe"))) {
Tej Singhc9250ce2019-09-20 19:28:53 -0700428 {
429 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
430 if (mShellSubscriber == nullptr) {
431 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
432 }
Yao Chena80e5c02018-09-04 13:55:29 -0700433 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800434 int timeoutSec = -1;
435 if (argCount >= 2) {
436 timeoutSec = atoi(args[1].c_str());
437 }
Tej Singhc9250ce2019-09-20 19:28:53 -0700438 if (resultReceiver == nullptr) {
439 ALOGI("Null resultReceiver given, no subscription will be started");
440 return UNEXPECTED_NULL;
441 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800442 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700443 return NO_ERROR;
444 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700445 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700446
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700447 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700448 return NO_ERROR;
449}
450
Yao Chena80e5c02018-09-04 13:55:29 -0700451void StatsService::print_cmd_help(int out) {
452 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700453 "usage: adb shell cmd stats print-stats-log [tag_required] "
454 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700455 dprintf(out, "\n");
456 dprintf(out, "\n");
457 dprintf(out, "usage: adb shell cmd stats meminfo\n");
458 dprintf(out, "\n");
459 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
460 dprintf(out, " # adb shell stop\n");
461 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
462 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
463 dprintf(out, " # adb shell start\n");
464 dprintf(out, "\n");
465 dprintf(out, "\n");
466 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
467 dprintf(out, "\n");
468 dprintf(out, " Prints the UID, app name, version mapping.\n");
469 dprintf(out, " PKG Optional package name to print the uids of the package\n");
470 dprintf(out, "\n");
471 dprintf(out, "\n");
472 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
473 dprintf(out, "\n");
474 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
475 dprintf(out, "\n");
476 dprintf(out, "\n");
477 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
478 dprintf(out, "\n");
479 dprintf(out, " Flushes all data on memory to disk.\n");
480 dprintf(out, "\n");
481 dprintf(out, "\n");
482 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
483 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
484 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
485 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
486 dprintf(out, " uid is used.\n");
487 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
488 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
489 dprintf(out, "\n");
490 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700491 dprintf(out,
492 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
493 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
494 dprintf(out, " Log a binary push state changed event.\n");
495 dprintf(out, " NAME The train name.\n");
496 dprintf(out, " VERSION The train version code.\n");
497 dprintf(out, " STAGING If this train requires a restart.\n");
498 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
499 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
500 dprintf(out, " STATE The status of the train push.\n");
501 dprintf(out, " Integer value of the enum in atoms.proto.\n");
502 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
503 dprintf(out, " Leave blank for none.\n");
504 dprintf(out, "\n");
505 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700506 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
507 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
508 dprintf(out, "\n");
509 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
510 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
511 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
512 dprintf(out, "\n");
513 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
514 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
515 dprintf(out, " uid is used.\n");
516 dprintf(out, " NAME The per-uid name to use\n");
517 dprintf(out, "\n");
518 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
519 dprintf(out, "\n be removed from memory and disk!\n");
520 dprintf(out, "\n");
521 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800522 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
523 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700524 dprintf(out, " Dump all metric data for a configuration.\n");
525 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
526 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
527 dprintf(out, " calling uid is used.\n");
528 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800529 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700530 dprintf(out, " --proto Print proto binary.\n");
531 dprintf(out, "\n");
532 dprintf(out, "\n");
533 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
534 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
535 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
536 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
537 dprintf(out, " calling uid is used.\n");
538 dprintf(out, " NAME The name of the configuration\n");
539 dprintf(out, "\n");
540 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800541 dprintf(out,
542 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
543 "[NAME1] [NAME2] [NAME3..]\n");
544 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
545 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
546 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
547 dprintf(out, " calling uid is used.\n");
548 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
549 dprintf(out, " the currently active configs\n");
550 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800551 dprintf(out, "\n");
552 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700553 dprintf(out, "usage: adb shell cmd stats print-stats\n");
554 dprintf(out, " Prints some basic stats.\n");
555 dprintf(out, " --proto Print proto binary instead of string format.\n");
556 dprintf(out, "\n");
557 dprintf(out, "\n");
558 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
559 dprintf(out, " Clear cached puller data.\n");
560 dprintf(out, "\n");
561 dprintf(out, "usage: adb shell cmd stats print-logs\n");
562 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700563}
564
Yao Chena80e5c02018-09-04 13:55:29 -0700565status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800566 string name;
567 bool good = false;
568 int uid;
569 const int argCount = args.size();
570 if (argCount == 2) {
571 // Automatically pick the UID
572 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800573 name.assign(args[1].c_str(), args[1].size());
574 good = true;
575 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800576 good = getUidFromArgs(args, 1, uid);
577 if (!good) {
578 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
579 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800580 }
Bookatzd2386572018-12-14 15:53:14 -0800581 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800582 }
583 if (!good) {
584 print_cmd_help(out);
585 return UNKNOWN_ERROR;
586 }
David Chend37bc232018-04-12 18:05:11 -0700587 ConfigKey key(uid, StrToInt64(name));
Jeffrey Huangad213742019-12-16 13:50:06 -0800588 sp<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
589 if (receiver == nullptr) {
590 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
591 return UNKNOWN_ERROR;
592 } else if (receiver->sendDataBroadcast(
593 mProcessor->getLastReportTimeNs(key)).isOk()) {
yro74fed972017-11-27 14:42:42 -0800594 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
595 args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800596 } else {
597 VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(),
598 args[2].c_str());
599 return UNKNOWN_ERROR;
yro4d889e62017-11-17 15:44:48 -0800600 }
David Chenadaf8b32017-11-03 15:42:08 -0700601 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700602}
603
Tej Singh6ede28b2019-01-29 17:06:54 -0800604status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
605 const int argCount = args.size();
606 int uid;
607 vector<int64_t> configIds;
608 if (argCount == 1) {
609 // Automatically pick the uid and send a broadcast that has no active configs.
610 uid = IPCThreadState::self()->getCallingUid();
611 mProcessor->GetActiveConfigs(uid, configIds);
612 } else {
613 int curArg = 1;
614 if(args[curArg].find("--uid=") == 0) {
615 string uidArgStr(args[curArg].c_str());
616 string uidStr = uidArgStr.substr(6);
617 if (!getUidFromString(uidStr.c_str(), uid)) {
618 dprintf(out, "Invalid UID. Note that the config can only be set for "
619 "other UIDs on eng or userdebug builds.\n");
620 return UNKNOWN_ERROR;
621 }
622 curArg++;
623 } else {
624 uid = IPCThreadState::self()->getCallingUid();
625 }
626 if (curArg == argCount || args[curArg] != "--configs") {
627 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
628 mProcessor->GetActiveConfigs(uid, configIds);
629 } else {
630 // Flag specified, use the given list of configs.
631 curArg++;
632 for (int i = curArg; i < argCount; i++) {
633 char* endp;
634 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
635 if (endp == args[i].c_str() || *endp != '\0') {
636 dprintf(out, "Error parsing config ID.\n");
637 return UNKNOWN_ERROR;
638 }
639 VLOG("Adding config id %ld", static_cast<long>(configID));
640 configIds.push_back(configID);
641 }
642 }
643 }
Jeffrey Huang47537a12020-01-06 15:35:34 -0800644 sp<IPendingIntentRef> receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
645 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800646 VLOG("Could not find receiver for uid %d", uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800647 return UNKNOWN_ERROR;
648 } else if (receiver->sendActiveConfigsChangedBroadcast(configIds).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800649 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800650 } else {
651 VLOG("StatsService::trigger active configs changed broadcast failed for uid %d", uid);
652 return UNKNOWN_ERROR;
Tej Singh6ede28b2019-01-29 17:06:54 -0800653 }
654 return NO_ERROR;
655}
656
Yao Chena80e5c02018-09-04 13:55:29 -0700657status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700658 const int argCount = args.size();
659 if (argCount >= 2) {
660 if (args[1] == "update" || args[1] == "remove") {
661 bool good = false;
662 int uid = -1;
663 string name;
664
665 if (argCount == 3) {
666 // Automatically pick the UID
667 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700668 name.assign(args[2].c_str(), args[2].size());
669 good = true;
670 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800671 good = getUidFromArgs(args, 2, uid);
672 if (!good) {
673 dprintf(err, "Invalid UID. Note that the config can only be set for "
674 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700675 }
Bookatzd2386572018-12-14 15:53:14 -0800676 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800677 } else if (argCount == 2 && args[1] == "remove") {
678 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700679 }
680
681 if (!good) {
682 // If arg parsing failed, print the help text and return an error.
683 print_cmd_help(out);
684 return UNKNOWN_ERROR;
685 }
686
687 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800688 char* endp;
689 int64_t configID = strtoll(name.c_str(), &endp, 10);
690 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700691 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800692 return UNKNOWN_ERROR;
693 }
694
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700695 // Read stream into buffer.
696 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700697 if (!android::base::ReadFdToString(in, &buffer)) {
698 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700699 return UNKNOWN_ERROR;
700 }
701
702 // Parse buffer.
703 StatsdConfig config;
704 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700705 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700706 return UNKNOWN_ERROR;
707 }
708
709 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800710 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700711 } else {
yro74fed972017-11-27 14:42:42 -0800712 if (argCount == 2) {
713 cmd_remove_all_configs(out);
714 } else {
715 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800716 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800717 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700718 }
719
720 return NO_ERROR;
721 }
David Chen0656b7a2017-09-13 15:53:39 -0700722 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700723 print_cmd_help(out);
724 return UNKNOWN_ERROR;
725}
726
Bookatzff71cad2018-09-20 17:17:49 -0700727status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700728 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800729 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700730 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800731 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700732 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800733 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700734 int uid;
735 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800736 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
737 proto = true;
738 argCount -= 1;
739 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700740 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
741 includeCurrentBucket = true;
742 argCount -= 1;
743 }
Bookatz3e906582018-12-10 17:26:58 -0800744 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
745 eraseData = false;
746 argCount -= 1;
747 }
Yao Chen729093d2017-10-16 10:33:26 -0700748 if (argCount == 2) {
749 // Automatically pick the UID
750 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700751 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700752 good = true;
753 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800754 good = getUidFromArgs(args, 1, uid);
755 if (!good) {
756 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
757 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700758 }
Bookatzd2386572018-12-14 15:53:14 -0800759 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700760 }
761 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800762 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800763 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000764 includeCurrentBucket, eraseData, ADB_DUMP,
765 NO_TIME_CONSTRAINTS,
766 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800767 if (proto) {
768 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700769 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800770 }
771 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700772 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800773 }
Yao Chen729093d2017-10-16 10:33:26 -0700774 return android::OK;
775 } else {
776 // If arg parsing failed, print the help text and return an error.
777 print_cmd_help(out);
778 return UNKNOWN_ERROR;
779 }
780 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700781 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700782 return UNKNOWN_ERROR;
783 }
784}
785
Yao Chena80e5c02018-09-04 13:55:29 -0700786status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700787 int argCount = args.size();
788 bool proto = false;
789 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
790 proto = true;
791 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800792 }
Yao Chenb3561512017-11-21 18:07:17 -0800793 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700794 if (proto) {
795 vector<uint8_t> data;
796 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
797 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700798 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700799 }
800
801 } else {
802 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
803 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700804 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700805 mProcessor->GetMetricsSize(key));
806 }
807 statsdStats.dumpStats(out);
808 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800809 return NO_ERROR;
810}
811
Yao Chena80e5c02018-09-04 13:55:29 -0700812status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800813 if (args.size() > 1) {
814 string pkg;
815 pkg.assign(args[1].c_str(), args[1].size());
816 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700817 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800818 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700819 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800820 }
Yao Chena80e5c02018-09-04 13:55:29 -0700821 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800822 } else {
823 mUidMap->printUidMap(out);
824 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700825 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700826}
827
Yao Chena80e5c02018-09-04 13:55:29 -0700828status_t StatsService::cmd_write_data_to_disk(int out) {
829 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000830 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800831 return NO_ERROR;
832}
833
Yao Chena80e5c02018-09-04 13:55:29 -0700834status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800835 bool good = false;
836 int32_t uid;
837 int32_t label;
838 int32_t state;
839 const int argCount = args.size();
840 if (argCount == 3) {
841 // Automatically pick the UID
842 uid = IPCThreadState::self()->getCallingUid();
843 label = atoi(args[1].c_str());
844 state = atoi(args[2].c_str());
845 good = true;
846 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800847 good = getUidFromArgs(args, 1, uid);
848 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700849 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800850 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
851 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800852 }
Bookatzd2386572018-12-14 15:53:14 -0800853 label = atoi(args[2].c_str());
854 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800855 }
856 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700857 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800858 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800859 } else {
860 print_cmd_help(out);
861 return UNKNOWN_ERROR;
862 }
863 return NO_ERROR;
864}
865
Tej Singh53f9dee2019-04-30 17:45:54 -0700866status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
867 // Security checks are done in the sendBinaryPushStateChanged atom.
868 const int argCount = args.size();
869 if (argCount != 7 && argCount != 8) {
870 dprintf(out, "Incorrect number of argument supplied\n");
871 return UNKNOWN_ERROR;
872 }
873 android::String16 trainName = android::String16(args[1].c_str());
874 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
875 int options = 0;
876 if (args[3] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800877 options = options | IStatsd::FLAG_REQUIRE_STAGING;
Tej Singh53f9dee2019-04-30 17:45:54 -0700878 }
879 if (args[4] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800880 options = options | IStatsd::FLAG_ROLLBACK_ENABLED;
Tej Singh53f9dee2019-04-30 17:45:54 -0700881 }
882 if (args[5] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800883 options = options | IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Tej Singh53f9dee2019-04-30 17:45:54 -0700884 }
885 int32_t state = atoi(args[6].c_str());
886 vector<int64_t> experimentIds;
887 if (argCount == 8) {
888 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
889 for (string experimentIdString : experimentIdsString) {
890 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
891 experimentIds.push_back(experimentId);
892 }
893 }
894 dprintf(out, "Logging BinaryPushStateChanged\n");
895 sendBinaryPushStateChangedAtom(trainName, trainVersion, options, state, experimentIds);
896 return NO_ERROR;
897}
898
Yao Chena80e5c02018-09-04 13:55:29 -0700899status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700900 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700901 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800902 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700903 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700904 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700905 }
Yao Chena80e5c02018-09-04 13:55:29 -0700906 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700907 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700908 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700909 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700910}
911
Yao Chena80e5c02018-09-04 13:55:29 -0700912status_t StatsService::cmd_remove_all_configs(int out) {
913 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800914 VLOG("StatsService::cmd_remove_all_configs was called");
915 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800916 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800917 return NO_ERROR;
918}
919
Yao Chena80e5c02018-09-04 13:55:29 -0700920status_t StatsService::cmd_dump_memory_info(int out) {
921 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800922 return NO_ERROR;
923}
924
Yao Chena80e5c02018-09-04 13:55:29 -0700925status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800926 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800927 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
928 ipc->getCallingPid(), ipc->getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800929 if (checkPermission(kPermissionDump)) {
Chenjie Yue2219202018-06-08 10:07:51 -0700930 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700931 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800932 return NO_ERROR;
933 } else {
934 return PERMISSION_DENIED;
935 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800936}
937
Yao Chena80e5c02018-09-04 13:55:29 -0700938status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700939 IPCThreadState* ipc = IPCThreadState::self();
940 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
941 ipc->getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800942 if (checkPermission(kPermissionDump)) {
Yao Chen876889c2018-05-02 11:16:16 -0700943 bool enabled = true;
944 if (args.size() >= 2) {
945 enabled = atoi(args[1].c_str()) != 0;
946 }
947 mProcessor->setPrintLogs(enabled);
948 return NO_ERROR;
949 } else {
950 return PERMISSION_DENIED;
951 }
952}
953
Bookatzd2386572018-12-14 15:53:14 -0800954bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800955 return getUidFromString(args[uidArgIndex].c_str(), uid);
956}
957
958bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800959 if (*s == '\0') {
960 return false;
961 }
962 char* endc = NULL;
963 int64_t longUid = strtol(s, &endc, 0);
964 if (*endc != '\0') {
965 return false;
966 }
967 int32_t goodUid = static_cast<int32_t>(longUid);
968 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
969 return false; // It was not of uid_t type.
970 }
971 uid = goodUid;
972
973 int32_t callingUid = IPCThreadState::self()->getCallingUid();
974 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
975 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
976 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
977}
978
Max Dashouk11e0d402019-05-16 16:58:07 -0700979Status StatsService::informAllUidData(const ParcelFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600980 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700981 // Read stream into buffer.
982 string buffer;
983 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
984 return exception(Status::EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
985 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600986
Max Dashouk11e0d402019-05-16 16:58:07 -0700987 // Parse buffer.
988 UidData uidData;
989 if (!uidData.ParseFromString(buffer)) {
990 return exception(Status::EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
991 }
David Chende701692017-10-05 13:16:02 -0700992
Max Dashouk11e0d402019-05-16 16:58:07 -0700993 vector<String16> versionStrings;
994 vector<String16> installers;
995 vector<String16> packageNames;
996 vector<int32_t> uids;
997 vector<int64_t> versions;
998
999 const auto numEntries = uidData.app_info_size();
1000 versionStrings.reserve(numEntries);
1001 installers.reserve(numEntries);
1002 packageNames.reserve(numEntries);
1003 uids.reserve(numEntries);
1004 versions.reserve(numEntries);
1005
1006 for (const auto& appInfo: uidData.app_info()) {
1007 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
1008 uids.push_back(appInfo.uid());
1009 versions.push_back(appInfo.version());
1010 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
1011 installers.emplace_back(String16(appInfo.installer().c_str()));
1012 }
1013
1014 mUidMap->updateMap(getElapsedRealtimeNs(),
1015 uids,
1016 versions,
1017 versionStrings,
1018 packageNames,
1019 installers);
1020
1021 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -07001022 return Status::ok();
1023}
1024
dwchen730403e2018-10-29 11:41:56 -07001025Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
1026 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001027 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001028
Jeff Sharkey6b649252018-04-16 09:50:22 -06001029 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -07001030 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -07001031 return Status::ok();
1032}
1033
1034Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001035 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001036
Jeff Sharkey6b649252018-04-16 09:50:22 -06001037 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -07001038 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -08001039 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -07001040 return Status::ok();
1041}
1042
Yao Chenef99c4f2017-09-22 16:26:54 -07001043Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001044 ENFORCE_UID(AID_SYSTEM);
1045
yro74fed972017-11-27 14:42:42 -08001046 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001047 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001048 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1049 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1050 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -08001051 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -08001052 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -08001053 } else {
1054 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
1055 }
Bookatz1b0b1142017-09-08 11:58:42 -07001056 return Status::ok();
1057}
1058
Yangster-mac932ecec2018-02-01 10:23:52 -08001059Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001060 ENFORCE_UID(AID_SYSTEM);
1061
Yangster-mac932ecec2018-02-01 10:23:52 -08001062 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001063 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001064 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1065 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1066 if (alarmSet.size() > 0) {
1067 VLOG("Found periodic alarm fired.");
1068 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1069 } else {
1070 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1071 }
1072 return Status::ok();
1073}
1074
Yao Chenef99c4f2017-09-22 16:26:54 -07001075Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001076 ENFORCE_UID(AID_SYSTEM);
1077
yro74fed972017-11-27 14:42:42 -08001078 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001079 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001080 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001081 return Status::ok();
1082}
1083
Yao Chenef99c4f2017-09-22 16:26:54 -07001084Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001085 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001086
1087 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001088 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001089 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001090 return Status::ok();
1091}
1092
Yangster-mac892f3d32018-05-02 14:16:48 -07001093Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001094 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001095 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001096 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001097 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001098 return Status::ok();
1099}
1100
Yao Chenef99c4f2017-09-22 16:26:54 -07001101void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -07001102 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1103 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001104 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001105 statsCompanion->statsdReady();
1106 } else {
yro74fed972017-11-27 14:42:42 -08001107 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001108 }
1109}
1110
Yao Chenef99c4f2017-09-22 16:26:54 -07001111Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001112 ENFORCE_UID(AID_SYSTEM);
1113
yro74fed972017-11-27 14:42:42 -08001114 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001115 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1116 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001117 return Status::fromExceptionCode(
1118 Status::EX_NULL_POINTER,
1119 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001120 }
yro74fed972017-11-27 14:42:42 -08001121 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001122 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001123 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001124 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1125 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001126 return Status::ok();
1127}
1128
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001129void StatsService::Startup() {
1130 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001131 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001132}
1133
Yangster-mac97e7d202018-10-09 11:05:39 -07001134void StatsService::Terminate() {
1135 ALOGI("StatsService::Terminating");
1136 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001137 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001138 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001139 }
1140}
1141
Yao Chen0f861862019-03-27 11:51:15 -07001142// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001143void StatsService::OnLogEvent(LogEvent* event) {
1144 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001145 if (mShellSubscriber != nullptr) {
1146 mShellSubscriber->onLogEvent(*event);
1147 }
Bookatz906a35c2017-09-20 15:26:44 -07001148}
1149
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001150Status StatsService::getData(int64_t key, const int32_t callingUid, vector<uint8_t>* output) {
1151 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001152
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001153 VLOG("StatsService::getData with Uid %i", callingUid);
1154 ConfigKey configKey(callingUid, key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001155 // The dump latency does not matter here since we do not include the current bucket, we do not
1156 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001157 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001158 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001159 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001160}
1161
Jeffrey Huang9613a972020-01-07 10:05:03 -08001162Status StatsService::getMetadata(vector<uint8_t>* output) {
1163 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001164
Bookatz4f716292018-04-10 17:15:12 -07001165 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1166 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001167}
1168
Jeff Sharkey6b649252018-04-16 09:50:22 -06001169Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001170 const int32_t callingUid) {
1171 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001172
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001173 if (addConfigurationChecked(callingUid, key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001174 return Status::ok();
1175 } else {
Bookatz4f716292018-04-10 17:15:12 -07001176 ALOGE("Could not parse malformatted StatsdConfig");
1177 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1178 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001179 }
1180}
1181
David Chen9fdd4032018-03-20 14:38:56 -07001182bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1183 ConfigKey configKey(uid, key);
1184 StatsdConfig cfg;
1185 if (config.size() > 0) { // If the config is empty, skip parsing.
1186 if (!cfg.ParseFromArray(&config[0], config.size())) {
1187 return false;
1188 }
1189 }
1190 mConfigManager->UpdateConfig(configKey, cfg);
1191 return true;
1192}
1193
Jeffrey Huangad213742019-12-16 13:50:06 -08001194Status StatsService::removeDataFetchOperation(int64_t key,
1195 const int32_t callingUid) {
1196 ENFORCE_UID(AID_SYSTEM);
1197 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001198 mConfigManager->RemoveConfigReceiver(configKey);
1199 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001200}
1201
Jeff Sharkey6b649252018-04-16 09:50:22 -06001202Status StatsService::setDataFetchOperation(int64_t key,
Jeffrey Huangad213742019-12-16 13:50:06 -08001203 const sp<IPendingIntentRef>& pir,
1204 const int32_t callingUid) {
1205 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001206
Jeffrey Huangad213742019-12-16 13:50:06 -08001207 ConfigKey configKey(callingUid, key);
1208 mConfigManager->SetConfigReceiver(configKey, pir);
David Chen48944902018-05-03 10:29:11 -07001209 if (StorageManager::hasConfigMetricsReport(configKey)) {
1210 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1211 configKey.ToString().c_str());
1212 mProcessor->noteOnDiskData(configKey);
1213 }
Bookatz4f716292018-04-10 17:15:12 -07001214 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001215}
1216
Jeffrey Huang47537a12020-01-06 15:35:34 -08001217Status StatsService::setActiveConfigsChangedOperation(const sp<IPendingIntentRef>& pir,
1218 const int32_t callingUid,
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001219 vector<int64_t>* output) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001220 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001221
Jeffrey Huang47537a12020-01-06 15:35:34 -08001222 mConfigManager->SetActiveConfigsChangedReceiver(callingUid, pir);
Tej Singh6ede28b2019-01-29 17:06:54 -08001223 if (output != nullptr) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001224 mProcessor->GetActiveConfigs(callingUid, *output);
Tej Singh6ede28b2019-01-29 17:06:54 -08001225 } else {
1226 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1227 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001228 return Status::ok();
1229}
1230
Jeffrey Huang47537a12020-01-06 15:35:34 -08001231Status StatsService::removeActiveConfigsChangedOperation(const int32_t callingUid) {
1232 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001233
Jeffrey Huang47537a12020-01-06 15:35:34 -08001234 mConfigManager->RemoveActiveConfigsChangedReceiver(callingUid);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001235 return Status::ok();
1236}
1237
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001238Status StatsService::removeConfiguration(int64_t key, const int32_t callingUid) {
1239 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001240
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001241 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001242 mConfigManager->RemoveConfig(configKey);
Bookatz4f716292018-04-10 17:15:12 -07001243 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001244}
1245
Bookatzc6977972018-01-16 16:55:05 -08001246Status StatsService::setBroadcastSubscriber(int64_t configId,
1247 int64_t subscriberId,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001248 const sp<IPendingIntentRef>& pir,
1249 const int32_t callingUid) {
1250 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001251
Bookatzc6977972018-01-16 16:55:05 -08001252 VLOG("StatsService::setBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001253 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001254 SubscriberReporter::getInstance()
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001255 .setBroadcastSubscriber(configKey, subscriberId, pir);
Bookatz4f716292018-04-10 17:15:12 -07001256 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001257}
1258
1259Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001260 int64_t subscriberId,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001261 const int32_t callingUid) {
1262 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001263
Bookatzc6977972018-01-16 16:55:05 -08001264 VLOG("StatsService::unsetBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001265 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001266 SubscriberReporter::getInstance()
1267 .unsetBroadcastSubscriber(configKey, subscriberId);
1268 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001269}
1270
yrobe6d7f92018-05-04 13:02:53 -07001271Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1272 // Permission check not necessary as it's meant for applications to write to
1273 // statsd.
1274 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
Jeff Sharkey6bd21572019-11-15 20:45:33 -07001275 (int32_t) IPCThreadState::self()->getCallingUid(), label,
yrobe6d7f92018-05-04 13:02:53 -07001276 state);
1277 return Status::ok();
1278}
1279
Tej Singh59184292019-10-11 11:07:06 -07001280Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownNs,
1281 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1282 const sp<android::os::IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001283 ENFORCE_UID(AID_SYSTEM);
1284
Tej Singhb7802512019-12-04 17:57:04 -08001285 VLOG("StatsService::registerPullAtomCallback called.");
1286 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1287 pullerCallback);
1288 return Status::ok();
1289}
1290
1291Status StatsService::registerNativePullAtomCallback(int32_t atomTag, int64_t coolDownNs,
1292 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1293 const sp<android::os::IPullAtomCallback>& pullerCallback) {
1294
1295 VLOG("StatsService::registerNativePullAtomCallback called.");
1296 int32_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh6a5c9432019-10-11 11:07:06 -07001297 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1298 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001299 return Status::ok();
1300}
1301
Tej Singhfa1c1372019-12-05 20:36:54 -08001302Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1303 ENFORCE_UID(AID_SYSTEM);
1304 VLOG("StatsService::unregisterPullAtomCallback called.");
1305 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1306 return Status::ok();
1307}
1308
Tej Singh8f358602020-01-15 16:05:39 -08001309Status StatsService::unregisterNativePullAtomCallback(int32_t atomTag) {
1310 VLOG("StatsService::unregisterNativePullAtomCallback called.");
1311 int32_t uid = IPCThreadState::self()->getCallingUid();
1312 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1313 return Status::ok();
1314}
1315
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001316Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainNameIn,
1317 const int64_t trainVersionCodeIn,
1318 const int options,
1319 const int32_t state,
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001320 const std::vector<int64_t>& experimentIdsIn) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001321 // Note: We skip the usage stats op check here since we do not have a package name.
1322 // This is ok since we are overloading the usage_stats permission.
1323 // This method only sends data, it does not receive it.
1324 pid_t pid = IPCThreadState::self()->getCallingPid();
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001325 uid_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh73f8e9b2019-05-19 16:52:38 -07001326 // Root, system, and shell always have access
Tej Singh53f9dee2019-04-30 17:45:54 -07001327 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1328 // Caller must be granted these permissions
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -08001329 if (!checkPermission(kPermissionDump)) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001330 return exception(binder::Status::EX_SECURITY,
1331 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1332 kPermissionDump));
1333 }
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -08001334 if (!checkPermission(kPermissionUsage)) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001335 return exception(binder::Status::EX_SECURITY,
1336 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1337 kPermissionUsage));
1338 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001339 }
1340
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001341 bool readTrainInfoSuccess = false;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001342 InstallTrainInfo trainInfoOnDisk;
1343 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001344
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001345 bool resetExperimentIds = false;
1346 int64_t trainVersionCode = trainVersionCodeIn;
1347 std::string trainNameUtf8 = std::string(String8(trainNameIn).string());
1348 if (readTrainInfoSuccess) {
1349 // Keep the old train version if we received an empty version.
1350 if (trainVersionCodeIn == -1) {
1351 trainVersionCode = trainInfoOnDisk.trainVersionCode;
1352 } else if (trainVersionCodeIn != trainInfoOnDisk.trainVersionCode) {
1353 // Reset experiment ids if we receive a new non-empty train version.
1354 resetExperimentIds = true;
1355 }
1356
1357 // Keep the old train name if we received an empty train name.
1358 if (trainNameUtf8.size() == 0) {
1359 trainNameUtf8 = trainInfoOnDisk.trainName;
1360 } else if (trainNameUtf8 != trainInfoOnDisk.trainName) {
1361 // Reset experiment ids if we received a new valid train name.
1362 resetExperimentIds = true;
1363 }
1364
1365 // Reset if we received a different experiment id.
1366 if (!experimentIdsIn.empty() &&
1367 (trainInfoOnDisk.experimentIds.empty() ||
1368 experimentIdsIn[0] != trainInfoOnDisk.experimentIds[0])) {
1369 resetExperimentIds = true;
1370 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001371 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001372
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001373 // Find the right experiment IDs
1374 std::vector<int64_t> experimentIds;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001375 if (resetExperimentIds || !readTrainInfoSuccess) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001376 experimentIds = experimentIdsIn;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001377 } else {
1378 experimentIds = trainInfoOnDisk.experimentIds;
1379 }
1380
1381 if (!experimentIds.empty()) {
1382 int64_t firstId = experimentIds[0];
1383 switch (state) {
1384 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
1385 experimentIds.push_back(firstId + 1);
1386 break;
1387 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
1388 experimentIds.push_back(firstId + 2);
1389 break;
1390 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
1391 experimentIds.push_back(firstId + 3);
1392 break;
1393 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001394 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001395
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001396 // Flatten the experiment IDs to proto
1397 vector<uint8_t> experimentIdsProtoBuffer;
1398 writeExperimentIdsToProto(experimentIds, &experimentIdsProtoBuffer);
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001399 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001400
1401 userid_t userId = multiuser_get_user_id(uid);
Jeffrey Huang161c0752019-12-11 14:47:32 -08001402 bool requiresStaging = options & IStatsd::FLAG_REQUIRE_STAGING;
1403 bool rollbackEnabled = options & IStatsd::FLAG_ROLLBACK_ENABLED;
1404 bool requiresLowLatencyMonitor = options & IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001405 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1406 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001407 mProcessor->OnLogEvent(&event);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001408 return Status::ok();
1409}
1410
Tej Singh73f8e9b2019-05-19 16:52:38 -07001411Status StatsService::sendWatchdogRollbackOccurredAtom(const int32_t rollbackTypeIn,
1412 const android::String16& packageNameIn,
Gavin Corkerydd1daba2019-11-27 19:11:13 +00001413 const int64_t packageVersionCodeIn,
1414 const int32_t rollbackReasonIn,
1415 const android::String16&
1416 failingPackageNameIn) {
Tej Singh73f8e9b2019-05-19 16:52:38 -07001417 // Note: We skip the usage stats op check here since we do not have a package name.
1418 // This is ok since we are overloading the usage_stats permission.
1419 // This method only sends data, it does not receive it.
1420 pid_t pid = IPCThreadState::self()->getCallingPid();
1421 uid_t uid = IPCThreadState::self()->getCallingUid();
1422 // Root, system, and shell always have access
1423 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1424 // Caller must be granted these permissions
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -08001425 if (!checkPermission(kPermissionDump)) {
Tej Singh73f8e9b2019-05-19 16:52:38 -07001426 return exception(binder::Status::EX_SECURITY,
1427 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1428 kPermissionDump));
1429 }
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -08001430 if (!checkPermission(kPermissionUsage)) {
Tej Singh73f8e9b2019-05-19 16:52:38 -07001431 return exception(binder::Status::EX_SECURITY,
1432 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1433 kPermissionUsage));
1434 }
1435 }
1436
1437 android::util::stats_write(android::util::WATCHDOG_ROLLBACK_OCCURRED,
Gavin Corkerydd1daba2019-11-27 19:11:13 +00001438 rollbackTypeIn, String8(packageNameIn).string(), packageVersionCodeIn,
1439 rollbackReasonIn, String8(failingPackageNameIn).string());
Tej Singh73f8e9b2019-05-19 16:52:38 -07001440
1441 // Fast return to save disk read.
1442 if (rollbackTypeIn != android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS
1443 && rollbackTypeIn !=
1444 android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE) {
1445 return Status::ok();
1446 }
1447
1448 bool readTrainInfoSuccess = false;
1449 InstallTrainInfo trainInfoOnDisk;
1450 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
1451
1452 if (!readTrainInfoSuccess) {
1453 return Status::ok();
1454 }
1455 std::vector<int64_t> experimentIds = trainInfoOnDisk.experimentIds;
1456 if (experimentIds.empty()) {
1457 return Status::ok();
1458 }
1459 switch (rollbackTypeIn) {
1460 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
1461 experimentIds.push_back(experimentIds[0] + 4);
1462 break;
1463 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
1464 experimentIds.push_back(experimentIds[0] + 5);
1465 break;
1466 }
1467 StorageManager::writeTrainInfo(trainInfoOnDisk.trainVersionCode, trainInfoOnDisk.trainName,
1468 trainInfoOnDisk.status, experimentIds);
1469 return Status::ok();
1470}
1471
1472
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001473Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
Jeffrey Huang80c9a972020-01-07 10:04:27 -08001474 ENFORCE_UID(AID_SYSTEM);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001475 // TODO: add verifier permission
1476
1477 // Read the latest train info
1478 InstallTrainInfo trainInfo;
1479 if (!StorageManager::readTrainInfo(trainInfo)) {
1480 // No train info means no experiment IDs, return an empty list
1481 experimentIdsOut->clear();
1482 return Status::ok();
1483 }
1484
1485 // Copy the experiment IDs to the out vector
1486 experimentIdsOut->assign(trainInfo.experimentIds.begin(), trainInfo.experimentIds.end());
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001487 return Status::ok();
1488}
1489
Howard Roa46b6582018-09-18 16:45:02 -07001490hardware::Return<void> StatsService::reportSpeakerImpedance(
1491 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001492 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1493 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001494
1495 return hardware::Void();
1496}
1497
1498hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001499 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1500 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001501
1502 return hardware::Void();
1503}
1504
1505hardware::Return<void> StatsService::reportPhysicalDropDetected(
1506 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001507 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1508 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1509 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001510
1511 return hardware::Void();
1512}
1513
1514hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001515 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1516 int initialSize = buckets.size();
1517 for (int i = 0; i < 10 - initialSize; i++) {
1518 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1519 }
1520 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1521 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1522 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001523
1524 return hardware::Void();
1525}
1526
1527hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1528 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001529 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1530 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1531 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1532 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1533 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001534
1535 return hardware::Void();
1536}
1537
1538hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001539 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001540
1541 return hardware::Void();
1542}
1543
1544hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1545 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001546 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1547 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001548
1549 return hardware::Void();
1550}
1551
Maggie Whitefc1aa592018-11-28 21:55:23 -08001552hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1553 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001554 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1555 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1556 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1557 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001558
1559 return hardware::Void();
1560}
1561
Carter Hsub8fd1e92019-01-11 15:24:45 +08001562hardware::Return<void> StatsService::reportSpeechDspStat(
1563 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001564 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1565 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1566 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001567
1568 return hardware::Void();
1569}
1570
Maggie White58174da2019-01-18 15:23:35 -08001571hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1572 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1573 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1574 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1575 return hardware::Void();
1576 }
1577 if (reverseDomainName.length() > 50) {
1578 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1579 return hardware::Void();
1580 }
1581 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1582 mProcessor->OnLogEvent(&event);
1583
1584 return hardware::Void();
1585}
1586
David Chen1d7b0cd2017-11-15 14:20:04 -08001587void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001588 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001589 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1590 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001591 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001592 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1593 ProtoOutputStream proto;
1594 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1595 STATSCOMPANION_DIED, &proto);
1596
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001597 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001598 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001599
1600 std::string serializedActiveConfigs;
1601 if (proto.serializeToString(&serializedActiveConfigs)) {
1602 ActiveConfigList activeConfigs;
1603 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1604 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1605 }
1606 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001607 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001608 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1609 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001610 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001611}
1612
Yao Chenef99c4f2017-09-22 16:26:54 -07001613} // namespace statsd
1614} // namespace os
1615} // namespace android