blob: bfe2da93db1d7cb06f3b13745b6f6cb96a6a32b3 [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;
Chenjie Yu97dbb202019-02-13 16:42:04 -080068// for TrainInfo experiment id serialization
69const int FIELD_ID_EXPERIMENT_ID = 1;
Bookatzff71cad2018-09-20 17:17:49 -070070
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) {
Chenjie Yue2219202018-06-08 10:07:51 -0700173 sp<IStatsCompanionService> sc = getStatsCompanionService();
174 auto receiver = mConfigManager->GetConfigReceiver(key);
175 if (sc == nullptr) {
176 VLOG("Could not find StatsCompanionService");
177 return false;
178 } else if (receiver == nullptr) {
179 VLOG("Statscompanion could not find a broadcast receiver for %s",
180 key.ToString().c_str());
181 return false;
182 } else {
183 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
184 return true;
185 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800186 },
187 [this](const int& uid, const vector<int64_t>& activeConfigs) {
188 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
189 sp<IStatsCompanionService> sc = getStatsCompanionService();
190 if (sc == nullptr) {
191 VLOG("Could not access statsCompanion");
192 return false;
193 } else if (receiver == nullptr) {
194 VLOG("Could not find receiver for uid %d", uid);
195 return false;
196 } else {
197 sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
198 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
199 return true;
200 }
Chenjie Yue2219202018-06-08 10:07:51 -0700201 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700202
203 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);
269 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700270 return NO_ERROR;
271 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700272 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700273 }
274}
275
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700276/**
Bookatzff71cad2018-09-20 17:17:49 -0700277 * Write data from statsd.
278 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
279 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
280 * Anything ending in --proto will be in proto format.
281 * Anything without --metadata as the first argument will be report information.
282 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
283 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700284 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700285status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700286 if (!checkCallingPermission(String16(kPermissionDump))) {
287 return PERMISSION_DENIED;
288 }
Bookatzff71cad2018-09-20 17:17:49 -0700289 int lastArg = args.size() - 1;
290 bool asProto = false;
291 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
292 asProto = true;
293 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800294 }
Bookatzff71cad2018-09-20 17:17:49 -0700295 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
296 // Request is to dump statsd stats.
297 bool verbose = false;
298 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
299 verbose = true;
300 lastArg--;
301 }
302 dumpStatsdStats(fd, verbose, asProto);
303 } else {
304 // Request is to dump statsd report data.
305 if (asProto) {
306 dumpIncidentSection(fd);
307 } else {
308 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
309 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700310 }
Yao Chen884c8c12018-01-26 10:36:25 -0800311
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700312 return NO_ERROR;
313}
314
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700315/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700316 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700317 */
Bookatzff71cad2018-09-20 17:17:49 -0700318void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700319 if (proto) {
320 vector<uint8_t> data;
321 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
322 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700323 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700324 }
325 } else {
326 StatsdStats::getInstance().dumpStats(out);
327 mProcessor->dumpStates(out, verbose);
328 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700329}
330
331/**
Bookatzff71cad2018-09-20 17:17:49 -0700332 * Write stats report data in StatsDataDumpProto incident section format.
333 */
334void StatsService::dumpIncidentSection(int out) {
335 ProtoOutputStream proto;
336 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
337 uint64_t reportsListToken =
338 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
339 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
340 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000341 ADB_DUMP,
342 FAST,
343 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700344 proto.end(reportsListToken);
345 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800346 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700347 }
348}
349
350/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700351 * Implementation of the adb shell cmd stats command.
352 */
Yao Chena80e5c02018-09-04 13:55:29 -0700353status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
354 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600355 uid_t uid = IPCThreadState::self()->getCallingUid();
356 if (uid != AID_ROOT && uid != AID_SHELL) {
357 return PERMISSION_DENIED;
358 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700359
360 const int argCount = args.size();
361 if (argCount >= 1) {
362 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700363 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700364 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700365 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700366
David Chende701692017-10-05 13:16:02 -0700367 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800368 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700369 }
Yao Chen729093d2017-10-16 10:33:26 -0700370
371 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700372 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700373 }
David Chen1481fe12017-10-16 13:16:34 -0700374
375 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
376 return cmd_print_pulled_metrics(out, args);
377 }
David Chenadaf8b32017-11-03 15:42:08 -0700378
379 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800380 return cmd_trigger_broadcast(out, args);
381 }
382
383 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800384 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700385 }
yro87d983c2017-11-14 21:31:43 -0800386
Yao Chen8d9989b2017-11-18 18:54:50 -0800387 if (!args[0].compare(String8("meminfo"))) {
388 return cmd_dump_memory_info(out);
389 }
yro947fbce2017-11-15 22:50:23 -0800390
391 if (!args[0].compare(String8("write-to-disk"))) {
392 return cmd_write_data_to_disk(out);
393 }
Bookatzb223c4e2018-02-01 15:35:04 -0800394
David Chen0b5c90c2018-01-25 16:51:49 -0800395 if (!args[0].compare(String8("log-app-breadcrumb"))) {
396 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800397 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800398
399 if (!args[0].compare(String8("clear-puller-cache"))) {
400 return cmd_clear_puller_cache(out);
401 }
Yao Chen876889c2018-05-02 11:16:16 -0700402
403 if (!args[0].compare(String8("print-logs"))) {
404 return cmd_print_logs(out, args);
405 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800406 if (!args[0].compare(String8("send-active-configs"))) {
407 return cmd_trigger_active_config_broadcast(out, args);
408 }
Yao Chena80e5c02018-09-04 13:55:29 -0700409 if (!args[0].compare(String8("data-subscribe"))) {
410 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700411 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700412 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800413 int timeoutSec = -1;
414 if (argCount >= 2) {
415 timeoutSec = atoi(args[1].c_str());
416 }
417 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700418 return NO_ERROR;
419 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700420 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700421
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700422 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700423 return NO_ERROR;
424}
425
Yao Chena80e5c02018-09-04 13:55:29 -0700426void StatsService::print_cmd_help(int out) {
427 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700428 "usage: adb shell cmd stats print-stats-log [tag_required] "
429 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700430 dprintf(out, "\n");
431 dprintf(out, "\n");
432 dprintf(out, "usage: adb shell cmd stats meminfo\n");
433 dprintf(out, "\n");
434 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
435 dprintf(out, " # adb shell stop\n");
436 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
437 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
438 dprintf(out, " # adb shell start\n");
439 dprintf(out, "\n");
440 dprintf(out, "\n");
441 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
442 dprintf(out, "\n");
443 dprintf(out, " Prints the UID, app name, version mapping.\n");
444 dprintf(out, " PKG Optional package name to print the uids of the package\n");
445 dprintf(out, "\n");
446 dprintf(out, "\n");
447 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
448 dprintf(out, "\n");
449 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
450 dprintf(out, "\n");
451 dprintf(out, "\n");
452 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
453 dprintf(out, "\n");
454 dprintf(out, " Flushes all data on memory to disk.\n");
455 dprintf(out, "\n");
456 dprintf(out, "\n");
457 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
458 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
459 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
460 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
461 dprintf(out, " uid is used.\n");
462 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
463 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
464 dprintf(out, "\n");
465 dprintf(out, "\n");
466 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
467 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
468 dprintf(out, "\n");
469 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
470 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
471 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
472 dprintf(out, "\n");
473 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
474 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
475 dprintf(out, " uid is used.\n");
476 dprintf(out, " NAME The per-uid name to use\n");
477 dprintf(out, "\n");
478 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
479 dprintf(out, "\n be removed from memory and disk!\n");
480 dprintf(out, "\n");
481 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800482 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
483 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700484 dprintf(out, " Dump all metric data for a configuration.\n");
485 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
486 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
487 dprintf(out, " calling uid is used.\n");
488 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800489 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700490 dprintf(out, " --proto Print proto binary.\n");
491 dprintf(out, "\n");
492 dprintf(out, "\n");
493 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
494 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
495 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
496 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
497 dprintf(out, " calling uid is used.\n");
498 dprintf(out, " NAME The name of the configuration\n");
499 dprintf(out, "\n");
500 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800501 dprintf(out,
502 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
503 "[NAME1] [NAME2] [NAME3..]\n");
504 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
505 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
506 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
507 dprintf(out, " calling uid is used.\n");
508 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
509 dprintf(out, " the currently active configs\n");
510 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
511
512 dprintf(out, "\n");
513 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700514 dprintf(out, "usage: adb shell cmd stats print-stats\n");
515 dprintf(out, " Prints some basic stats.\n");
516 dprintf(out, " --proto Print proto binary instead of string format.\n");
517 dprintf(out, "\n");
518 dprintf(out, "\n");
519 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
520 dprintf(out, " Clear cached puller data.\n");
521 dprintf(out, "\n");
522 dprintf(out, "usage: adb shell cmd stats print-logs\n");
523 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700524}
525
Yao Chena80e5c02018-09-04 13:55:29 -0700526status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800527 string name;
528 bool good = false;
529 int uid;
530 const int argCount = args.size();
531 if (argCount == 2) {
532 // Automatically pick the UID
533 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800534 name.assign(args[1].c_str(), args[1].size());
535 good = true;
536 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800537 good = getUidFromArgs(args, 1, uid);
538 if (!good) {
539 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
540 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800541 }
Bookatzd2386572018-12-14 15:53:14 -0800542 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800543 }
544 if (!good) {
545 print_cmd_help(out);
546 return UNKNOWN_ERROR;
547 }
David Chend37bc232018-04-12 18:05:11 -0700548 ConfigKey key(uid, StrToInt64(name));
549 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800550 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800551 if (sc == nullptr) {
552 VLOG("Could not access statsCompanion");
553 } else if (receiver == nullptr) {
554 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
555 } else {
David Chend37bc232018-04-12 18:05:11 -0700556 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800557 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
558 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800559 }
560
David Chenadaf8b32017-11-03 15:42:08 -0700561 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700562}
563
Tej Singh6ede28b2019-01-29 17:06:54 -0800564status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
565 const int argCount = args.size();
566 int uid;
567 vector<int64_t> configIds;
568 if (argCount == 1) {
569 // Automatically pick the uid and send a broadcast that has no active configs.
570 uid = IPCThreadState::self()->getCallingUid();
571 mProcessor->GetActiveConfigs(uid, configIds);
572 } else {
573 int curArg = 1;
574 if(args[curArg].find("--uid=") == 0) {
575 string uidArgStr(args[curArg].c_str());
576 string uidStr = uidArgStr.substr(6);
577 if (!getUidFromString(uidStr.c_str(), uid)) {
578 dprintf(out, "Invalid UID. Note that the config can only be set for "
579 "other UIDs on eng or userdebug builds.\n");
580 return UNKNOWN_ERROR;
581 }
582 curArg++;
583 } else {
584 uid = IPCThreadState::self()->getCallingUid();
585 }
586 if (curArg == argCount || args[curArg] != "--configs") {
587 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
588 mProcessor->GetActiveConfigs(uid, configIds);
589 } else {
590 // Flag specified, use the given list of configs.
591 curArg++;
592 for (int i = curArg; i < argCount; i++) {
593 char* endp;
594 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
595 if (endp == args[i].c_str() || *endp != '\0') {
596 dprintf(out, "Error parsing config ID.\n");
597 return UNKNOWN_ERROR;
598 }
599 VLOG("Adding config id %ld", static_cast<long>(configID));
600 configIds.push_back(configID);
601 }
602 }
603 }
604 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
605 sp<IStatsCompanionService> sc = getStatsCompanionService();
606 if (sc == nullptr) {
607 VLOG("Could not access statsCompanion");
608 } else if (receiver == nullptr) {
609 VLOG("Could not find receiver for uid %d", uid);
610 } else {
611 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
612 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
613 }
614 return NO_ERROR;
615}
616
Yao Chena80e5c02018-09-04 13:55:29 -0700617status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700618 const int argCount = args.size();
619 if (argCount >= 2) {
620 if (args[1] == "update" || args[1] == "remove") {
621 bool good = false;
622 int uid = -1;
623 string name;
624
625 if (argCount == 3) {
626 // Automatically pick the UID
627 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700628 name.assign(args[2].c_str(), args[2].size());
629 good = true;
630 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800631 good = getUidFromArgs(args, 2, uid);
632 if (!good) {
633 dprintf(err, "Invalid UID. Note that the config can only be set for "
634 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700635 }
Bookatzd2386572018-12-14 15:53:14 -0800636 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800637 } else if (argCount == 2 && args[1] == "remove") {
638 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700639 }
640
641 if (!good) {
642 // If arg parsing failed, print the help text and return an error.
643 print_cmd_help(out);
644 return UNKNOWN_ERROR;
645 }
646
647 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800648 char* endp;
649 int64_t configID = strtoll(name.c_str(), &endp, 10);
650 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700651 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800652 return UNKNOWN_ERROR;
653 }
654
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700655 // Read stream into buffer.
656 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700657 if (!android::base::ReadFdToString(in, &buffer)) {
658 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700659 return UNKNOWN_ERROR;
660 }
661
662 // Parse buffer.
663 StatsdConfig config;
664 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700665 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700666 return UNKNOWN_ERROR;
667 }
668
669 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800670 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700671 } else {
yro74fed972017-11-27 14:42:42 -0800672 if (argCount == 2) {
673 cmd_remove_all_configs(out);
674 } else {
675 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800676 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800677 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700678 }
679
680 return NO_ERROR;
681 }
David Chen0656b7a2017-09-13 15:53:39 -0700682 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700683 print_cmd_help(out);
684 return UNKNOWN_ERROR;
685}
686
Bookatzff71cad2018-09-20 17:17:49 -0700687status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700688 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800689 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700690 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800691 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700692 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800693 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700694 int uid;
695 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800696 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
697 proto = true;
698 argCount -= 1;
699 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700700 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
701 includeCurrentBucket = true;
702 argCount -= 1;
703 }
Bookatz3e906582018-12-10 17:26:58 -0800704 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
705 eraseData = false;
706 argCount -= 1;
707 }
Yao Chen729093d2017-10-16 10:33:26 -0700708 if (argCount == 2) {
709 // Automatically pick the UID
710 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700711 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700712 good = true;
713 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800714 good = getUidFromArgs(args, 1, uid);
715 if (!good) {
716 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
717 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700718 }
Bookatzd2386572018-12-14 15:53:14 -0800719 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700720 }
721 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800722 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800723 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000724 includeCurrentBucket, eraseData, ADB_DUMP,
725 NO_TIME_CONSTRAINTS,
726 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800727 if (proto) {
728 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700729 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800730 }
731 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700732 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800733 }
Yao Chen729093d2017-10-16 10:33:26 -0700734 return android::OK;
735 } else {
736 // If arg parsing failed, print the help text and return an error.
737 print_cmd_help(out);
738 return UNKNOWN_ERROR;
739 }
740 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700741 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700742 return UNKNOWN_ERROR;
743 }
744}
745
Yao Chena80e5c02018-09-04 13:55:29 -0700746status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700747 int argCount = args.size();
748 bool proto = false;
749 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
750 proto = true;
751 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800752 }
Yao Chenb3561512017-11-21 18:07:17 -0800753 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700754 if (proto) {
755 vector<uint8_t> data;
756 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
757 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700758 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700759 }
760
761 } else {
762 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
763 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700764 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700765 mProcessor->GetMetricsSize(key));
766 }
767 statsdStats.dumpStats(out);
768 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800769 return NO_ERROR;
770}
771
Yao Chena80e5c02018-09-04 13:55:29 -0700772status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800773 if (args.size() > 1) {
774 string pkg;
775 pkg.assign(args[1].c_str(), args[1].size());
776 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700777 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800778 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700779 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800780 }
Yao Chena80e5c02018-09-04 13:55:29 -0700781 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800782 } else {
783 mUidMap->printUidMap(out);
784 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700785 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700786}
787
Yao Chena80e5c02018-09-04 13:55:29 -0700788status_t StatsService::cmd_write_data_to_disk(int out) {
789 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000790 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800791 return NO_ERROR;
792}
793
Yao Chena80e5c02018-09-04 13:55:29 -0700794status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800795 bool good = false;
796 int32_t uid;
797 int32_t label;
798 int32_t state;
799 const int argCount = args.size();
800 if (argCount == 3) {
801 // Automatically pick the UID
802 uid = IPCThreadState::self()->getCallingUid();
803 label = atoi(args[1].c_str());
804 state = atoi(args[2].c_str());
805 good = true;
806 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800807 good = getUidFromArgs(args, 1, uid);
808 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700809 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800810 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
811 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800812 }
Bookatzd2386572018-12-14 15:53:14 -0800813 label = atoi(args[2].c_str());
814 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800815 }
816 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700817 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800818 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800819 } else {
820 print_cmd_help(out);
821 return UNKNOWN_ERROR;
822 }
823 return NO_ERROR;
824}
825
Yao Chena80e5c02018-09-04 13:55:29 -0700826status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700827 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700828 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800829 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700830 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700831 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700832 }
Yao Chena80e5c02018-09-04 13:55:29 -0700833 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700834 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700835 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700836 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700837}
838
Yao Chena80e5c02018-09-04 13:55:29 -0700839status_t StatsService::cmd_remove_all_configs(int out) {
840 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800841 VLOG("StatsService::cmd_remove_all_configs was called");
842 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800843 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800844 return NO_ERROR;
845}
846
Yao Chena80e5c02018-09-04 13:55:29 -0700847status_t StatsService::cmd_dump_memory_info(int out) {
848 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800849 return NO_ERROR;
850}
851
Yao Chena80e5c02018-09-04 13:55:29 -0700852status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800853 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800854 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
855 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800856 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700857 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700858 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800859 return NO_ERROR;
860 } else {
861 return PERMISSION_DENIED;
862 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800863}
864
Yao Chena80e5c02018-09-04 13:55:29 -0700865status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700866 IPCThreadState* ipc = IPCThreadState::self();
867 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
868 ipc->getCallingUid());
869 if (checkCallingPermission(String16(kPermissionDump))) {
870 bool enabled = true;
871 if (args.size() >= 2) {
872 enabled = atoi(args[1].c_str()) != 0;
873 }
874 mProcessor->setPrintLogs(enabled);
875 return NO_ERROR;
876 } else {
877 return PERMISSION_DENIED;
878 }
879}
880
Bookatzd2386572018-12-14 15:53:14 -0800881bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800882 return getUidFromString(args[uidArgIndex].c_str(), uid);
883}
884
885bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800886 if (*s == '\0') {
887 return false;
888 }
889 char* endc = NULL;
890 int64_t longUid = strtol(s, &endc, 0);
891 if (*endc != '\0') {
892 return false;
893 }
894 int32_t goodUid = static_cast<int32_t>(longUid);
895 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
896 return false; // It was not of uid_t type.
897 }
898 uid = goodUid;
899
900 int32_t callingUid = IPCThreadState::self()->getCallingUid();
901 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
902 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
903 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
904}
905
Dianne Hackborn3accca02013-09-20 09:32:11 -0700906Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700907 const vector<String16>& version_string,
908 const vector<String16>& app,
909 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600910 ENFORCE_UID(AID_SYSTEM);
911
yro74fed972017-11-27 14:42:42 -0800912 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700913 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800914 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700915
916 return Status::ok();
917}
918
dwchen730403e2018-10-29 11:41:56 -0700919Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
920 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600921 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700922
Jeff Sharkey6b649252018-04-16 09:50:22 -0600923 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700924 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700925 return Status::ok();
926}
927
928Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600929 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700930
Jeff Sharkey6b649252018-04-16 09:50:22 -0600931 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700932 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800933 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700934 return Status::ok();
935}
936
Yao Chenef99c4f2017-09-22 16:26:54 -0700937Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600938 ENFORCE_UID(AID_SYSTEM);
939
yro74fed972017-11-27 14:42:42 -0800940 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700941 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800942 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
943 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
944 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800945 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800946 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800947 } else {
948 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
949 }
Bookatz1b0b1142017-09-08 11:58:42 -0700950 return Status::ok();
951}
952
Yangster-mac932ecec2018-02-01 10:23:52 -0800953Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600954 ENFORCE_UID(AID_SYSTEM);
955
Yangster-mac932ecec2018-02-01 10:23:52 -0800956 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700957 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800958 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
959 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
960 if (alarmSet.size() > 0) {
961 VLOG("Found periodic alarm fired.");
962 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
963 } else {
964 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
965 }
966 return Status::ok();
967}
968
Yao Chenef99c4f2017-09-22 16:26:54 -0700969Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600970 ENFORCE_UID(AID_SYSTEM);
971
yro74fed972017-11-27 14:42:42 -0800972 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700973 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800974 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700975 return Status::ok();
976}
977
Yao Chenef99c4f2017-09-22 16:26:54 -0700978Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600979 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700980
981 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800982 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700983 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700984 return Status::ok();
985}
986
Yangster-mac892f3d32018-05-02 14:16:48 -0700987Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600988 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700989 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000990 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800991 mProcessor->WriteMetricsActivationToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -0800992 return Status::ok();
993}
994
Yao Chenef99c4f2017-09-22 16:26:54 -0700995void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700996 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
997 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800998 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700999 statsCompanion->statsdReady();
1000 } else {
yro74fed972017-11-27 14:42:42 -08001001 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001002 }
1003}
1004
Yao Chenef99c4f2017-09-22 16:26:54 -07001005Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001006 ENFORCE_UID(AID_SYSTEM);
1007
yro74fed972017-11-27 14:42:42 -08001008 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001009 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1010 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001011 return Status::fromExceptionCode(
1012 Status::EX_NULL_POINTER,
1013 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001014 }
yro74fed972017-11-27 14:42:42 -08001015 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001016 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001017 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001018 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1019 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -08001020 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001021 return Status::ok();
1022}
1023
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001024void StatsService::Startup() {
1025 mConfigManager->Startup();
Chenjie Yuc7939cb2019-02-04 17:25:45 -08001026 mProcessor->LoadMetricsActivationFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001027}
1028
Yangster-mac97e7d202018-10-09 11:05:39 -07001029void StatsService::Terminate() {
1030 ALOGI("StatsService::Terminating");
1031 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001032 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Yangster-mac97e7d202018-10-09 11:05:39 -07001033 }
1034}
1035
Yao Chen0f861862019-03-27 11:51:15 -07001036// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001037void StatsService::OnLogEvent(LogEvent* event) {
1038 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001039 if (mShellSubscriber != nullptr) {
1040 mShellSubscriber->onLogEvent(*event);
1041 }
Bookatz906a35c2017-09-20 15:26:44 -07001042}
1043
Jeff Sharkey6b649252018-04-16 09:50:22 -06001044Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1045 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1046
David Chenadaf8b32017-11-03 15:42:08 -07001047 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001048 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001049 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001050 // The dump latency does not matter here since we do not include the current bucket, we do not
1051 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001052 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001053 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001054 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001055}
1056
Jeff Sharkey6b649252018-04-16 09:50:22 -06001057Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1058 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1059
David Chen2e8f3802017-11-22 10:56:48 -08001060 IPCThreadState* ipc = IPCThreadState::self();
1061 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1062 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001063 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1064 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001065}
1066
Jeff Sharkey6b649252018-04-16 09:50:22 -06001067Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1068 const String16& packageName) {
1069 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1070
David Chenadaf8b32017-11-03 15:42:08 -07001071 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001072 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001073 return Status::ok();
1074 } else {
Bookatz4f716292018-04-10 17:15:12 -07001075 ALOGE("Could not parse malformatted StatsdConfig");
1076 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1077 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001078 }
1079}
1080
David Chen9fdd4032018-03-20 14:38:56 -07001081bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1082 ConfigKey configKey(uid, key);
1083 StatsdConfig cfg;
1084 if (config.size() > 0) { // If the config is empty, skip parsing.
1085 if (!cfg.ParseFromArray(&config[0], config.size())) {
1086 return false;
1087 }
1088 }
1089 mConfigManager->UpdateConfig(configKey, cfg);
1090 return true;
1091}
1092
Jeff Sharkey6b649252018-04-16 09:50:22 -06001093Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1094 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1095
Bookatz4f716292018-04-10 17:15:12 -07001096 IPCThreadState* ipc = IPCThreadState::self();
1097 ConfigKey configKey(ipc->getCallingUid(), key);
1098 mConfigManager->RemoveConfigReceiver(configKey);
1099 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001100}
1101
Jeff Sharkey6b649252018-04-16 09:50:22 -06001102Status StatsService::setDataFetchOperation(int64_t key,
1103 const sp<android::IBinder>& intentSender,
1104 const String16& packageName) {
1105 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1106
Bookatz4f716292018-04-10 17:15:12 -07001107 IPCThreadState* ipc = IPCThreadState::self();
1108 ConfigKey configKey(ipc->getCallingUid(), key);
1109 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001110 if (StorageManager::hasConfigMetricsReport(configKey)) {
1111 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1112 configKey.ToString().c_str());
1113 mProcessor->noteOnDiskData(configKey);
1114 }
Bookatz4f716292018-04-10 17:15:12 -07001115 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001116}
1117
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001118Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1119 const String16& packageName,
1120 vector<int64_t>* output) {
1121 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1122
1123 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001124 int uid = ipc->getCallingUid();
1125 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1126 if (output != nullptr) {
1127 mProcessor->GetActiveConfigs(uid, *output);
1128 } else {
1129 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1130 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001131 return Status::ok();
1132}
1133
1134Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1135 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1136
1137 IPCThreadState* ipc = IPCThreadState::self();
1138 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1139 return Status::ok();
1140}
1141
Jeff Sharkey6b649252018-04-16 09:50:22 -06001142Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1143 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1144
Bookatz4f716292018-04-10 17:15:12 -07001145 IPCThreadState* ipc = IPCThreadState::self();
1146 ConfigKey configKey(ipc->getCallingUid(), key);
1147 mConfigManager->RemoveConfig(configKey);
1148 SubscriberReporter::getInstance().removeConfig(configKey);
1149 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001150}
1151
Bookatzc6977972018-01-16 16:55:05 -08001152Status StatsService::setBroadcastSubscriber(int64_t configId,
1153 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001154 const sp<android::IBinder>& intentSender,
1155 const String16& packageName) {
1156 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1157
Bookatzc6977972018-01-16 16:55:05 -08001158 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001159 IPCThreadState* ipc = IPCThreadState::self();
1160 ConfigKey configKey(ipc->getCallingUid(), configId);
1161 SubscriberReporter::getInstance()
1162 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1163 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001164}
1165
1166Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001167 int64_t subscriberId,
1168 const String16& packageName) {
1169 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1170
Bookatzc6977972018-01-16 16:55:05 -08001171 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001172 IPCThreadState* ipc = IPCThreadState::self();
1173 ConfigKey configKey(ipc->getCallingUid(), configId);
1174 SubscriberReporter::getInstance()
1175 .unsetBroadcastSubscriber(configKey, subscriberId);
1176 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001177}
1178
yrobe6d7f92018-05-04 13:02:53 -07001179Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1180 // Permission check not necessary as it's meant for applications to write to
1181 // statsd.
1182 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1183 IPCThreadState::self()->getCallingUid(), label,
1184 state);
1185 return Status::ok();
1186}
1187
Tej Singha0c89dd2019-01-25 16:39:18 -08001188Status StatsService::registerPullerCallback(int32_t atomTag,
1189 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1190 const String16& packageName) {
1191 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1192
1193 VLOG("StatsService::registerPullerCallback called.");
1194 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1195 return Status::ok();
1196}
1197
1198Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1199 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1200
1201 VLOG("StatsService::unregisterPullerCallback called.");
1202 mPullerManager->UnregisterPullerCallback(atomTag);
1203 return Status::ok();
1204}
1205
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001206Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainName,
1207 int64_t trainVersionCode, int options,
1208 int32_t state,
1209 const std::vector<int64_t>& experimentIds) {
1210 uid_t uid = IPCThreadState::self()->getCallingUid();
1211 // For testing
1212 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
1213 return ok();
1214 }
1215
1216 // Caller must be granted these permissions
1217 if (!checkCallingPermission(String16(kPermissionDump))) {
1218 return exception(binder::Status::EX_SECURITY,
1219 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1220 }
1221 if (!checkCallingPermission(String16(kPermissionUsage))) {
1222 return exception(binder::Status::EX_SECURITY,
1223 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1224 }
1225 // TODO: add verifier permission
1226
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001227 bool readTrainInfoSuccess = false;
1228 InstallTrainInfo trainInfo;
1229 if (trainVersionCode == -1 || experimentIds.empty() || trainName.size() == 0) {
1230 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfo);
1231 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001232
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001233 if (trainVersionCode == -1 && readTrainInfoSuccess) {
1234 trainVersionCode = trainInfo.trainVersionCode;
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001235 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001236
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001237 vector<uint8_t> experimentIdsProtoBuffer;
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001238 if (readTrainInfoSuccess && experimentIds.empty()) {
1239 experimentIdsProtoBuffer = trainInfo.experimentIds;
1240 } else {
1241 ProtoOutputStream proto;
1242 for (const auto& expId : experimentIds) {
1243 proto.write(FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_EXPERIMENT_ID,
1244 (long long)expId);
1245 }
1246
1247 experimentIdsProtoBuffer.resize(proto.size());
1248 size_t pos = 0;
Joe Onorato99598ee2019-02-11 15:55:13 +00001249 sp<ProtoReader> reader = proto.data();
1250 while (reader->readBuffer() != NULL) {
1251 size_t toRead = reader->currentToRead();
1252 std::memcpy(&(experimentIdsProtoBuffer[pos]), reader->readBuffer(), toRead);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001253 pos += toRead;
Joe Onorato99598ee2019-02-11 15:55:13 +00001254 reader->move(toRead);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001255 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001256 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001257
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001258 std::string trainNameUtf8;
1259 if (readTrainInfoSuccess && trainName.size() == 0) {
1260 trainNameUtf8 = trainInfo.trainName;
1261 } else {
1262 trainNameUtf8 = std::string(String8(trainName).string());
1263 }
1264
1265 userid_t userId = multiuser_get_user_id(uid);
1266 bool requiresStaging = options & IStatsManager::FLAG_REQUIRE_STAGING;
1267 bool rollbackEnabled = options & IStatsManager::FLAG_ROLLBACK_ENABLED;
1268 bool requiresLowLatencyMonitor = options & IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001269 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1270 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001271 mProcessor->OnLogEvent(&event);
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001272 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIdsProtoBuffer);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001273 return Status::ok();
1274}
1275
Howard Roa46b6582018-09-18 16:45:02 -07001276hardware::Return<void> StatsService::reportSpeakerImpedance(
1277 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001278 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1279 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001280
1281 return hardware::Void();
1282}
1283
1284hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001285 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1286 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001287
1288 return hardware::Void();
1289}
1290
1291hardware::Return<void> StatsService::reportPhysicalDropDetected(
1292 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001293 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1294 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1295 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001296
1297 return hardware::Void();
1298}
1299
1300hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001301 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1302 int initialSize = buckets.size();
1303 for (int i = 0; i < 10 - initialSize; i++) {
1304 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1305 }
1306 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1307 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1308 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001309
1310 return hardware::Void();
1311}
1312
1313hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1314 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001315 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1316 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1317 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1318 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1319 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001320
1321 return hardware::Void();
1322}
1323
1324hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001325 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001326
1327 return hardware::Void();
1328}
1329
1330hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1331 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001332 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1333 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001334
1335 return hardware::Void();
1336}
1337
Maggie Whitefc1aa592018-11-28 21:55:23 -08001338hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1339 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001340 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1341 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1342 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1343 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001344
1345 return hardware::Void();
1346}
1347
Carter Hsub8fd1e92019-01-11 15:24:45 +08001348hardware::Return<void> StatsService::reportSpeechDspStat(
1349 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001350 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1351 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1352 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001353
1354 return hardware::Void();
1355}
1356
Maggie White58174da2019-01-18 15:23:35 -08001357hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1358 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1359 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1360 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1361 return hardware::Void();
1362 }
1363 if (reverseDomainName.length() > 50) {
1364 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1365 return hardware::Void();
1366 }
1367 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1368 mProcessor->OnLogEvent(&event);
1369
1370 return hardware::Void();
1371}
1372
David Chen1d7b0cd2017-11-15 14:20:04 -08001373void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001374 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001375 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1376 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001377 ALOGW("Reset statsd upon system server restarts.");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001378 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001379 mProcessor->resetConfigs();
1380 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001381 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1382 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1383 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001384 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001385}
1386
Yao Chenef99c4f2017-09-22 16:26:54 -07001387} // namespace statsd
1388} // namespace os
1389} // namespace android