blob: 3a29b7271bbf6566e19982c0da633e198c1b669b [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>
Jeff Sharkey6b649252018-04-16 09:50:22 -060030#include <android-base/stringprintf.h>
Tej Singh53f9dee2019-04-30 17:45:54 -070031#include <android-base/strings.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060034#include <binder/PermissionController.h>
Chenjie Yu6b1667c2019-01-18 10:09:33 -080035#include <cutils/multiuser.h>
yro87d983c2017-11-14 21:31:43 -080036#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070037#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Max Dashouk11e0d402019-05-16 16:58:07 -070038#include <frameworks/base/cmds/statsd/src/uid_data.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070039#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080040#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070041#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070042#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070043#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070044#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070045#include <utils/Looper.h>
46#include <utils/String16.h>
47#include <chrono>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070048
49using namespace android;
50
Jeff Sharkey6b649252018-04-16 09:50:22 -060051using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070052using android::util::FIELD_COUNT_REPEATED;
Chenjie Yu6b1667c2019-01-18 10:09:33 -080053using android::util::FIELD_TYPE_INT64;
Bookatzff71cad2018-09-20 17:17:49 -070054using android::util::FIELD_TYPE_MESSAGE;
Joe Onorato99598ee2019-02-11 15:55:13 +000055using android::util::ProtoReader;
Jeff Sharkey6b649252018-04-16 09:50:22 -060056
Bookatz906a35c2017-09-20 15:26:44 -070057namespace android {
58namespace os {
59namespace statsd {
60
David Chenadaf8b32017-11-03 15:42:08 -070061constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060062constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
63
64constexpr const char* kOpUsage = "android:get_usage_stats";
65
yro03faf092017-12-12 00:17:50 -080066#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070067
Bookatzff71cad2018-09-20 17:17:49 -070068// for StatsDataDumpProto
69const int FIELD_ID_REPORTS_LIST = 1;
70
Jeff Sharkey6b649252018-04-16 09:50:22 -060071static binder::Status ok() {
72 return binder::Status::ok();
73}
74
75static binder::Status exception(uint32_t code, const std::string& msg) {
76 ALOGE("%s (%d)", msg.c_str(), code);
77 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
78}
79
80binder::Status checkUid(uid_t expectedUid) {
81 uid_t uid = IPCThreadState::self()->getCallingUid();
82 if (uid == expectedUid || uid == AID_ROOT) {
83 return ok();
84 } else {
85 return exception(binder::Status::EX_SECURITY,
86 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
87 }
88}
89
90binder::Status checkDumpAndUsageStats(const String16& packageName) {
91 pid_t pid = IPCThreadState::self()->getCallingPid();
92 uid_t uid = IPCThreadState::self()->getCallingUid();
93
94 // Root, system, and shell always have access
95 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
96 return ok();
97 }
98
99 // Caller must be granted these permissions
100 if (!checkCallingPermission(String16(kPermissionDump))) {
101 return exception(binder::Status::EX_SECURITY,
102 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
103 }
104 if (!checkCallingPermission(String16(kPermissionUsage))) {
105 return exception(binder::Status::EX_SECURITY,
106 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
107 }
108
109 // Caller must also have usage stats op granted
110 PermissionController pc;
111 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
112 case PermissionController::MODE_ALLOWED:
113 case PermissionController::MODE_DEFAULT:
114 return ok();
115 default:
116 return exception(binder::Status::EX_SECURITY,
117 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
118 }
119}
120
121#define ENFORCE_UID(uid) { \
122 binder::Status status = checkUid((uid)); \
123 if (!status.isOk()) { \
124 return status; \
125 } \
126}
127
128#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
129 binder::Status status = checkDumpAndUsageStats(packageName); \
130 if (!status.isOk()) { \
131 return status; \
132 } \
133}
134
Yao Chen0f861862019-03-27 11:51:15 -0700135StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
136 : mAnomalyAlarmMonitor(new AlarmMonitor(
137 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
138 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
139 if (sc != nullptr) {
140 sc->setAnomalyAlarm(timeMillis);
141 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
142 }
143 },
144 [](const sp<IStatsCompanionService>& sc) {
145 if (sc != nullptr) {
146 sc->cancelAnomalyAlarm();
147 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
148 }
149 })),
150 mPeriodicAlarmMonitor(new AlarmMonitor(
151 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
152 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
153 if (sc != nullptr) {
154 sc->setAlarmForSubscriberTriggering(timeMillis);
155 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
156 }
157 },
158 [](const sp<IStatsCompanionService>& sc) {
159 if (sc != nullptr) {
160 sc->cancelAlarmForSubscriberTriggering();
161 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
162 }
163 })),
164 mEventQueue(queue) {
Yao Chen4ce07292019-02-13 13:06:36 -0800165 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700166 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800167 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700168 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700169 mProcessor = new StatsLogProcessor(
170 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800171 getElapsedRealtimeNs(),
172 [this](const ConfigKey& key) {
Jeffrey Huangad213742019-12-16 13:50:06 -0800173 sp<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
174 if (receiver == nullptr) {
175 VLOG("Could not find a broadcast receiver for %s",
176 key.ToString().c_str());
Chenjie Yue2219202018-06-08 10:07:51 -0700177 return false;
Jeffrey Huangad213742019-12-16 13:50:06 -0800178 } else if (receiver->sendDataBroadcast(
179 mProcessor->getLastReportTimeNs(key)).isOk()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700180 return true;
Jeffrey Huangad213742019-12-16 13:50:06 -0800181 } else {
182 VLOG("Failed to send a broadcast for receiver %s",
183 key.ToString().c_str());
184 return false;
Chenjie Yue2219202018-06-08 10:07:51 -0700185 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800186 },
187 [this](const int& uid, const vector<int64_t>& activeConfigs) {
Jeffrey Huang47537a12020-01-06 15:35:34 -0800188 sp<IPendingIntentRef> receiver =
189 mConfigManager->GetActiveConfigsChangedReceiver(uid);
190 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800191 VLOG("Could not find receiver for uid %d", uid);
192 return false;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800193 } else if (receiver->sendActiveConfigsChangedBroadcast(activeConfigs).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800194 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
195 return true;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800196 } else {
197 VLOG("StatsService::active configs broadcast failed for uid %d" , uid);
198 return false;
Tej Singh6ede28b2019-01-29 17:06:54 -0800199 }
Chenjie Yue2219202018-06-08 10:07:51 -0700200 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700201
Tej Singh9ec159a2019-11-14 11:59:48 -0800202 mUidMap->setListener(mProcessor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700203 mConfigManager->AddListener(mProcessor);
204
205 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700206
207 if (mEventQueue != nullptr) {
208 std::thread pushedEventThread([this] { readLogs(); });
209 pushedEventThread.detach();
210 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700211}
212
Yao Chenef99c4f2017-09-22 16:26:54 -0700213StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700214}
215
Yao Chen0f861862019-03-27 11:51:15 -0700216/* Runs on a dedicated thread to process pushed events. */
217void StatsService::readLogs() {
218 // Read forever..... long live statsd
219 while (1) {
220 // Block until an event is available.
221 auto event = mEventQueue->waitPop();
222 // Pass it to StatsLogProcess to all configs/metrics
223 // At this point, the LogEventQueue is not blocked, so that the socketListener
224 // can read events from the socket and write to buffer to avoid data drop.
225 mProcessor->OnLogEvent(event.get());
226 // The ShellSubscriber is only used by shell for local debugging.
227 if (mShellSubscriber != nullptr) {
228 mShellSubscriber->onLogEvent(*event);
229 }
230 }
231}
232
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700233void StatsService::init_system_properties() {
234 mEngBuild = false;
235 const prop_info* buildType = __system_property_find("ro.build.type");
236 if (buildType != NULL) {
237 __system_property_read_callback(buildType, init_build_type_callback, this);
238 }
David Chen0656b7a2017-09-13 15:53:39 -0700239}
240
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700241void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
242 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700243 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700244 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
245 }
246}
247
248/**
249 * Implement our own because the default binder implementation isn't
250 * properly handling SHELL_COMMAND_TRANSACTION.
251 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700252status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
253 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700254 switch (code) {
255 case SHELL_COMMAND_TRANSACTION: {
256 int in = data.readFileDescriptor();
257 int out = data.readFileDescriptor();
258 int err = data.readFileDescriptor();
259 int argc = data.readInt32();
260 Vector<String8> args;
261 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
262 args.add(String8(data.readString16()));
263 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700264 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
265 sp<IResultReceiver> resultReceiver =
266 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700267
Yao Chena80e5c02018-09-04 13:55:29 -0700268 err = command(in, out, err, args, resultReceiver);
Tej Singhc9250ce2019-09-20 19:28:53 -0700269 if (resultReceiver != nullptr) {
270 resultReceiver->send(err);
271 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700272 return NO_ERROR;
273 }
Jeffrey Huang161c0752019-12-11 14:47:32 -0800274 default: { return BnStatsd::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700275 }
276}
277
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700278/**
Bookatzff71cad2018-09-20 17:17:49 -0700279 * Write data from statsd.
280 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
281 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
282 * Anything ending in --proto will be in proto format.
283 * Anything without --metadata as the first argument will be report information.
284 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
285 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700286 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700287status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700288 if (!checkCallingPermission(String16(kPermissionDump))) {
289 return PERMISSION_DENIED;
290 }
Bookatzff71cad2018-09-20 17:17:49 -0700291 int lastArg = args.size() - 1;
292 bool asProto = false;
293 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
294 asProto = true;
295 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800296 }
Bookatzff71cad2018-09-20 17:17:49 -0700297 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
298 // Request is to dump statsd stats.
299 bool verbose = false;
300 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
301 verbose = true;
302 lastArg--;
303 }
304 dumpStatsdStats(fd, verbose, asProto);
305 } else {
306 // Request is to dump statsd report data.
307 if (asProto) {
308 dumpIncidentSection(fd);
309 } else {
310 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
311 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700312 }
Yao Chen884c8c12018-01-26 10:36:25 -0800313
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700314 return NO_ERROR;
315}
316
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700317/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700318 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700319 */
Bookatzff71cad2018-09-20 17:17:49 -0700320void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700321 if (proto) {
322 vector<uint8_t> data;
323 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
324 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700325 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700326 }
327 } else {
328 StatsdStats::getInstance().dumpStats(out);
329 mProcessor->dumpStates(out, verbose);
330 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700331}
332
333/**
Bookatzff71cad2018-09-20 17:17:49 -0700334 * Write stats report data in StatsDataDumpProto incident section format.
335 */
336void StatsService::dumpIncidentSection(int out) {
337 ProtoOutputStream proto;
338 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
339 uint64_t reportsListToken =
340 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
341 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
342 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000343 ADB_DUMP,
344 FAST,
345 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700346 proto.end(reportsListToken);
347 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800348 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700349 }
350}
351
352/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700353 * Implementation of the adb shell cmd stats command.
354 */
Yao Chena80e5c02018-09-04 13:55:29 -0700355status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
356 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600357 uid_t uid = IPCThreadState::self()->getCallingUid();
358 if (uid != AID_ROOT && uid != AID_SHELL) {
359 return PERMISSION_DENIED;
360 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700361
362 const int argCount = args.size();
363 if (argCount >= 1) {
364 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700365 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700366 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700367 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700368
David Chende701692017-10-05 13:16:02 -0700369 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800370 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700371 }
Yao Chen729093d2017-10-16 10:33:26 -0700372
373 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700374 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700375 }
David Chen1481fe12017-10-16 13:16:34 -0700376
377 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
378 return cmd_print_pulled_metrics(out, args);
379 }
David Chenadaf8b32017-11-03 15:42:08 -0700380
381 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800382 return cmd_trigger_broadcast(out, args);
383 }
384
385 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800386 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700387 }
yro87d983c2017-11-14 21:31:43 -0800388
Yao Chen8d9989b2017-11-18 18:54:50 -0800389 if (!args[0].compare(String8("meminfo"))) {
390 return cmd_dump_memory_info(out);
391 }
yro947fbce2017-11-15 22:50:23 -0800392
393 if (!args[0].compare(String8("write-to-disk"))) {
394 return cmd_write_data_to_disk(out);
395 }
Bookatzb223c4e2018-02-01 15:35:04 -0800396
David Chen0b5c90c2018-01-25 16:51:49 -0800397 if (!args[0].compare(String8("log-app-breadcrumb"))) {
398 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800399 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800400
Tej Singh53f9dee2019-04-30 17:45:54 -0700401 if (!args[0].compare(String8("log-binary-push"))) {
402 return cmd_log_binary_push(out, args);
403 }
404
Chenjie Yufa22d652018-02-05 14:37:48 -0800405 if (!args[0].compare(String8("clear-puller-cache"))) {
406 return cmd_clear_puller_cache(out);
407 }
Yao Chen876889c2018-05-02 11:16:16 -0700408
409 if (!args[0].compare(String8("print-logs"))) {
410 return cmd_print_logs(out, args);
411 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800412 if (!args[0].compare(String8("send-active-configs"))) {
413 return cmd_trigger_active_config_broadcast(out, args);
414 }
Yao Chena80e5c02018-09-04 13:55:29 -0700415 if (!args[0].compare(String8("data-subscribe"))) {
Tej Singhc9250ce2019-09-20 19:28:53 -0700416 {
417 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
418 if (mShellSubscriber == nullptr) {
419 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
420 }
Yao Chena80e5c02018-09-04 13:55:29 -0700421 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800422 int timeoutSec = -1;
423 if (argCount >= 2) {
424 timeoutSec = atoi(args[1].c_str());
425 }
Tej Singhc9250ce2019-09-20 19:28:53 -0700426 if (resultReceiver == nullptr) {
427 ALOGI("Null resultReceiver given, no subscription will be started");
428 return UNEXPECTED_NULL;
429 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800430 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700431 return NO_ERROR;
432 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700433 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700434
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700435 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700436 return NO_ERROR;
437}
438
Yao Chena80e5c02018-09-04 13:55:29 -0700439void StatsService::print_cmd_help(int out) {
440 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700441 "usage: adb shell cmd stats print-stats-log [tag_required] "
442 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700443 dprintf(out, "\n");
444 dprintf(out, "\n");
445 dprintf(out, "usage: adb shell cmd stats meminfo\n");
446 dprintf(out, "\n");
447 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
448 dprintf(out, " # adb shell stop\n");
449 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
450 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
451 dprintf(out, " # adb shell start\n");
452 dprintf(out, "\n");
453 dprintf(out, "\n");
454 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
455 dprintf(out, "\n");
456 dprintf(out, " Prints the UID, app name, version mapping.\n");
457 dprintf(out, " PKG Optional package name to print the uids of the package\n");
458 dprintf(out, "\n");
459 dprintf(out, "\n");
460 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
461 dprintf(out, "\n");
462 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
463 dprintf(out, "\n");
464 dprintf(out, "\n");
465 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
466 dprintf(out, "\n");
467 dprintf(out, " Flushes all data on memory to disk.\n");
468 dprintf(out, "\n");
469 dprintf(out, "\n");
470 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
471 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
472 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
473 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
474 dprintf(out, " uid is used.\n");
475 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
476 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
477 dprintf(out, "\n");
478 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700479 dprintf(out,
480 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
481 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
482 dprintf(out, " Log a binary push state changed event.\n");
483 dprintf(out, " NAME The train name.\n");
484 dprintf(out, " VERSION The train version code.\n");
485 dprintf(out, " STAGING If this train requires a restart.\n");
486 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
487 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
488 dprintf(out, " STATE The status of the train push.\n");
489 dprintf(out, " Integer value of the enum in atoms.proto.\n");
490 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
491 dprintf(out, " Leave blank for none.\n");
492 dprintf(out, "\n");
493 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700494 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
495 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
496 dprintf(out, "\n");
497 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
498 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
499 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
500 dprintf(out, "\n");
501 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
502 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
503 dprintf(out, " uid is used.\n");
504 dprintf(out, " NAME The per-uid name to use\n");
505 dprintf(out, "\n");
506 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
507 dprintf(out, "\n be removed from memory and disk!\n");
508 dprintf(out, "\n");
509 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800510 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
511 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700512 dprintf(out, " Dump all metric data for a configuration.\n");
513 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
514 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
515 dprintf(out, " calling uid is used.\n");
516 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800517 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700518 dprintf(out, " --proto Print proto binary.\n");
519 dprintf(out, "\n");
520 dprintf(out, "\n");
521 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
522 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
523 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
524 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
525 dprintf(out, " calling uid is used.\n");
526 dprintf(out, " NAME The name of the configuration\n");
527 dprintf(out, "\n");
528 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800529 dprintf(out,
530 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
531 "[NAME1] [NAME2] [NAME3..]\n");
532 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
533 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
534 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
535 dprintf(out, " calling uid is used.\n");
536 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
537 dprintf(out, " the currently active configs\n");
538 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800539 dprintf(out, "\n");
540 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700541 dprintf(out, "usage: adb shell cmd stats print-stats\n");
542 dprintf(out, " Prints some basic stats.\n");
543 dprintf(out, " --proto Print proto binary instead of string format.\n");
544 dprintf(out, "\n");
545 dprintf(out, "\n");
546 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
547 dprintf(out, " Clear cached puller data.\n");
548 dprintf(out, "\n");
549 dprintf(out, "usage: adb shell cmd stats print-logs\n");
550 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700551}
552
Yao Chena80e5c02018-09-04 13:55:29 -0700553status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800554 string name;
555 bool good = false;
556 int uid;
557 const int argCount = args.size();
558 if (argCount == 2) {
559 // Automatically pick the UID
560 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800561 name.assign(args[1].c_str(), args[1].size());
562 good = true;
563 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800564 good = getUidFromArgs(args, 1, uid);
565 if (!good) {
566 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
567 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800568 }
Bookatzd2386572018-12-14 15:53:14 -0800569 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800570 }
571 if (!good) {
572 print_cmd_help(out);
573 return UNKNOWN_ERROR;
574 }
David Chend37bc232018-04-12 18:05:11 -0700575 ConfigKey key(uid, StrToInt64(name));
Jeffrey Huangad213742019-12-16 13:50:06 -0800576 sp<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
577 if (receiver == nullptr) {
578 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
579 return UNKNOWN_ERROR;
580 } else if (receiver->sendDataBroadcast(
581 mProcessor->getLastReportTimeNs(key)).isOk()) {
yro74fed972017-11-27 14:42:42 -0800582 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
583 args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800584 } else {
585 VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(),
586 args[2].c_str());
587 return UNKNOWN_ERROR;
yro4d889e62017-11-17 15:44:48 -0800588 }
David Chenadaf8b32017-11-03 15:42:08 -0700589 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700590}
591
Tej Singh6ede28b2019-01-29 17:06:54 -0800592status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
593 const int argCount = args.size();
594 int uid;
595 vector<int64_t> configIds;
596 if (argCount == 1) {
597 // Automatically pick the uid and send a broadcast that has no active configs.
598 uid = IPCThreadState::self()->getCallingUid();
599 mProcessor->GetActiveConfigs(uid, configIds);
600 } else {
601 int curArg = 1;
602 if(args[curArg].find("--uid=") == 0) {
603 string uidArgStr(args[curArg].c_str());
604 string uidStr = uidArgStr.substr(6);
605 if (!getUidFromString(uidStr.c_str(), uid)) {
606 dprintf(out, "Invalid UID. Note that the config can only be set for "
607 "other UIDs on eng or userdebug builds.\n");
608 return UNKNOWN_ERROR;
609 }
610 curArg++;
611 } else {
612 uid = IPCThreadState::self()->getCallingUid();
613 }
614 if (curArg == argCount || args[curArg] != "--configs") {
615 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
616 mProcessor->GetActiveConfigs(uid, configIds);
617 } else {
618 // Flag specified, use the given list of configs.
619 curArg++;
620 for (int i = curArg; i < argCount; i++) {
621 char* endp;
622 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
623 if (endp == args[i].c_str() || *endp != '\0') {
624 dprintf(out, "Error parsing config ID.\n");
625 return UNKNOWN_ERROR;
626 }
627 VLOG("Adding config id %ld", static_cast<long>(configID));
628 configIds.push_back(configID);
629 }
630 }
631 }
Jeffrey Huang47537a12020-01-06 15:35:34 -0800632 sp<IPendingIntentRef> receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
633 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800634 VLOG("Could not find receiver for uid %d", uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800635 return UNKNOWN_ERROR;
636 } else if (receiver->sendActiveConfigsChangedBroadcast(configIds).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800637 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800638 } else {
639 VLOG("StatsService::trigger active configs changed broadcast failed for uid %d", uid);
640 return UNKNOWN_ERROR;
Tej Singh6ede28b2019-01-29 17:06:54 -0800641 }
642 return NO_ERROR;
643}
644
Yao Chena80e5c02018-09-04 13:55:29 -0700645status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700646 const int argCount = args.size();
647 if (argCount >= 2) {
648 if (args[1] == "update" || args[1] == "remove") {
649 bool good = false;
650 int uid = -1;
651 string name;
652
653 if (argCount == 3) {
654 // Automatically pick the UID
655 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700656 name.assign(args[2].c_str(), args[2].size());
657 good = true;
658 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800659 good = getUidFromArgs(args, 2, uid);
660 if (!good) {
661 dprintf(err, "Invalid UID. Note that the config can only be set for "
662 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700663 }
Bookatzd2386572018-12-14 15:53:14 -0800664 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800665 } else if (argCount == 2 && args[1] == "remove") {
666 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700667 }
668
669 if (!good) {
670 // If arg parsing failed, print the help text and return an error.
671 print_cmd_help(out);
672 return UNKNOWN_ERROR;
673 }
674
675 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800676 char* endp;
677 int64_t configID = strtoll(name.c_str(), &endp, 10);
678 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700679 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800680 return UNKNOWN_ERROR;
681 }
682
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700683 // Read stream into buffer.
684 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700685 if (!android::base::ReadFdToString(in, &buffer)) {
686 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700687 return UNKNOWN_ERROR;
688 }
689
690 // Parse buffer.
691 StatsdConfig config;
692 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700693 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700694 return UNKNOWN_ERROR;
695 }
696
697 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800698 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700699 } else {
yro74fed972017-11-27 14:42:42 -0800700 if (argCount == 2) {
701 cmd_remove_all_configs(out);
702 } else {
703 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800704 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800705 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700706 }
707
708 return NO_ERROR;
709 }
David Chen0656b7a2017-09-13 15:53:39 -0700710 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700711 print_cmd_help(out);
712 return UNKNOWN_ERROR;
713}
714
Bookatzff71cad2018-09-20 17:17:49 -0700715status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700716 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800717 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700718 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800719 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700720 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800721 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700722 int uid;
723 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800724 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
725 proto = true;
726 argCount -= 1;
727 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700728 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
729 includeCurrentBucket = true;
730 argCount -= 1;
731 }
Bookatz3e906582018-12-10 17:26:58 -0800732 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
733 eraseData = false;
734 argCount -= 1;
735 }
Yao Chen729093d2017-10-16 10:33:26 -0700736 if (argCount == 2) {
737 // Automatically pick the UID
738 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700739 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700740 good = true;
741 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800742 good = getUidFromArgs(args, 1, uid);
743 if (!good) {
744 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
745 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700746 }
Bookatzd2386572018-12-14 15:53:14 -0800747 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700748 }
749 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800750 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800751 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000752 includeCurrentBucket, eraseData, ADB_DUMP,
753 NO_TIME_CONSTRAINTS,
754 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800755 if (proto) {
756 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700757 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800758 }
759 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700760 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800761 }
Yao Chen729093d2017-10-16 10:33:26 -0700762 return android::OK;
763 } else {
764 // If arg parsing failed, print the help text and return an error.
765 print_cmd_help(out);
766 return UNKNOWN_ERROR;
767 }
768 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700769 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700770 return UNKNOWN_ERROR;
771 }
772}
773
Yao Chena80e5c02018-09-04 13:55:29 -0700774status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700775 int argCount = args.size();
776 bool proto = false;
777 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
778 proto = true;
779 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800780 }
Yao Chenb3561512017-11-21 18:07:17 -0800781 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700782 if (proto) {
783 vector<uint8_t> data;
784 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
785 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700786 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700787 }
788
789 } else {
790 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
791 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700792 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700793 mProcessor->GetMetricsSize(key));
794 }
795 statsdStats.dumpStats(out);
796 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800797 return NO_ERROR;
798}
799
Yao Chena80e5c02018-09-04 13:55:29 -0700800status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800801 if (args.size() > 1) {
802 string pkg;
803 pkg.assign(args[1].c_str(), args[1].size());
804 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700805 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800806 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700807 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800808 }
Yao Chena80e5c02018-09-04 13:55:29 -0700809 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800810 } else {
811 mUidMap->printUidMap(out);
812 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700813 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700814}
815
Yao Chena80e5c02018-09-04 13:55:29 -0700816status_t StatsService::cmd_write_data_to_disk(int out) {
817 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000818 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800819 return NO_ERROR;
820}
821
Yao Chena80e5c02018-09-04 13:55:29 -0700822status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800823 bool good = false;
824 int32_t uid;
825 int32_t label;
826 int32_t state;
827 const int argCount = args.size();
828 if (argCount == 3) {
829 // Automatically pick the UID
830 uid = IPCThreadState::self()->getCallingUid();
831 label = atoi(args[1].c_str());
832 state = atoi(args[2].c_str());
833 good = true;
834 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800835 good = getUidFromArgs(args, 1, uid);
836 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700837 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800838 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
839 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800840 }
Bookatzd2386572018-12-14 15:53:14 -0800841 label = atoi(args[2].c_str());
842 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800843 }
844 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700845 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800846 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800847 } else {
848 print_cmd_help(out);
849 return UNKNOWN_ERROR;
850 }
851 return NO_ERROR;
852}
853
Tej Singh53f9dee2019-04-30 17:45:54 -0700854status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
855 // Security checks are done in the sendBinaryPushStateChanged atom.
856 const int argCount = args.size();
857 if (argCount != 7 && argCount != 8) {
858 dprintf(out, "Incorrect number of argument supplied\n");
859 return UNKNOWN_ERROR;
860 }
861 android::String16 trainName = android::String16(args[1].c_str());
862 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
863 int options = 0;
864 if (args[3] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800865 options = options | IStatsd::FLAG_REQUIRE_STAGING;
Tej Singh53f9dee2019-04-30 17:45:54 -0700866 }
867 if (args[4] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800868 options = options | IStatsd::FLAG_ROLLBACK_ENABLED;
Tej Singh53f9dee2019-04-30 17:45:54 -0700869 }
870 if (args[5] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800871 options = options | IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Tej Singh53f9dee2019-04-30 17:45:54 -0700872 }
873 int32_t state = atoi(args[6].c_str());
874 vector<int64_t> experimentIds;
875 if (argCount == 8) {
876 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
877 for (string experimentIdString : experimentIdsString) {
878 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
879 experimentIds.push_back(experimentId);
880 }
881 }
882 dprintf(out, "Logging BinaryPushStateChanged\n");
883 sendBinaryPushStateChangedAtom(trainName, trainVersion, options, state, experimentIds);
884 return NO_ERROR;
885}
886
Yao Chena80e5c02018-09-04 13:55:29 -0700887status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700888 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700889 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800890 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700891 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700892 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700893 }
Yao Chena80e5c02018-09-04 13:55:29 -0700894 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700895 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700896 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700897 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700898}
899
Yao Chena80e5c02018-09-04 13:55:29 -0700900status_t StatsService::cmd_remove_all_configs(int out) {
901 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800902 VLOG("StatsService::cmd_remove_all_configs was called");
903 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800904 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800905 return NO_ERROR;
906}
907
Yao Chena80e5c02018-09-04 13:55:29 -0700908status_t StatsService::cmd_dump_memory_info(int out) {
909 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800910 return NO_ERROR;
911}
912
Yao Chena80e5c02018-09-04 13:55:29 -0700913status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800914 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800915 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
916 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800917 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700918 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700919 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800920 return NO_ERROR;
921 } else {
922 return PERMISSION_DENIED;
923 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800924}
925
Yao Chena80e5c02018-09-04 13:55:29 -0700926status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700927 IPCThreadState* ipc = IPCThreadState::self();
928 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
929 ipc->getCallingUid());
930 if (checkCallingPermission(String16(kPermissionDump))) {
931 bool enabled = true;
932 if (args.size() >= 2) {
933 enabled = atoi(args[1].c_str()) != 0;
934 }
935 mProcessor->setPrintLogs(enabled);
936 return NO_ERROR;
937 } else {
938 return PERMISSION_DENIED;
939 }
940}
941
Bookatzd2386572018-12-14 15:53:14 -0800942bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800943 return getUidFromString(args[uidArgIndex].c_str(), uid);
944}
945
946bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800947 if (*s == '\0') {
948 return false;
949 }
950 char* endc = NULL;
951 int64_t longUid = strtol(s, &endc, 0);
952 if (*endc != '\0') {
953 return false;
954 }
955 int32_t goodUid = static_cast<int32_t>(longUid);
956 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
957 return false; // It was not of uid_t type.
958 }
959 uid = goodUid;
960
961 int32_t callingUid = IPCThreadState::self()->getCallingUid();
962 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
963 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
964 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
965}
966
Max Dashouk11e0d402019-05-16 16:58:07 -0700967Status StatsService::informAllUidData(const ParcelFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600968 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700969 // Read stream into buffer.
970 string buffer;
971 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
972 return exception(Status::EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
973 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600974
Max Dashouk11e0d402019-05-16 16:58:07 -0700975 // Parse buffer.
976 UidData uidData;
977 if (!uidData.ParseFromString(buffer)) {
978 return exception(Status::EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
979 }
David Chende701692017-10-05 13:16:02 -0700980
Max Dashouk11e0d402019-05-16 16:58:07 -0700981 vector<String16> versionStrings;
982 vector<String16> installers;
983 vector<String16> packageNames;
984 vector<int32_t> uids;
985 vector<int64_t> versions;
986
987 const auto numEntries = uidData.app_info_size();
988 versionStrings.reserve(numEntries);
989 installers.reserve(numEntries);
990 packageNames.reserve(numEntries);
991 uids.reserve(numEntries);
992 versions.reserve(numEntries);
993
994 for (const auto& appInfo: uidData.app_info()) {
995 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
996 uids.push_back(appInfo.uid());
997 versions.push_back(appInfo.version());
998 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
999 installers.emplace_back(String16(appInfo.installer().c_str()));
1000 }
1001
1002 mUidMap->updateMap(getElapsedRealtimeNs(),
1003 uids,
1004 versions,
1005 versionStrings,
1006 packageNames,
1007 installers);
1008
1009 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -07001010 return Status::ok();
1011}
1012
dwchen730403e2018-10-29 11:41:56 -07001013Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
1014 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001015 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001016
Jeff Sharkey6b649252018-04-16 09:50:22 -06001017 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -07001018 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -07001019 return Status::ok();
1020}
1021
1022Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001023 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001024
Jeff Sharkey6b649252018-04-16 09:50:22 -06001025 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -07001026 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -08001027 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -07001028 return Status::ok();
1029}
1030
Yao Chenef99c4f2017-09-22 16:26:54 -07001031Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001032 ENFORCE_UID(AID_SYSTEM);
1033
yro74fed972017-11-27 14:42:42 -08001034 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001035 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001036 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1037 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1038 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -08001039 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -08001040 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -08001041 } else {
1042 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
1043 }
Bookatz1b0b1142017-09-08 11:58:42 -07001044 return Status::ok();
1045}
1046
Yangster-mac932ecec2018-02-01 10:23:52 -08001047Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001048 ENFORCE_UID(AID_SYSTEM);
1049
Yangster-mac932ecec2018-02-01 10:23:52 -08001050 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001051 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001052 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1053 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1054 if (alarmSet.size() > 0) {
1055 VLOG("Found periodic alarm fired.");
1056 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1057 } else {
1058 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1059 }
1060 return Status::ok();
1061}
1062
Yao Chenef99c4f2017-09-22 16:26:54 -07001063Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001064 ENFORCE_UID(AID_SYSTEM);
1065
yro74fed972017-11-27 14:42:42 -08001066 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001067 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001068 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001069 return Status::ok();
1070}
1071
Yao Chenef99c4f2017-09-22 16:26:54 -07001072Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001073 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001074
1075 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001076 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001077 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001078 return Status::ok();
1079}
1080
Yangster-mac892f3d32018-05-02 14:16:48 -07001081Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001082 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001083 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001084 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001085 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001086 return Status::ok();
1087}
1088
Yao Chenef99c4f2017-09-22 16:26:54 -07001089void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -07001090 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1091 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001092 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001093 statsCompanion->statsdReady();
1094 } else {
yro74fed972017-11-27 14:42:42 -08001095 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001096 }
1097}
1098
Yao Chenef99c4f2017-09-22 16:26:54 -07001099Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001100 ENFORCE_UID(AID_SYSTEM);
1101
yro74fed972017-11-27 14:42:42 -08001102 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001103 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1104 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001105 return Status::fromExceptionCode(
1106 Status::EX_NULL_POINTER,
1107 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001108 }
yro74fed972017-11-27 14:42:42 -08001109 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001110 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001111 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001112 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1113 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -08001114 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001115 return Status::ok();
1116}
1117
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001118void StatsService::Startup() {
1119 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001120 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001121}
1122
Yangster-mac97e7d202018-10-09 11:05:39 -07001123void StatsService::Terminate() {
1124 ALOGI("StatsService::Terminating");
1125 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001126 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001127 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001128 }
1129}
1130
Yao Chen0f861862019-03-27 11:51:15 -07001131// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001132void StatsService::OnLogEvent(LogEvent* event) {
1133 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001134 if (mShellSubscriber != nullptr) {
1135 mShellSubscriber->onLogEvent(*event);
1136 }
Bookatz906a35c2017-09-20 15:26:44 -07001137}
1138
Jeff Sharkey6b649252018-04-16 09:50:22 -06001139Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1140 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1141
David Chenadaf8b32017-11-03 15:42:08 -07001142 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001143 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001144 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001145 // The dump latency does not matter here since we do not include the current bucket, we do not
1146 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001147 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001148 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001149 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001150}
1151
Jeff Sharkey6b649252018-04-16 09:50:22 -06001152Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1153 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1154
David Chen2e8f3802017-11-22 10:56:48 -08001155 IPCThreadState* ipc = IPCThreadState::self();
1156 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1157 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001158 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1159 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001160}
1161
Jeff Sharkey6b649252018-04-16 09:50:22 -06001162Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1163 const String16& packageName) {
1164 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1165
David Chenadaf8b32017-11-03 15:42:08 -07001166 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001167 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001168 return Status::ok();
1169 } else {
Bookatz4f716292018-04-10 17:15:12 -07001170 ALOGE("Could not parse malformatted StatsdConfig");
1171 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1172 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001173 }
1174}
1175
David Chen9fdd4032018-03-20 14:38:56 -07001176bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1177 ConfigKey configKey(uid, key);
1178 StatsdConfig cfg;
1179 if (config.size() > 0) { // If the config is empty, skip parsing.
1180 if (!cfg.ParseFromArray(&config[0], config.size())) {
1181 return false;
1182 }
1183 }
1184 mConfigManager->UpdateConfig(configKey, cfg);
1185 return true;
1186}
1187
Jeffrey Huangad213742019-12-16 13:50:06 -08001188Status StatsService::removeDataFetchOperation(int64_t key,
1189 const int32_t callingUid) {
1190 ENFORCE_UID(AID_SYSTEM);
1191 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001192 mConfigManager->RemoveConfigReceiver(configKey);
1193 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001194}
1195
Jeff Sharkey6b649252018-04-16 09:50:22 -06001196Status StatsService::setDataFetchOperation(int64_t key,
Jeffrey Huangad213742019-12-16 13:50:06 -08001197 const sp<IPendingIntentRef>& pir,
1198 const int32_t callingUid) {
1199 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001200
Jeffrey Huangad213742019-12-16 13:50:06 -08001201 ConfigKey configKey(callingUid, key);
1202 mConfigManager->SetConfigReceiver(configKey, pir);
David Chen48944902018-05-03 10:29:11 -07001203 if (StorageManager::hasConfigMetricsReport(configKey)) {
1204 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1205 configKey.ToString().c_str());
1206 mProcessor->noteOnDiskData(configKey);
1207 }
Bookatz4f716292018-04-10 17:15:12 -07001208 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001209}
1210
Jeffrey Huang47537a12020-01-06 15:35:34 -08001211Status StatsService::setActiveConfigsChangedOperation(const sp<IPendingIntentRef>& pir,
1212 const int32_t callingUid,
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001213 vector<int64_t>* output) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001214 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001215
Jeffrey Huang47537a12020-01-06 15:35:34 -08001216 mConfigManager->SetActiveConfigsChangedReceiver(callingUid, pir);
Tej Singh6ede28b2019-01-29 17:06:54 -08001217 if (output != nullptr) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001218 mProcessor->GetActiveConfigs(callingUid, *output);
Tej Singh6ede28b2019-01-29 17:06:54 -08001219 } else {
1220 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1221 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001222 return Status::ok();
1223}
1224
Jeffrey Huang47537a12020-01-06 15:35:34 -08001225Status StatsService::removeActiveConfigsChangedOperation(const int32_t callingUid) {
1226 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001227
Jeffrey Huang47537a12020-01-06 15:35:34 -08001228 mConfigManager->RemoveActiveConfigsChangedReceiver(callingUid);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001229 return Status::ok();
1230}
1231
Jeff Sharkey6b649252018-04-16 09:50:22 -06001232Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1233 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1234
Bookatz4f716292018-04-10 17:15:12 -07001235 IPCThreadState* ipc = IPCThreadState::self();
1236 ConfigKey configKey(ipc->getCallingUid(), key);
1237 mConfigManager->RemoveConfig(configKey);
1238 SubscriberReporter::getInstance().removeConfig(configKey);
1239 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001240}
1241
Bookatzc6977972018-01-16 16:55:05 -08001242Status StatsService::setBroadcastSubscriber(int64_t configId,
1243 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001244 const sp<android::IBinder>& intentSender,
1245 const String16& packageName) {
1246 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1247
Bookatzc6977972018-01-16 16:55:05 -08001248 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001249 IPCThreadState* ipc = IPCThreadState::self();
1250 ConfigKey configKey(ipc->getCallingUid(), configId);
1251 SubscriberReporter::getInstance()
1252 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1253 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001254}
1255
1256Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001257 int64_t subscriberId,
1258 const String16& packageName) {
1259 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1260
Bookatzc6977972018-01-16 16:55:05 -08001261 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001262 IPCThreadState* ipc = IPCThreadState::self();
1263 ConfigKey configKey(ipc->getCallingUid(), configId);
1264 SubscriberReporter::getInstance()
1265 .unsetBroadcastSubscriber(configKey, subscriberId);
1266 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001267}
1268
yrobe6d7f92018-05-04 13:02:53 -07001269Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1270 // Permission check not necessary as it's meant for applications to write to
1271 // statsd.
1272 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
Jeff Sharkey6bd21572019-11-15 20:45:33 -07001273 (int32_t) IPCThreadState::self()->getCallingUid(), label,
yrobe6d7f92018-05-04 13:02:53 -07001274 state);
1275 return Status::ok();
1276}
1277
Tej Singha0c89dd2019-01-25 16:39:18 -08001278Status StatsService::registerPullerCallback(int32_t atomTag,
1279 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1280 const String16& packageName) {
1281 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1282
1283 VLOG("StatsService::registerPullerCallback called.");
1284 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1285 return Status::ok();
1286}
1287
Tej Singh59184292019-10-11 11:07:06 -07001288Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownNs,
1289 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1290 const sp<android::os::IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001291 ENFORCE_UID(AID_SYSTEM);
1292
Tej Singhb7802512019-12-04 17:57:04 -08001293 VLOG("StatsService::registerPullAtomCallback called.");
1294 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1295 pullerCallback);
1296 return Status::ok();
1297}
1298
1299Status StatsService::registerNativePullAtomCallback(int32_t atomTag, int64_t coolDownNs,
1300 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1301 const sp<android::os::IPullAtomCallback>& pullerCallback) {
1302
1303 VLOG("StatsService::registerNativePullAtomCallback called.");
1304 int32_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh6a5c9432019-10-11 11:07:06 -07001305 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1306 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001307 return Status::ok();
1308}
1309
Tej Singha0c89dd2019-01-25 16:39:18 -08001310Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1311 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1312
1313 VLOG("StatsService::unregisterPullerCallback called.");
1314 mPullerManager->UnregisterPullerCallback(atomTag);
1315 return Status::ok();
1316}
1317
Tej Singhfa1c1372019-12-05 20:36:54 -08001318Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1319 ENFORCE_UID(AID_SYSTEM);
1320 VLOG("StatsService::unregisterPullAtomCallback called.");
1321 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1322 return Status::ok();
1323}
1324
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001325Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainNameIn,
1326 const int64_t trainVersionCodeIn,
1327 const int options,
1328 const int32_t state,
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001329 const std::vector<int64_t>& experimentIdsIn) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001330 // Note: We skip the usage stats op check here since we do not have a package name.
1331 // This is ok since we are overloading the usage_stats permission.
1332 // This method only sends data, it does not receive it.
1333 pid_t pid = IPCThreadState::self()->getCallingPid();
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001334 uid_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh73f8e9b2019-05-19 16:52:38 -07001335 // Root, system, and shell always have access
Tej Singh53f9dee2019-04-30 17:45:54 -07001336 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1337 // Caller must be granted these permissions
1338 if (!checkCallingPermission(String16(kPermissionDump))) {
1339 return exception(binder::Status::EX_SECURITY,
1340 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1341 kPermissionDump));
1342 }
1343 if (!checkCallingPermission(String16(kPermissionUsage))) {
1344 return exception(binder::Status::EX_SECURITY,
1345 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1346 kPermissionUsage));
1347 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001348 }
1349
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001350 bool readTrainInfoSuccess = false;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001351 InstallTrainInfo trainInfoOnDisk;
1352 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001353
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001354 bool resetExperimentIds = false;
1355 int64_t trainVersionCode = trainVersionCodeIn;
1356 std::string trainNameUtf8 = std::string(String8(trainNameIn).string());
1357 if (readTrainInfoSuccess) {
1358 // Keep the old train version if we received an empty version.
1359 if (trainVersionCodeIn == -1) {
1360 trainVersionCode = trainInfoOnDisk.trainVersionCode;
1361 } else if (trainVersionCodeIn != trainInfoOnDisk.trainVersionCode) {
1362 // Reset experiment ids if we receive a new non-empty train version.
1363 resetExperimentIds = true;
1364 }
1365
1366 // Keep the old train name if we received an empty train name.
1367 if (trainNameUtf8.size() == 0) {
1368 trainNameUtf8 = trainInfoOnDisk.trainName;
1369 } else if (trainNameUtf8 != trainInfoOnDisk.trainName) {
1370 // Reset experiment ids if we received a new valid train name.
1371 resetExperimentIds = true;
1372 }
1373
1374 // Reset if we received a different experiment id.
1375 if (!experimentIdsIn.empty() &&
1376 (trainInfoOnDisk.experimentIds.empty() ||
1377 experimentIdsIn[0] != trainInfoOnDisk.experimentIds[0])) {
1378 resetExperimentIds = true;
1379 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001380 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001381
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001382 // Find the right experiment IDs
1383 std::vector<int64_t> experimentIds;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001384 if (resetExperimentIds || !readTrainInfoSuccess) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001385 experimentIds = experimentIdsIn;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001386 } else {
1387 experimentIds = trainInfoOnDisk.experimentIds;
1388 }
1389
1390 if (!experimentIds.empty()) {
1391 int64_t firstId = experimentIds[0];
1392 switch (state) {
1393 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
1394 experimentIds.push_back(firstId + 1);
1395 break;
1396 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
1397 experimentIds.push_back(firstId + 2);
1398 break;
1399 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
1400 experimentIds.push_back(firstId + 3);
1401 break;
1402 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001403 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001404
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001405 // Flatten the experiment IDs to proto
1406 vector<uint8_t> experimentIdsProtoBuffer;
1407 writeExperimentIdsToProto(experimentIds, &experimentIdsProtoBuffer);
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001408 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001409
1410 userid_t userId = multiuser_get_user_id(uid);
Jeffrey Huang161c0752019-12-11 14:47:32 -08001411 bool requiresStaging = options & IStatsd::FLAG_REQUIRE_STAGING;
1412 bool rollbackEnabled = options & IStatsd::FLAG_ROLLBACK_ENABLED;
1413 bool requiresLowLatencyMonitor = options & IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001414 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1415 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001416 mProcessor->OnLogEvent(&event);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001417 return Status::ok();
1418}
1419
Tej Singh73f8e9b2019-05-19 16:52:38 -07001420Status StatsService::sendWatchdogRollbackOccurredAtom(const int32_t rollbackTypeIn,
1421 const android::String16& packageNameIn,
Gavin Corkerydd1daba2019-11-27 19:11:13 +00001422 const int64_t packageVersionCodeIn,
1423 const int32_t rollbackReasonIn,
1424 const android::String16&
1425 failingPackageNameIn) {
Tej Singh73f8e9b2019-05-19 16:52:38 -07001426 // Note: We skip the usage stats op check here since we do not have a package name.
1427 // This is ok since we are overloading the usage_stats permission.
1428 // This method only sends data, it does not receive it.
1429 pid_t pid = IPCThreadState::self()->getCallingPid();
1430 uid_t uid = IPCThreadState::self()->getCallingUid();
1431 // Root, system, and shell always have access
1432 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1433 // Caller must be granted these permissions
1434 if (!checkCallingPermission(String16(kPermissionDump))) {
1435 return exception(binder::Status::EX_SECURITY,
1436 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1437 kPermissionDump));
1438 }
1439 if (!checkCallingPermission(String16(kPermissionUsage))) {
1440 return exception(binder::Status::EX_SECURITY,
1441 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1442 kPermissionUsage));
1443 }
1444 }
1445
1446 android::util::stats_write(android::util::WATCHDOG_ROLLBACK_OCCURRED,
Gavin Corkerydd1daba2019-11-27 19:11:13 +00001447 rollbackTypeIn, String8(packageNameIn).string(), packageVersionCodeIn,
1448 rollbackReasonIn, String8(failingPackageNameIn).string());
Tej Singh73f8e9b2019-05-19 16:52:38 -07001449
1450 // Fast return to save disk read.
1451 if (rollbackTypeIn != android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS
1452 && rollbackTypeIn !=
1453 android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE) {
1454 return Status::ok();
1455 }
1456
1457 bool readTrainInfoSuccess = false;
1458 InstallTrainInfo trainInfoOnDisk;
1459 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
1460
1461 if (!readTrainInfoSuccess) {
1462 return Status::ok();
1463 }
1464 std::vector<int64_t> experimentIds = trainInfoOnDisk.experimentIds;
1465 if (experimentIds.empty()) {
1466 return Status::ok();
1467 }
1468 switch (rollbackTypeIn) {
1469 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
1470 experimentIds.push_back(experimentIds[0] + 4);
1471 break;
1472 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
1473 experimentIds.push_back(experimentIds[0] + 5);
1474 break;
1475 }
1476 StorageManager::writeTrainInfo(trainInfoOnDisk.trainVersionCode, trainInfoOnDisk.trainName,
1477 trainInfoOnDisk.status, experimentIds);
1478 return Status::ok();
1479}
1480
1481
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001482Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
1483 uid_t uid = IPCThreadState::self()->getCallingUid();
1484
1485 // Caller must be granted these permissions
1486 if (!checkCallingPermission(String16(kPermissionDump))) {
1487 return exception(binder::Status::EX_SECURITY,
1488 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1489 }
1490 if (!checkCallingPermission(String16(kPermissionUsage))) {
1491 return exception(binder::Status::EX_SECURITY,
1492 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1493 }
1494 // TODO: add verifier permission
1495
1496 // Read the latest train info
1497 InstallTrainInfo trainInfo;
1498 if (!StorageManager::readTrainInfo(trainInfo)) {
1499 // No train info means no experiment IDs, return an empty list
1500 experimentIdsOut->clear();
1501 return Status::ok();
1502 }
1503
1504 // Copy the experiment IDs to the out vector
1505 experimentIdsOut->assign(trainInfo.experimentIds.begin(), trainInfo.experimentIds.end());
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001506 return Status::ok();
1507}
1508
Howard Roa46b6582018-09-18 16:45:02 -07001509hardware::Return<void> StatsService::reportSpeakerImpedance(
1510 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001511 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1512 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001513
1514 return hardware::Void();
1515}
1516
1517hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001518 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1519 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001520
1521 return hardware::Void();
1522}
1523
1524hardware::Return<void> StatsService::reportPhysicalDropDetected(
1525 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001526 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1527 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1528 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001529
1530 return hardware::Void();
1531}
1532
1533hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001534 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1535 int initialSize = buckets.size();
1536 for (int i = 0; i < 10 - initialSize; i++) {
1537 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1538 }
1539 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1540 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1541 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001542
1543 return hardware::Void();
1544}
1545
1546hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1547 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001548 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1549 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1550 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1551 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1552 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001553
1554 return hardware::Void();
1555}
1556
1557hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001558 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001559
1560 return hardware::Void();
1561}
1562
1563hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1564 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001565 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1566 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001567
1568 return hardware::Void();
1569}
1570
Maggie Whitefc1aa592018-11-28 21:55:23 -08001571hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1572 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001573 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1574 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1575 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1576 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001577
1578 return hardware::Void();
1579}
1580
Carter Hsub8fd1e92019-01-11 15:24:45 +08001581hardware::Return<void> StatsService::reportSpeechDspStat(
1582 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001583 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1584 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1585 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001586
1587 return hardware::Void();
1588}
1589
Maggie White58174da2019-01-18 15:23:35 -08001590hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1591 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1592 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1593 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1594 return hardware::Void();
1595 }
1596 if (reverseDomainName.length() > 50) {
1597 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1598 return hardware::Void();
1599 }
1600 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1601 mProcessor->OnLogEvent(&event);
1602
1603 return hardware::Void();
1604}
1605
David Chen1d7b0cd2017-11-15 14:20:04 -08001606void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001607 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001608 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1609 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001610 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001611 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1612 ProtoOutputStream proto;
1613 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1614 STATSCOMPANION_DIED, &proto);
1615
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001616 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001617 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001618
1619 std::string serializedActiveConfigs;
1620 if (proto.serializeToString(&serializedActiveConfigs)) {
1621 ActiveConfigList activeConfigs;
1622 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1623 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1624 }
1625 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001626 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001627 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1628 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1629 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001630 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001631}
1632
Yao Chenef99c4f2017-09-22 16:26:54 -07001633} // namespace statsd
1634} // namespace os
1635} // namespace android