blob: 3bcebd9e3f766a744b0a6b8da4e26423d7658913 [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>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070031#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060033#include <binder/PermissionController.h>
Chenjie Yu6b1667c2019-01-18 10:09:33 -080034#include <cutils/multiuser.h>
yro87d983c2017-11-14 21:31:43 -080035#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070036#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070037#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080038#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070039#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070040#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070041#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070042#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070043#include <utils/Looper.h>
44#include <utils/String16.h>
45#include <chrono>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070046
47using namespace android;
48
Jeff Sharkey6b649252018-04-16 09:50:22 -060049using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070050using android::util::FIELD_COUNT_REPEATED;
Chenjie Yu6b1667c2019-01-18 10:09:33 -080051using android::util::FIELD_TYPE_INT64;
Bookatzff71cad2018-09-20 17:17:49 -070052using android::util::FIELD_TYPE_MESSAGE;
Joe Onorato99598ee2019-02-11 15:55:13 +000053using android::util::ProtoReader;
Jeff Sharkey6b649252018-04-16 09:50:22 -060054
Bookatz906a35c2017-09-20 15:26:44 -070055namespace android {
56namespace os {
57namespace statsd {
58
David Chenadaf8b32017-11-03 15:42:08 -070059constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060060constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
61
62constexpr const char* kOpUsage = "android:get_usage_stats";
63
yro03faf092017-12-12 00:17:50 -080064#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070065
Bookatzff71cad2018-09-20 17:17:49 -070066// for StatsDataDumpProto
67const int FIELD_ID_REPORTS_LIST = 1;
68
Jeff Sharkey6b649252018-04-16 09:50:22 -060069static binder::Status ok() {
70 return binder::Status::ok();
71}
72
73static binder::Status exception(uint32_t code, const std::string& msg) {
74 ALOGE("%s (%d)", msg.c_str(), code);
75 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
76}
77
78binder::Status checkUid(uid_t expectedUid) {
79 uid_t uid = IPCThreadState::self()->getCallingUid();
80 if (uid == expectedUid || uid == AID_ROOT) {
81 return ok();
82 } else {
83 return exception(binder::Status::EX_SECURITY,
84 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
85 }
86}
87
88binder::Status checkDumpAndUsageStats(const String16& packageName) {
89 pid_t pid = IPCThreadState::self()->getCallingPid();
90 uid_t uid = IPCThreadState::self()->getCallingUid();
91
92 // Root, system, and shell always have access
93 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
94 return ok();
95 }
96
97 // Caller must be granted these permissions
98 if (!checkCallingPermission(String16(kPermissionDump))) {
99 return exception(binder::Status::EX_SECURITY,
100 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
101 }
102 if (!checkCallingPermission(String16(kPermissionUsage))) {
103 return exception(binder::Status::EX_SECURITY,
104 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
105 }
106
107 // Caller must also have usage stats op granted
108 PermissionController pc;
109 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
110 case PermissionController::MODE_ALLOWED:
111 case PermissionController::MODE_DEFAULT:
112 return ok();
113 default:
114 return exception(binder::Status::EX_SECURITY,
115 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
116 }
117}
118
119#define ENFORCE_UID(uid) { \
120 binder::Status status = checkUid((uid)); \
121 if (!status.isOk()) { \
122 return status; \
123 } \
124}
125
126#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
127 binder::Status status = checkDumpAndUsageStats(packageName); \
128 if (!status.isOk()) { \
129 return status; \
130 } \
131}
132
Yao Chen0f861862019-03-27 11:51:15 -0700133StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
134 : mAnomalyAlarmMonitor(new AlarmMonitor(
135 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
136 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
137 if (sc != nullptr) {
138 sc->setAnomalyAlarm(timeMillis);
139 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
140 }
141 },
142 [](const sp<IStatsCompanionService>& sc) {
143 if (sc != nullptr) {
144 sc->cancelAnomalyAlarm();
145 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
146 }
147 })),
148 mPeriodicAlarmMonitor(new AlarmMonitor(
149 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
150 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
151 if (sc != nullptr) {
152 sc->setAlarmForSubscriberTriggering(timeMillis);
153 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
154 }
155 },
156 [](const sp<IStatsCompanionService>& sc) {
157 if (sc != nullptr) {
158 sc->cancelAlarmForSubscriberTriggering();
159 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
160 }
161 })),
162 mEventQueue(queue) {
Yao Chen4ce07292019-02-13 13:06:36 -0800163 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700164 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800165 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700166 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700167 mProcessor = new StatsLogProcessor(
168 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800169 getElapsedRealtimeNs(),
170 [this](const ConfigKey& key) {
Chenjie Yue2219202018-06-08 10:07:51 -0700171 sp<IStatsCompanionService> sc = getStatsCompanionService();
172 auto receiver = mConfigManager->GetConfigReceiver(key);
173 if (sc == nullptr) {
174 VLOG("Could not find StatsCompanionService");
175 return false;
176 } else if (receiver == nullptr) {
177 VLOG("Statscompanion could not find a broadcast receiver for %s",
178 key.ToString().c_str());
179 return false;
180 } else {
181 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
182 return true;
183 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800184 },
185 [this](const int& uid, const vector<int64_t>& activeConfigs) {
186 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
187 sp<IStatsCompanionService> sc = getStatsCompanionService();
188 if (sc == nullptr) {
189 VLOG("Could not access statsCompanion");
190 return false;
191 } else if (receiver == nullptr) {
192 VLOG("Could not find receiver for uid %d", uid);
193 return false;
194 } else {
195 sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
196 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
197 return true;
198 }
Chenjie Yue2219202018-06-08 10:07:51 -0700199 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700200
201 mConfigManager->AddListener(mProcessor);
202
203 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700204
205 if (mEventQueue != nullptr) {
206 std::thread pushedEventThread([this] { readLogs(); });
207 pushedEventThread.detach();
208 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700209}
210
Yao Chenef99c4f2017-09-22 16:26:54 -0700211StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700212}
213
Yao Chen0f861862019-03-27 11:51:15 -0700214/* Runs on a dedicated thread to process pushed events. */
215void StatsService::readLogs() {
216 // Read forever..... long live statsd
217 while (1) {
218 // Block until an event is available.
219 auto event = mEventQueue->waitPop();
220 // Pass it to StatsLogProcess to all configs/metrics
221 // At this point, the LogEventQueue is not blocked, so that the socketListener
222 // can read events from the socket and write to buffer to avoid data drop.
223 mProcessor->OnLogEvent(event.get());
224 // The ShellSubscriber is only used by shell for local debugging.
225 if (mShellSubscriber != nullptr) {
226 mShellSubscriber->onLogEvent(*event);
227 }
228 }
229}
230
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700231void StatsService::init_system_properties() {
232 mEngBuild = false;
233 const prop_info* buildType = __system_property_find("ro.build.type");
234 if (buildType != NULL) {
235 __system_property_read_callback(buildType, init_build_type_callback, this);
236 }
David Chen0656b7a2017-09-13 15:53:39 -0700237}
238
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700239void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
240 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700241 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700242 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
243 }
244}
245
246/**
247 * Implement our own because the default binder implementation isn't
248 * properly handling SHELL_COMMAND_TRANSACTION.
249 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700250status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
251 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700252 switch (code) {
253 case SHELL_COMMAND_TRANSACTION: {
254 int in = data.readFileDescriptor();
255 int out = data.readFileDescriptor();
256 int err = data.readFileDescriptor();
257 int argc = data.readInt32();
258 Vector<String8> args;
259 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
260 args.add(String8(data.readString16()));
261 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700262 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
263 sp<IResultReceiver> resultReceiver =
264 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700265
Yao Chena80e5c02018-09-04 13:55:29 -0700266 err = command(in, out, err, args, resultReceiver);
267 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700268 return NO_ERROR;
269 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700270 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700271 }
272}
273
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700274/**
Bookatzff71cad2018-09-20 17:17:49 -0700275 * Write data from statsd.
276 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
277 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
278 * Anything ending in --proto will be in proto format.
279 * Anything without --metadata as the first argument will be report information.
280 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
281 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700282 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700283status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700284 if (!checkCallingPermission(String16(kPermissionDump))) {
285 return PERMISSION_DENIED;
286 }
Bookatzff71cad2018-09-20 17:17:49 -0700287 int lastArg = args.size() - 1;
288 bool asProto = false;
289 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
290 asProto = true;
291 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800292 }
Bookatzff71cad2018-09-20 17:17:49 -0700293 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
294 // Request is to dump statsd stats.
295 bool verbose = false;
296 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
297 verbose = true;
298 lastArg--;
299 }
300 dumpStatsdStats(fd, verbose, asProto);
301 } else {
302 // Request is to dump statsd report data.
303 if (asProto) {
304 dumpIncidentSection(fd);
305 } else {
306 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
307 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700308 }
Yao Chen884c8c12018-01-26 10:36:25 -0800309
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700310 return NO_ERROR;
311}
312
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700313/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700314 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700315 */
Bookatzff71cad2018-09-20 17:17:49 -0700316void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700317 if (proto) {
318 vector<uint8_t> data;
319 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
320 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700321 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700322 }
323 } else {
324 StatsdStats::getInstance().dumpStats(out);
325 mProcessor->dumpStates(out, verbose);
326 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700327}
328
329/**
Bookatzff71cad2018-09-20 17:17:49 -0700330 * Write stats report data in StatsDataDumpProto incident section format.
331 */
332void StatsService::dumpIncidentSection(int out) {
333 ProtoOutputStream proto;
334 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
335 uint64_t reportsListToken =
336 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
337 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
338 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000339 ADB_DUMP,
340 FAST,
341 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700342 proto.end(reportsListToken);
343 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800344 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700345 }
346}
347
348/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700349 * Implementation of the adb shell cmd stats command.
350 */
Yao Chena80e5c02018-09-04 13:55:29 -0700351status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
352 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600353 uid_t uid = IPCThreadState::self()->getCallingUid();
354 if (uid != AID_ROOT && uid != AID_SHELL) {
355 return PERMISSION_DENIED;
356 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700357
358 const int argCount = args.size();
359 if (argCount >= 1) {
360 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700361 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700362 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700363 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700364
David Chende701692017-10-05 13:16:02 -0700365 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800366 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700367 }
Yao Chen729093d2017-10-16 10:33:26 -0700368
369 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700370 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700371 }
David Chen1481fe12017-10-16 13:16:34 -0700372
373 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
374 return cmd_print_pulled_metrics(out, args);
375 }
David Chenadaf8b32017-11-03 15:42:08 -0700376
377 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800378 return cmd_trigger_broadcast(out, args);
379 }
380
381 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800382 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700383 }
yro87d983c2017-11-14 21:31:43 -0800384
Yao Chen8d9989b2017-11-18 18:54:50 -0800385 if (!args[0].compare(String8("meminfo"))) {
386 return cmd_dump_memory_info(out);
387 }
yro947fbce2017-11-15 22:50:23 -0800388
389 if (!args[0].compare(String8("write-to-disk"))) {
390 return cmd_write_data_to_disk(out);
391 }
Bookatzb223c4e2018-02-01 15:35:04 -0800392
David Chen0b5c90c2018-01-25 16:51:49 -0800393 if (!args[0].compare(String8("log-app-breadcrumb"))) {
394 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800395 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800396
397 if (!args[0].compare(String8("clear-puller-cache"))) {
398 return cmd_clear_puller_cache(out);
399 }
Yao Chen876889c2018-05-02 11:16:16 -0700400
401 if (!args[0].compare(String8("print-logs"))) {
402 return cmd_print_logs(out, args);
403 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800404 if (!args[0].compare(String8("send-active-configs"))) {
405 return cmd_trigger_active_config_broadcast(out, args);
406 }
Yao Chena80e5c02018-09-04 13:55:29 -0700407 if (!args[0].compare(String8("data-subscribe"))) {
408 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700409 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700410 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800411 int timeoutSec = -1;
412 if (argCount >= 2) {
413 timeoutSec = atoi(args[1].c_str());
414 }
415 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700416 return NO_ERROR;
417 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700418 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700419
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700420 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700421 return NO_ERROR;
422}
423
Yao Chena80e5c02018-09-04 13:55:29 -0700424void StatsService::print_cmd_help(int out) {
425 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700426 "usage: adb shell cmd stats print-stats-log [tag_required] "
427 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700428 dprintf(out, "\n");
429 dprintf(out, "\n");
430 dprintf(out, "usage: adb shell cmd stats meminfo\n");
431 dprintf(out, "\n");
432 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
433 dprintf(out, " # adb shell stop\n");
434 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
435 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
436 dprintf(out, " # adb shell start\n");
437 dprintf(out, "\n");
438 dprintf(out, "\n");
439 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
440 dprintf(out, "\n");
441 dprintf(out, " Prints the UID, app name, version mapping.\n");
442 dprintf(out, " PKG Optional package name to print the uids of the package\n");
443 dprintf(out, "\n");
444 dprintf(out, "\n");
445 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
446 dprintf(out, "\n");
447 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
448 dprintf(out, "\n");
449 dprintf(out, "\n");
450 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
451 dprintf(out, "\n");
452 dprintf(out, " Flushes all data on memory to disk.\n");
453 dprintf(out, "\n");
454 dprintf(out, "\n");
455 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
456 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
457 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
458 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
459 dprintf(out, " uid is used.\n");
460 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
461 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
462 dprintf(out, "\n");
463 dprintf(out, "\n");
464 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
465 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
466 dprintf(out, "\n");
467 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
468 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
469 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
470 dprintf(out, "\n");
471 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
472 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
473 dprintf(out, " uid is used.\n");
474 dprintf(out, " NAME The per-uid name to use\n");
475 dprintf(out, "\n");
476 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
477 dprintf(out, "\n be removed from memory and disk!\n");
478 dprintf(out, "\n");
479 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800480 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
481 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700482 dprintf(out, " Dump all metric data for a configuration.\n");
483 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
484 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
485 dprintf(out, " calling uid is used.\n");
486 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800487 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700488 dprintf(out, " --proto Print proto binary.\n");
489 dprintf(out, "\n");
490 dprintf(out, "\n");
491 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
492 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
493 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
494 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
495 dprintf(out, " calling uid is used.\n");
496 dprintf(out, " NAME The name of the configuration\n");
497 dprintf(out, "\n");
498 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800499 dprintf(out,
500 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
501 "[NAME1] [NAME2] [NAME3..]\n");
502 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
503 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
504 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
505 dprintf(out, " calling uid is used.\n");
506 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
507 dprintf(out, " the currently active configs\n");
508 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
509
510 dprintf(out, "\n");
511 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700512 dprintf(out, "usage: adb shell cmd stats print-stats\n");
513 dprintf(out, " Prints some basic stats.\n");
514 dprintf(out, " --proto Print proto binary instead of string format.\n");
515 dprintf(out, "\n");
516 dprintf(out, "\n");
517 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
518 dprintf(out, " Clear cached puller data.\n");
519 dprintf(out, "\n");
520 dprintf(out, "usage: adb shell cmd stats print-logs\n");
521 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700522}
523
Yao Chena80e5c02018-09-04 13:55:29 -0700524status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800525 string name;
526 bool good = false;
527 int uid;
528 const int argCount = args.size();
529 if (argCount == 2) {
530 // Automatically pick the UID
531 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800532 name.assign(args[1].c_str(), args[1].size());
533 good = true;
534 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800535 good = getUidFromArgs(args, 1, uid);
536 if (!good) {
537 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
538 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800539 }
Bookatzd2386572018-12-14 15:53:14 -0800540 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800541 }
542 if (!good) {
543 print_cmd_help(out);
544 return UNKNOWN_ERROR;
545 }
David Chend37bc232018-04-12 18:05:11 -0700546 ConfigKey key(uid, StrToInt64(name));
547 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800548 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800549 if (sc == nullptr) {
550 VLOG("Could not access statsCompanion");
551 } else if (receiver == nullptr) {
552 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
553 } else {
David Chend37bc232018-04-12 18:05:11 -0700554 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800555 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
556 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800557 }
558
David Chenadaf8b32017-11-03 15:42:08 -0700559 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700560}
561
Tej Singh6ede28b2019-01-29 17:06:54 -0800562status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
563 const int argCount = args.size();
564 int uid;
565 vector<int64_t> configIds;
566 if (argCount == 1) {
567 // Automatically pick the uid and send a broadcast that has no active configs.
568 uid = IPCThreadState::self()->getCallingUid();
569 mProcessor->GetActiveConfigs(uid, configIds);
570 } else {
571 int curArg = 1;
572 if(args[curArg].find("--uid=") == 0) {
573 string uidArgStr(args[curArg].c_str());
574 string uidStr = uidArgStr.substr(6);
575 if (!getUidFromString(uidStr.c_str(), uid)) {
576 dprintf(out, "Invalid UID. Note that the config can only be set for "
577 "other UIDs on eng or userdebug builds.\n");
578 return UNKNOWN_ERROR;
579 }
580 curArg++;
581 } else {
582 uid = IPCThreadState::self()->getCallingUid();
583 }
584 if (curArg == argCount || args[curArg] != "--configs") {
585 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
586 mProcessor->GetActiveConfigs(uid, configIds);
587 } else {
588 // Flag specified, use the given list of configs.
589 curArg++;
590 for (int i = curArg; i < argCount; i++) {
591 char* endp;
592 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
593 if (endp == args[i].c_str() || *endp != '\0') {
594 dprintf(out, "Error parsing config ID.\n");
595 return UNKNOWN_ERROR;
596 }
597 VLOG("Adding config id %ld", static_cast<long>(configID));
598 configIds.push_back(configID);
599 }
600 }
601 }
602 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
603 sp<IStatsCompanionService> sc = getStatsCompanionService();
604 if (sc == nullptr) {
605 VLOG("Could not access statsCompanion");
606 } else if (receiver == nullptr) {
607 VLOG("Could not find receiver for uid %d", uid);
608 } else {
609 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
610 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
611 }
612 return NO_ERROR;
613}
614
Yao Chena80e5c02018-09-04 13:55:29 -0700615status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700616 const int argCount = args.size();
617 if (argCount >= 2) {
618 if (args[1] == "update" || args[1] == "remove") {
619 bool good = false;
620 int uid = -1;
621 string name;
622
623 if (argCount == 3) {
624 // Automatically pick the UID
625 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700626 name.assign(args[2].c_str(), args[2].size());
627 good = true;
628 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800629 good = getUidFromArgs(args, 2, uid);
630 if (!good) {
631 dprintf(err, "Invalid UID. Note that the config can only be set for "
632 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700633 }
Bookatzd2386572018-12-14 15:53:14 -0800634 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800635 } else if (argCount == 2 && args[1] == "remove") {
636 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700637 }
638
639 if (!good) {
640 // If arg parsing failed, print the help text and return an error.
641 print_cmd_help(out);
642 return UNKNOWN_ERROR;
643 }
644
645 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800646 char* endp;
647 int64_t configID = strtoll(name.c_str(), &endp, 10);
648 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700649 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800650 return UNKNOWN_ERROR;
651 }
652
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700653 // Read stream into buffer.
654 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700655 if (!android::base::ReadFdToString(in, &buffer)) {
656 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700657 return UNKNOWN_ERROR;
658 }
659
660 // Parse buffer.
661 StatsdConfig config;
662 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700663 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700664 return UNKNOWN_ERROR;
665 }
666
667 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800668 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700669 } else {
yro74fed972017-11-27 14:42:42 -0800670 if (argCount == 2) {
671 cmd_remove_all_configs(out);
672 } else {
673 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800674 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800675 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700676 }
677
678 return NO_ERROR;
679 }
David Chen0656b7a2017-09-13 15:53:39 -0700680 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700681 print_cmd_help(out);
682 return UNKNOWN_ERROR;
683}
684
Bookatzff71cad2018-09-20 17:17:49 -0700685status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700686 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800687 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700688 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800689 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700690 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800691 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700692 int uid;
693 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800694 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
695 proto = true;
696 argCount -= 1;
697 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700698 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
699 includeCurrentBucket = true;
700 argCount -= 1;
701 }
Bookatz3e906582018-12-10 17:26:58 -0800702 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
703 eraseData = false;
704 argCount -= 1;
705 }
Yao Chen729093d2017-10-16 10:33:26 -0700706 if (argCount == 2) {
707 // Automatically pick the UID
708 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700709 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700710 good = true;
711 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800712 good = getUidFromArgs(args, 1, uid);
713 if (!good) {
714 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
715 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700716 }
Bookatzd2386572018-12-14 15:53:14 -0800717 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700718 }
719 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800720 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800721 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000722 includeCurrentBucket, eraseData, ADB_DUMP,
723 NO_TIME_CONSTRAINTS,
724 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800725 if (proto) {
726 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700727 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800728 }
729 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700730 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800731 }
Yao Chen729093d2017-10-16 10:33:26 -0700732 return android::OK;
733 } else {
734 // If arg parsing failed, print the help text and return an error.
735 print_cmd_help(out);
736 return UNKNOWN_ERROR;
737 }
738 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700739 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700740 return UNKNOWN_ERROR;
741 }
742}
743
Yao Chena80e5c02018-09-04 13:55:29 -0700744status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700745 int argCount = args.size();
746 bool proto = false;
747 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
748 proto = true;
749 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800750 }
Yao Chenb3561512017-11-21 18:07:17 -0800751 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700752 if (proto) {
753 vector<uint8_t> data;
754 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
755 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700756 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700757 }
758
759 } else {
760 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
761 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700762 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700763 mProcessor->GetMetricsSize(key));
764 }
765 statsdStats.dumpStats(out);
766 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800767 return NO_ERROR;
768}
769
Yao Chena80e5c02018-09-04 13:55:29 -0700770status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800771 if (args.size() > 1) {
772 string pkg;
773 pkg.assign(args[1].c_str(), args[1].size());
774 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700775 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800776 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700777 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800778 }
Yao Chena80e5c02018-09-04 13:55:29 -0700779 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800780 } else {
781 mUidMap->printUidMap(out);
782 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700783 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700784}
785
Yao Chena80e5c02018-09-04 13:55:29 -0700786status_t StatsService::cmd_write_data_to_disk(int out) {
787 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000788 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800789 return NO_ERROR;
790}
791
Yao Chena80e5c02018-09-04 13:55:29 -0700792status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800793 bool good = false;
794 int32_t uid;
795 int32_t label;
796 int32_t state;
797 const int argCount = args.size();
798 if (argCount == 3) {
799 // Automatically pick the UID
800 uid = IPCThreadState::self()->getCallingUid();
801 label = atoi(args[1].c_str());
802 state = atoi(args[2].c_str());
803 good = true;
804 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800805 good = getUidFromArgs(args, 1, uid);
806 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700807 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800808 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
809 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800810 }
Bookatzd2386572018-12-14 15:53:14 -0800811 label = atoi(args[2].c_str());
812 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800813 }
814 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700815 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800816 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800817 } else {
818 print_cmd_help(out);
819 return UNKNOWN_ERROR;
820 }
821 return NO_ERROR;
822}
823
Yao Chena80e5c02018-09-04 13:55:29 -0700824status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700825 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700826 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800827 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700828 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700829 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700830 }
Yao Chena80e5c02018-09-04 13:55:29 -0700831 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700832 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700833 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700834 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700835}
836
Yao Chena80e5c02018-09-04 13:55:29 -0700837status_t StatsService::cmd_remove_all_configs(int out) {
838 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800839 VLOG("StatsService::cmd_remove_all_configs was called");
840 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800841 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800842 return NO_ERROR;
843}
844
Yao Chena80e5c02018-09-04 13:55:29 -0700845status_t StatsService::cmd_dump_memory_info(int out) {
846 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800847 return NO_ERROR;
848}
849
Yao Chena80e5c02018-09-04 13:55:29 -0700850status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800851 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800852 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
853 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800854 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700855 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700856 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800857 return NO_ERROR;
858 } else {
859 return PERMISSION_DENIED;
860 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800861}
862
Yao Chena80e5c02018-09-04 13:55:29 -0700863status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700864 IPCThreadState* ipc = IPCThreadState::self();
865 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
866 ipc->getCallingUid());
867 if (checkCallingPermission(String16(kPermissionDump))) {
868 bool enabled = true;
869 if (args.size() >= 2) {
870 enabled = atoi(args[1].c_str()) != 0;
871 }
872 mProcessor->setPrintLogs(enabled);
873 return NO_ERROR;
874 } else {
875 return PERMISSION_DENIED;
876 }
877}
878
Bookatzd2386572018-12-14 15:53:14 -0800879bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800880 return getUidFromString(args[uidArgIndex].c_str(), uid);
881}
882
883bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800884 if (*s == '\0') {
885 return false;
886 }
887 char* endc = NULL;
888 int64_t longUid = strtol(s, &endc, 0);
889 if (*endc != '\0') {
890 return false;
891 }
892 int32_t goodUid = static_cast<int32_t>(longUid);
893 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
894 return false; // It was not of uid_t type.
895 }
896 uid = goodUid;
897
898 int32_t callingUid = IPCThreadState::self()->getCallingUid();
899 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
900 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
901 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
902}
903
Dianne Hackborn3accca02013-09-20 09:32:11 -0700904Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700905 const vector<String16>& version_string,
906 const vector<String16>& app,
907 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600908 ENFORCE_UID(AID_SYSTEM);
909
yro74fed972017-11-27 14:42:42 -0800910 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700911 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800912 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700913
914 return Status::ok();
915}
916
dwchen730403e2018-10-29 11:41:56 -0700917Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
918 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600919 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700920
Jeff Sharkey6b649252018-04-16 09:50:22 -0600921 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700922 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700923 return Status::ok();
924}
925
926Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600927 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700928
Jeff Sharkey6b649252018-04-16 09:50:22 -0600929 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700930 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800931 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700932 return Status::ok();
933}
934
Yao Chenef99c4f2017-09-22 16:26:54 -0700935Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600936 ENFORCE_UID(AID_SYSTEM);
937
yro74fed972017-11-27 14:42:42 -0800938 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700939 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800940 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
941 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
942 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800943 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800944 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800945 } else {
946 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
947 }
Bookatz1b0b1142017-09-08 11:58:42 -0700948 return Status::ok();
949}
950
Yangster-mac932ecec2018-02-01 10:23:52 -0800951Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600952 ENFORCE_UID(AID_SYSTEM);
953
Yangster-mac932ecec2018-02-01 10:23:52 -0800954 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700955 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800956 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
957 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
958 if (alarmSet.size() > 0) {
959 VLOG("Found periodic alarm fired.");
960 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
961 } else {
962 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
963 }
964 return Status::ok();
965}
966
Yao Chenef99c4f2017-09-22 16:26:54 -0700967Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600968 ENFORCE_UID(AID_SYSTEM);
969
yro74fed972017-11-27 14:42:42 -0800970 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700971 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800972 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700973 return Status::ok();
974}
975
Yao Chenef99c4f2017-09-22 16:26:54 -0700976Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600977 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700978
979 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800980 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700981 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700982 return Status::ok();
983}
984
Yangster-mac892f3d32018-05-02 14:16:48 -0700985Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600986 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700987 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000988 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800989 mProcessor->WriteMetricsActivationToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -0800990 return Status::ok();
991}
992
Yao Chenef99c4f2017-09-22 16:26:54 -0700993void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700994 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
995 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800996 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700997 statsCompanion->statsdReady();
998 } else {
yro74fed972017-11-27 14:42:42 -0800999 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001000 }
1001}
1002
Yao Chenef99c4f2017-09-22 16:26:54 -07001003Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001004 ENFORCE_UID(AID_SYSTEM);
1005
yro74fed972017-11-27 14:42:42 -08001006 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001007 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1008 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001009 return Status::fromExceptionCode(
1010 Status::EX_NULL_POINTER,
1011 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001012 }
yro74fed972017-11-27 14:42:42 -08001013 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001014 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001015 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001016 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1017 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -08001018 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001019 return Status::ok();
1020}
1021
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001022void StatsService::Startup() {
1023 mConfigManager->Startup();
Chenjie Yuc7939cb2019-02-04 17:25:45 -08001024 mProcessor->LoadMetricsActivationFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001025}
1026
Yangster-mac97e7d202018-10-09 11:05:39 -07001027void StatsService::Terminate() {
1028 ALOGI("StatsService::Terminating");
1029 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001030 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Yangster-mac97e7d202018-10-09 11:05:39 -07001031 }
1032}
1033
Yao Chen0f861862019-03-27 11:51:15 -07001034// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001035void StatsService::OnLogEvent(LogEvent* event) {
1036 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001037 if (mShellSubscriber != nullptr) {
1038 mShellSubscriber->onLogEvent(*event);
1039 }
Bookatz906a35c2017-09-20 15:26:44 -07001040}
1041
Jeff Sharkey6b649252018-04-16 09:50:22 -06001042Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1043 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1044
David Chenadaf8b32017-11-03 15:42:08 -07001045 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001046 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001047 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001048 // The dump latency does not matter here since we do not include the current bucket, we do not
1049 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001050 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001051 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001052 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001053}
1054
Jeff Sharkey6b649252018-04-16 09:50:22 -06001055Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1056 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1057
David Chen2e8f3802017-11-22 10:56:48 -08001058 IPCThreadState* ipc = IPCThreadState::self();
1059 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1060 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001061 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1062 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001063}
1064
Jeff Sharkey6b649252018-04-16 09:50:22 -06001065Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1066 const String16& packageName) {
1067 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1068
David Chenadaf8b32017-11-03 15:42:08 -07001069 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001070 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001071 return Status::ok();
1072 } else {
Bookatz4f716292018-04-10 17:15:12 -07001073 ALOGE("Could not parse malformatted StatsdConfig");
1074 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1075 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001076 }
1077}
1078
David Chen9fdd4032018-03-20 14:38:56 -07001079bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1080 ConfigKey configKey(uid, key);
1081 StatsdConfig cfg;
1082 if (config.size() > 0) { // If the config is empty, skip parsing.
1083 if (!cfg.ParseFromArray(&config[0], config.size())) {
1084 return false;
1085 }
1086 }
1087 mConfigManager->UpdateConfig(configKey, cfg);
1088 return true;
1089}
1090
Jeff Sharkey6b649252018-04-16 09:50:22 -06001091Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1092 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1093
Bookatz4f716292018-04-10 17:15:12 -07001094 IPCThreadState* ipc = IPCThreadState::self();
1095 ConfigKey configKey(ipc->getCallingUid(), key);
1096 mConfigManager->RemoveConfigReceiver(configKey);
1097 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001098}
1099
Jeff Sharkey6b649252018-04-16 09:50:22 -06001100Status StatsService::setDataFetchOperation(int64_t key,
1101 const sp<android::IBinder>& intentSender,
1102 const String16& packageName) {
1103 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1104
Bookatz4f716292018-04-10 17:15:12 -07001105 IPCThreadState* ipc = IPCThreadState::self();
1106 ConfigKey configKey(ipc->getCallingUid(), key);
1107 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001108 if (StorageManager::hasConfigMetricsReport(configKey)) {
1109 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1110 configKey.ToString().c_str());
1111 mProcessor->noteOnDiskData(configKey);
1112 }
Bookatz4f716292018-04-10 17:15:12 -07001113 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001114}
1115
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001116Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1117 const String16& packageName,
1118 vector<int64_t>* output) {
1119 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1120
1121 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001122 int uid = ipc->getCallingUid();
1123 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1124 if (output != nullptr) {
1125 mProcessor->GetActiveConfigs(uid, *output);
1126 } else {
1127 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1128 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001129 return Status::ok();
1130}
1131
1132Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1133 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1134
1135 IPCThreadState* ipc = IPCThreadState::self();
1136 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1137 return Status::ok();
1138}
1139
Jeff Sharkey6b649252018-04-16 09:50:22 -06001140Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1141 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1142
Bookatz4f716292018-04-10 17:15:12 -07001143 IPCThreadState* ipc = IPCThreadState::self();
1144 ConfigKey configKey(ipc->getCallingUid(), key);
1145 mConfigManager->RemoveConfig(configKey);
1146 SubscriberReporter::getInstance().removeConfig(configKey);
1147 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001148}
1149
Bookatzc6977972018-01-16 16:55:05 -08001150Status StatsService::setBroadcastSubscriber(int64_t configId,
1151 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001152 const sp<android::IBinder>& intentSender,
1153 const String16& packageName) {
1154 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1155
Bookatzc6977972018-01-16 16:55:05 -08001156 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001157 IPCThreadState* ipc = IPCThreadState::self();
1158 ConfigKey configKey(ipc->getCallingUid(), configId);
1159 SubscriberReporter::getInstance()
1160 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1161 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001162}
1163
1164Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001165 int64_t subscriberId,
1166 const String16& packageName) {
1167 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1168
Bookatzc6977972018-01-16 16:55:05 -08001169 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001170 IPCThreadState* ipc = IPCThreadState::self();
1171 ConfigKey configKey(ipc->getCallingUid(), configId);
1172 SubscriberReporter::getInstance()
1173 .unsetBroadcastSubscriber(configKey, subscriberId);
1174 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001175}
1176
yrobe6d7f92018-05-04 13:02:53 -07001177Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1178 // Permission check not necessary as it's meant for applications to write to
1179 // statsd.
1180 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1181 IPCThreadState::self()->getCallingUid(), label,
1182 state);
1183 return Status::ok();
1184}
1185
Tej Singha0c89dd2019-01-25 16:39:18 -08001186Status StatsService::registerPullerCallback(int32_t atomTag,
1187 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1188 const String16& packageName) {
1189 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1190
1191 VLOG("StatsService::registerPullerCallback called.");
1192 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1193 return Status::ok();
1194}
1195
1196Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1197 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1198
1199 VLOG("StatsService::unregisterPullerCallback called.");
1200 mPullerManager->UnregisterPullerCallback(atomTag);
1201 return Status::ok();
1202}
1203
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001204Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainName,
1205 int64_t trainVersionCode, int options,
1206 int32_t state,
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001207 const std::vector<int64_t>& experimentIdsIn) {
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001208 uid_t uid = IPCThreadState::self()->getCallingUid();
1209 // For testing
1210 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
1211 return ok();
1212 }
1213
1214 // Caller must be granted these permissions
1215 if (!checkCallingPermission(String16(kPermissionDump))) {
1216 return exception(binder::Status::EX_SECURITY,
1217 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1218 }
1219 if (!checkCallingPermission(String16(kPermissionUsage))) {
1220 return exception(binder::Status::EX_SECURITY,
1221 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1222 }
1223 // TODO: add verifier permission
1224
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001225 bool readTrainInfoSuccess = false;
1226 InstallTrainInfo trainInfo;
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001227 if (trainVersionCode == -1 || experimentIdsIn.empty() || trainName.size() == 0) {
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001228 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfo);
1229 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001230
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001231 if (trainVersionCode == -1 && readTrainInfoSuccess) {
1232 trainVersionCode = trainInfo.trainVersionCode;
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001233 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001234
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001235 // Find the right experiment IDs
1236 std::vector<int64_t> experimentIds;
1237 if (readTrainInfoSuccess && experimentIdsIn.empty()) {
1238 experimentIds = trainInfo.experimentIds;
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001239 } else {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001240 experimentIds = experimentIdsIn;
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001241 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001242
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001243 // Flatten the experiment IDs to proto
1244 vector<uint8_t> experimentIdsProtoBuffer;
1245 writeExperimentIdsToProto(experimentIds, &experimentIdsProtoBuffer);
1246
1247 // Find the right train name
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001248 std::string trainNameUtf8;
1249 if (readTrainInfoSuccess && trainName.size() == 0) {
1250 trainNameUtf8 = trainInfo.trainName;
1251 } else {
1252 trainNameUtf8 = std::string(String8(trainName).string());
1253 }
1254
1255 userid_t userId = multiuser_get_user_id(uid);
1256 bool requiresStaging = options & IStatsManager::FLAG_REQUIRE_STAGING;
1257 bool rollbackEnabled = options & IStatsManager::FLAG_ROLLBACK_ENABLED;
1258 bool requiresLowLatencyMonitor = options & IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001259 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1260 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001261 mProcessor->OnLogEvent(&event);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001262 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
1263 return Status::ok();
1264}
1265
1266Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
1267 uid_t uid = IPCThreadState::self()->getCallingUid();
1268
1269 // Caller must be granted these permissions
1270 if (!checkCallingPermission(String16(kPermissionDump))) {
1271 return exception(binder::Status::EX_SECURITY,
1272 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1273 }
1274 if (!checkCallingPermission(String16(kPermissionUsage))) {
1275 return exception(binder::Status::EX_SECURITY,
1276 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1277 }
1278 // TODO: add verifier permission
1279
1280 // Read the latest train info
1281 InstallTrainInfo trainInfo;
1282 if (!StorageManager::readTrainInfo(trainInfo)) {
1283 // No train info means no experiment IDs, return an empty list
1284 experimentIdsOut->clear();
1285 return Status::ok();
1286 }
1287
1288 // Copy the experiment IDs to the out vector
1289 experimentIdsOut->assign(trainInfo.experimentIds.begin(), trainInfo.experimentIds.end());
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001290 return Status::ok();
1291}
1292
Howard Roa46b6582018-09-18 16:45:02 -07001293hardware::Return<void> StatsService::reportSpeakerImpedance(
1294 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001295 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1296 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001297
1298 return hardware::Void();
1299}
1300
1301hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001302 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1303 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001304
1305 return hardware::Void();
1306}
1307
1308hardware::Return<void> StatsService::reportPhysicalDropDetected(
1309 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001310 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1311 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1312 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001313
1314 return hardware::Void();
1315}
1316
1317hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001318 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1319 int initialSize = buckets.size();
1320 for (int i = 0; i < 10 - initialSize; i++) {
1321 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1322 }
1323 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1324 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1325 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001326
1327 return hardware::Void();
1328}
1329
1330hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1331 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001332 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1333 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1334 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1335 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1336 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001337
1338 return hardware::Void();
1339}
1340
1341hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001342 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001343
1344 return hardware::Void();
1345}
1346
1347hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1348 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001349 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1350 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001351
1352 return hardware::Void();
1353}
1354
Maggie Whitefc1aa592018-11-28 21:55:23 -08001355hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1356 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001357 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1358 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1359 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1360 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001361
1362 return hardware::Void();
1363}
1364
Carter Hsub8fd1e92019-01-11 15:24:45 +08001365hardware::Return<void> StatsService::reportSpeechDspStat(
1366 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001367 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1368 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1369 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001370
1371 return hardware::Void();
1372}
1373
Maggie White58174da2019-01-18 15:23:35 -08001374hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1375 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1376 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1377 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1378 return hardware::Void();
1379 }
1380 if (reverseDomainName.length() > 50) {
1381 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1382 return hardware::Void();
1383 }
1384 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1385 mProcessor->OnLogEvent(&event);
1386
1387 return hardware::Void();
1388}
1389
David Chen1d7b0cd2017-11-15 14:20:04 -08001390void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001391 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001392 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1393 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001394 ALOGW("Reset statsd upon system server restarts.");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001395 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001396 mProcessor->resetConfigs();
1397 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001398 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1399 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1400 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001401 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001402}
1403
Yao Chenef99c4f2017-09-22 16:26:54 -07001404} // namespace statsd
1405} // namespace os
1406} // namespace android