blob: 7fa05be29b9d9e5207e10a19929ad62615e8e72c [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>
yro87d983c2017-11-14 21:31:43 -080034#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070035#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070036#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080037#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070038#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070039#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070040#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070041#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070042#include <utils/Looper.h>
43#include <utils/String16.h>
44#include <chrono>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070045
46using namespace android;
47
Jeff Sharkey6b649252018-04-16 09:50:22 -060048using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070049using android::util::FIELD_COUNT_REPEATED;
50using android::util::FIELD_TYPE_MESSAGE;
Jeff Sharkey6b649252018-04-16 09:50:22 -060051
Bookatz906a35c2017-09-20 15:26:44 -070052namespace android {
53namespace os {
54namespace statsd {
55
David Chenadaf8b32017-11-03 15:42:08 -070056constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060057constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
58
59constexpr const char* kOpUsage = "android:get_usage_stats";
60
yro03faf092017-12-12 00:17:50 -080061#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070062
Bookatzff71cad2018-09-20 17:17:49 -070063// for StatsDataDumpProto
64const int FIELD_ID_REPORTS_LIST = 1;
65
Jeff Sharkey6b649252018-04-16 09:50:22 -060066static binder::Status ok() {
67 return binder::Status::ok();
68}
69
70static binder::Status exception(uint32_t code, const std::string& msg) {
71 ALOGE("%s (%d)", msg.c_str(), code);
72 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
73}
74
75binder::Status checkUid(uid_t expectedUid) {
76 uid_t uid = IPCThreadState::self()->getCallingUid();
77 if (uid == expectedUid || uid == AID_ROOT) {
78 return ok();
79 } else {
80 return exception(binder::Status::EX_SECURITY,
81 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
82 }
83}
84
85binder::Status checkDumpAndUsageStats(const String16& packageName) {
86 pid_t pid = IPCThreadState::self()->getCallingPid();
87 uid_t uid = IPCThreadState::self()->getCallingUid();
88
89 // Root, system, and shell always have access
90 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
91 return ok();
92 }
93
94 // Caller must be granted these permissions
95 if (!checkCallingPermission(String16(kPermissionDump))) {
96 return exception(binder::Status::EX_SECURITY,
97 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
98 }
99 if (!checkCallingPermission(String16(kPermissionUsage))) {
100 return exception(binder::Status::EX_SECURITY,
101 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
102 }
103
104 // Caller must also have usage stats op granted
105 PermissionController pc;
106 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
107 case PermissionController::MODE_ALLOWED:
108 case PermissionController::MODE_DEFAULT:
109 return ok();
110 default:
111 return exception(binder::Status::EX_SECURITY,
112 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
113 }
114}
115
116#define ENFORCE_UID(uid) { \
117 binder::Status status = checkUid((uid)); \
118 if (!status.isOk()) { \
119 return status; \
120 } \
121}
122
123#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
124 binder::Status status = checkDumpAndUsageStats(packageName); \
125 if (!status.isOk()) { \
126 return status; \
127 } \
128}
129
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700130StatsService::StatsService(const sp<Looper>& handlerLooper)
Yangster-mac932ecec2018-02-01 10:23:52 -0800131 : mAnomalyAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
132 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
133 if (sc != nullptr) {
134 sc->setAnomalyAlarm(timeMillis);
135 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
136 }
137 },
138 [](const sp<IStatsCompanionService>& sc) {
139 if (sc != nullptr) {
140 sc->cancelAnomalyAlarm();
141 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
142 }
143 })),
144 mPeriodicAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
145 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
146 if (sc != nullptr) {
147 sc->setAlarmForSubscriberTriggering(timeMillis);
148 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
149 }
150 },
151 [](const sp<IStatsCompanionService>& sc) {
152 if (sc != nullptr) {
153 sc->cancelAlarmForSubscriberTriggering();
154 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
155 }
156
157 })) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700158 mUidMap = new UidMap();
Chenjie Yue2219202018-06-08 10:07:51 -0700159 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800160 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700161 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700162 mProcessor = new StatsLogProcessor(
163 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
164 getElapsedRealtimeNs(), [this](const ConfigKey& key) {
165 sp<IStatsCompanionService> sc = getStatsCompanionService();
166 auto receiver = mConfigManager->GetConfigReceiver(key);
167 if (sc == nullptr) {
168 VLOG("Could not find StatsCompanionService");
169 return false;
170 } else if (receiver == nullptr) {
171 VLOG("Statscompanion could not find a broadcast receiver for %s",
172 key.ToString().c_str());
173 return false;
174 } else {
175 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
176 return true;
177 }
178 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700179
180 mConfigManager->AddListener(mProcessor);
181
182 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700183}
184
Yao Chenef99c4f2017-09-22 16:26:54 -0700185StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700186}
187
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700188void StatsService::init_system_properties() {
189 mEngBuild = false;
190 const prop_info* buildType = __system_property_find("ro.build.type");
191 if (buildType != NULL) {
192 __system_property_read_callback(buildType, init_build_type_callback, this);
193 }
David Chen0656b7a2017-09-13 15:53:39 -0700194}
195
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700196void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
197 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700198 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700199 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
200 }
201}
202
203/**
204 * Implement our own because the default binder implementation isn't
205 * properly handling SHELL_COMMAND_TRANSACTION.
206 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700207status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
208 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700209 switch (code) {
210 case SHELL_COMMAND_TRANSACTION: {
211 int in = data.readFileDescriptor();
212 int out = data.readFileDescriptor();
213 int err = data.readFileDescriptor();
214 int argc = data.readInt32();
215 Vector<String8> args;
216 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
217 args.add(String8(data.readString16()));
218 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700219 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
220 sp<IResultReceiver> resultReceiver =
221 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700222
Yao Chena80e5c02018-09-04 13:55:29 -0700223 err = command(in, out, err, args, resultReceiver);
224 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700225 return NO_ERROR;
226 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700227 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700228 }
229}
230
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700231/**
Bookatzff71cad2018-09-20 17:17:49 -0700232 * Write data from statsd.
233 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
234 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
235 * Anything ending in --proto will be in proto format.
236 * Anything without --metadata as the first argument will be report information.
237 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
238 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700239 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700240status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700241 if (!checkCallingPermission(String16(kPermissionDump))) {
242 return PERMISSION_DENIED;
243 }
Bookatzff71cad2018-09-20 17:17:49 -0700244 int lastArg = args.size() - 1;
245 bool asProto = false;
246 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
247 asProto = true;
248 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800249 }
Bookatzff71cad2018-09-20 17:17:49 -0700250 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
251 // Request is to dump statsd stats.
252 bool verbose = false;
253 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
254 verbose = true;
255 lastArg--;
256 }
257 dumpStatsdStats(fd, verbose, asProto);
258 } else {
259 // Request is to dump statsd report data.
260 if (asProto) {
261 dumpIncidentSection(fd);
262 } else {
263 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
264 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700265 }
Yao Chen884c8c12018-01-26 10:36:25 -0800266
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700267 return NO_ERROR;
268}
269
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700270/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700271 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700272 */
Bookatzff71cad2018-09-20 17:17:49 -0700273void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700274 if (proto) {
275 vector<uint8_t> data;
276 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
277 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700278 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700279 }
280 } else {
281 StatsdStats::getInstance().dumpStats(out);
282 mProcessor->dumpStates(out, verbose);
283 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700284}
285
286/**
Bookatzff71cad2018-09-20 17:17:49 -0700287 * Write stats report data in StatsDataDumpProto incident section format.
288 */
289void StatsService::dumpIncidentSection(int out) {
290 ProtoOutputStream proto;
291 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
292 uint64_t reportsListToken =
293 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
294 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
295 true /* includeCurrentBucket */, false /* erase_data */,
296 ADB_DUMP, &proto);
297 proto.end(reportsListToken);
298 proto.flush(out);
299 }
300}
301
302/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700303 * Implementation of the adb shell cmd stats command.
304 */
Yao Chena80e5c02018-09-04 13:55:29 -0700305status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
306 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600307 uid_t uid = IPCThreadState::self()->getCallingUid();
308 if (uid != AID_ROOT && uid != AID_SHELL) {
309 return PERMISSION_DENIED;
310 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700311
312 const int argCount = args.size();
313 if (argCount >= 1) {
314 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700315 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700316 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700317 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700318
David Chende701692017-10-05 13:16:02 -0700319 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800320 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700321 }
Yao Chen729093d2017-10-16 10:33:26 -0700322
323 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700324 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700325 }
David Chen1481fe12017-10-16 13:16:34 -0700326
327 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
328 return cmd_print_pulled_metrics(out, args);
329 }
David Chenadaf8b32017-11-03 15:42:08 -0700330
331 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800332 return cmd_trigger_broadcast(out, args);
333 }
334
335 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800336 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700337 }
yro87d983c2017-11-14 21:31:43 -0800338
Yao Chen8d9989b2017-11-18 18:54:50 -0800339 if (!args[0].compare(String8("meminfo"))) {
340 return cmd_dump_memory_info(out);
341 }
yro947fbce2017-11-15 22:50:23 -0800342
343 if (!args[0].compare(String8("write-to-disk"))) {
344 return cmd_write_data_to_disk(out);
345 }
Bookatzb223c4e2018-02-01 15:35:04 -0800346
David Chen0b5c90c2018-01-25 16:51:49 -0800347 if (!args[0].compare(String8("log-app-breadcrumb"))) {
348 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800349 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800350
351 if (!args[0].compare(String8("clear-puller-cache"))) {
352 return cmd_clear_puller_cache(out);
353 }
Yao Chen876889c2018-05-02 11:16:16 -0700354
355 if (!args[0].compare(String8("print-logs"))) {
356 return cmd_print_logs(out, args);
357 }
Yao Chena80e5c02018-09-04 13:55:29 -0700358 if (!args[0].compare(String8("data-subscribe"))) {
359 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700360 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700361 }
362 mShellSubscriber->startNewSubscription(in, out, resultReceiver);
363 return NO_ERROR;
364 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700365 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700366
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700367 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700368 return NO_ERROR;
369}
370
Yao Chena80e5c02018-09-04 13:55:29 -0700371void StatsService::print_cmd_help(int out) {
372 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700373 "usage: adb shell cmd stats print-stats-log [tag_required] "
374 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700375 dprintf(out, "\n");
376 dprintf(out, "\n");
377 dprintf(out, "usage: adb shell cmd stats meminfo\n");
378 dprintf(out, "\n");
379 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
380 dprintf(out, " # adb shell stop\n");
381 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
382 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
383 dprintf(out, " # adb shell start\n");
384 dprintf(out, "\n");
385 dprintf(out, "\n");
386 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
387 dprintf(out, "\n");
388 dprintf(out, " Prints the UID, app name, version mapping.\n");
389 dprintf(out, " PKG Optional package name to print the uids of the package\n");
390 dprintf(out, "\n");
391 dprintf(out, "\n");
392 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
393 dprintf(out, "\n");
394 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
395 dprintf(out, "\n");
396 dprintf(out, "\n");
397 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
398 dprintf(out, "\n");
399 dprintf(out, " Flushes all data on memory to disk.\n");
400 dprintf(out, "\n");
401 dprintf(out, "\n");
402 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
403 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
404 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
405 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
406 dprintf(out, " uid is used.\n");
407 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
408 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
409 dprintf(out, "\n");
410 dprintf(out, "\n");
411 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
412 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
413 dprintf(out, "\n");
414 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
415 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
416 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
417 dprintf(out, "\n");
418 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
419 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
420 dprintf(out, " uid is used.\n");
421 dprintf(out, " NAME The per-uid name to use\n");
422 dprintf(out, "\n");
423 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
424 dprintf(out, "\n be removed from memory and disk!\n");
425 dprintf(out, "\n");
426 dprintf(out,
427 "usage: adb shell cmd stats dump-report [UID] NAME [--include_current_bucket] "
428 "[--proto]\n");
429 dprintf(out, " Dump all metric data for a configuration.\n");
430 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
431 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
432 dprintf(out, " calling uid is used.\n");
433 dprintf(out, " NAME The name of the configuration\n");
434 dprintf(out, " --proto Print proto binary.\n");
435 dprintf(out, "\n");
436 dprintf(out, "\n");
437 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
438 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
439 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
440 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
441 dprintf(out, " calling uid is used.\n");
442 dprintf(out, " NAME The name of the configuration\n");
443 dprintf(out, "\n");
444 dprintf(out, "\n");
445 dprintf(out, "usage: adb shell cmd stats print-stats\n");
446 dprintf(out, " Prints some basic stats.\n");
447 dprintf(out, " --proto Print proto binary instead of string format.\n");
448 dprintf(out, "\n");
449 dprintf(out, "\n");
450 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
451 dprintf(out, " Clear cached puller data.\n");
452 dprintf(out, "\n");
453 dprintf(out, "usage: adb shell cmd stats print-logs\n");
454 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700455}
456
Yao Chena80e5c02018-09-04 13:55:29 -0700457status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800458 string name;
459 bool good = false;
460 int uid;
461 const int argCount = args.size();
462 if (argCount == 2) {
463 // Automatically pick the UID
464 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800465 name.assign(args[1].c_str(), args[1].size());
466 good = true;
467 } else if (argCount == 3) {
468 // If it's a userdebug or eng build, then the shell user can
469 // impersonate other uids.
470 if (mEngBuild) {
471 const char* s = args[1].c_str();
472 if (*s != '\0') {
473 char* end = NULL;
474 uid = strtol(s, &end, 0);
475 if (*end == '\0') {
476 name.assign(args[2].c_str(), args[2].size());
477 good = true;
478 }
479 }
480 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700481 dprintf(out,
David Chen1d7b0cd2017-11-15 14:20:04 -0800482 "The metrics can only be dumped for other UIDs on eng or userdebug "
Yao Chena80e5c02018-09-04 13:55:29 -0700483 "builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800484 }
485 }
486 if (!good) {
487 print_cmd_help(out);
488 return UNKNOWN_ERROR;
489 }
David Chend37bc232018-04-12 18:05:11 -0700490 ConfigKey key(uid, StrToInt64(name));
491 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800492 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800493 if (sc == nullptr) {
494 VLOG("Could not access statsCompanion");
495 } else if (receiver == nullptr) {
496 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
497 } else {
David Chend37bc232018-04-12 18:05:11 -0700498 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800499 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
500 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800501 }
502
David Chenadaf8b32017-11-03 15:42:08 -0700503 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700504}
505
Yao Chena80e5c02018-09-04 13:55:29 -0700506status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700507 const int argCount = args.size();
508 if (argCount >= 2) {
509 if (args[1] == "update" || args[1] == "remove") {
510 bool good = false;
511 int uid = -1;
512 string name;
513
514 if (argCount == 3) {
515 // Automatically pick the UID
516 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700517 name.assign(args[2].c_str(), args[2].size());
518 good = true;
519 } else if (argCount == 4) {
520 // If it's a userdebug or eng build, then the shell user can
521 // impersonate other uids.
522 if (mEngBuild) {
523 const char* s = args[2].c_str();
524 if (*s != '\0') {
525 char* end = NULL;
526 uid = strtol(s, &end, 0);
527 if (*end == '\0') {
528 name.assign(args[3].c_str(), args[3].size());
529 good = true;
530 }
531 }
532 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700533 dprintf(err,
Yao Chen729093d2017-10-16 10:33:26 -0700534 "The config can only be set for other UIDs on eng or userdebug "
535 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700536 }
yroe5f82922018-01-22 18:37:27 -0800537 } else if (argCount == 2 && args[1] == "remove") {
538 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700539 }
540
541 if (!good) {
542 // If arg parsing failed, print the help text and return an error.
543 print_cmd_help(out);
544 return UNKNOWN_ERROR;
545 }
546
547 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800548 char* endp;
549 int64_t configID = strtoll(name.c_str(), &endp, 10);
550 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700551 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800552 return UNKNOWN_ERROR;
553 }
554
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700555 // Read stream into buffer.
556 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700557 if (!android::base::ReadFdToString(in, &buffer)) {
558 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700559 return UNKNOWN_ERROR;
560 }
561
562 // Parse buffer.
563 StatsdConfig config;
564 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700565 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700566 return UNKNOWN_ERROR;
567 }
568
569 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800570 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700571 } else {
yro74fed972017-11-27 14:42:42 -0800572 if (argCount == 2) {
573 cmd_remove_all_configs(out);
574 } else {
575 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800576 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800577 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700578 }
579
580 return NO_ERROR;
581 }
David Chen0656b7a2017-09-13 15:53:39 -0700582 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700583 print_cmd_help(out);
584 return UNKNOWN_ERROR;
585}
586
Bookatzff71cad2018-09-20 17:17:49 -0700587status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700588 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800589 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700590 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800591 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700592 bool includeCurrentBucket = false;
Yao Chen729093d2017-10-16 10:33:26 -0700593 int uid;
594 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800595 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
596 proto = true;
597 argCount -= 1;
598 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700599 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
600 includeCurrentBucket = true;
601 argCount -= 1;
602 }
Yao Chen729093d2017-10-16 10:33:26 -0700603 if (argCount == 2) {
604 // Automatically pick the UID
605 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700606 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700607 good = true;
608 } else if (argCount == 3) {
609 // If it's a userdebug or eng build, then the shell user can
610 // impersonate other uids.
611 if (mEngBuild) {
612 const char* s = args[1].c_str();
613 if (*s != '\0') {
614 char* end = NULL;
615 uid = strtol(s, &end, 0);
616 if (*end == '\0') {
617 name.assign(args[2].c_str(), args[2].size());
618 good = true;
619 }
620 }
621 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700622 dprintf(out,
Yao Chen729093d2017-10-16 10:33:26 -0700623 "The metrics can only be dumped for other UIDs on eng or userdebug "
624 "builds.\n");
625 }
626 }
627 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800628 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800629 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Bookatzff71cad2018-09-20 17:17:49 -0700630 includeCurrentBucket, true /* erase_data */, ADB_DUMP, &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800631 if (proto) {
632 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700633 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800634 }
635 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700636 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800637 }
Yao Chen729093d2017-10-16 10:33:26 -0700638 return android::OK;
639 } else {
640 // If arg parsing failed, print the help text and return an error.
641 print_cmd_help(out);
642 return UNKNOWN_ERROR;
643 }
644 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700645 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700646 return UNKNOWN_ERROR;
647 }
648}
649
Yao Chena80e5c02018-09-04 13:55:29 -0700650status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700651 int argCount = args.size();
652 bool proto = false;
653 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
654 proto = true;
655 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800656 }
Yao Chenb3561512017-11-21 18:07:17 -0800657 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700658 if (proto) {
659 vector<uint8_t> data;
660 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
661 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700662 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700663 }
664
665 } else {
666 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
667 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700668 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700669 mProcessor->GetMetricsSize(key));
670 }
671 statsdStats.dumpStats(out);
672 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800673 return NO_ERROR;
674}
675
Yao Chena80e5c02018-09-04 13:55:29 -0700676status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800677 if (args.size() > 1) {
678 string pkg;
679 pkg.assign(args[1].c_str(), args[1].size());
680 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700681 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800682 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700683 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800684 }
Yao Chena80e5c02018-09-04 13:55:29 -0700685 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800686 } else {
687 mUidMap->printUidMap(out);
688 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700689 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700690}
691
Yao Chena80e5c02018-09-04 13:55:29 -0700692status_t StatsService::cmd_write_data_to_disk(int out) {
693 dprintf(out, "Writing data to disk\n");
Yangster-mac892f3d32018-05-02 14:16:48 -0700694 mProcessor->WriteDataToDisk(ADB_DUMP);
yro947fbce2017-11-15 22:50:23 -0800695 return NO_ERROR;
696}
697
Yao Chena80e5c02018-09-04 13:55:29 -0700698status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800699 bool good = false;
700 int32_t uid;
701 int32_t label;
702 int32_t state;
703 const int argCount = args.size();
704 if (argCount == 3) {
705 // Automatically pick the UID
706 uid = IPCThreadState::self()->getCallingUid();
707 label = atoi(args[1].c_str());
708 state = atoi(args[2].c_str());
709 good = true;
710 } else if (argCount == 4) {
711 uid = atoi(args[1].c_str());
712 // If it's a userdebug or eng build, then the shell user can impersonate other uids.
713 // Otherwise, the uid must match the actual caller's uid.
714 if (mEngBuild || (uid >= 0 && (uid_t)uid == IPCThreadState::self()->getCallingUid())) {
715 label = atoi(args[2].c_str());
716 state = atoi(args[3].c_str());
717 good = true;
718 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700719 dprintf(out,
David Chenb639d142018-02-14 17:29:54 -0800720 "Selecting a UID for writing AppBreadcrumb can only be done for other UIDs "
Yao Chena80e5c02018-09-04 13:55:29 -0700721 "on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800722 }
723 }
724 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700725 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800726 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800727 } else {
728 print_cmd_help(out);
729 return UNKNOWN_ERROR;
730 }
731 return NO_ERROR;
732}
733
Yao Chena80e5c02018-09-04 13:55:29 -0700734status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700735 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700736 vector<shared_ptr<LogEvent> > stats;
Chenjie Yue2219202018-06-08 10:07:51 -0700737 if (mPullerManager->Pull(s, getElapsedRealtimeNs(), &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700738 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700739 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700740 }
Yao Chena80e5c02018-09-04 13:55:29 -0700741 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700742 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700743 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700744 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700745}
746
Yao Chena80e5c02018-09-04 13:55:29 -0700747status_t StatsService::cmd_remove_all_configs(int out) {
748 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800749 VLOG("StatsService::cmd_remove_all_configs was called");
750 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800751 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800752 return NO_ERROR;
753}
754
Yao Chena80e5c02018-09-04 13:55:29 -0700755status_t StatsService::cmd_dump_memory_info(int out) {
756 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800757 return NO_ERROR;
758}
759
Yao Chena80e5c02018-09-04 13:55:29 -0700760status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800761 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800762 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
763 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800764 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700765 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700766 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800767 return NO_ERROR;
768 } else {
769 return PERMISSION_DENIED;
770 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800771}
772
Yao Chena80e5c02018-09-04 13:55:29 -0700773status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700774 IPCThreadState* ipc = IPCThreadState::self();
775 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
776 ipc->getCallingUid());
777 if (checkCallingPermission(String16(kPermissionDump))) {
778 bool enabled = true;
779 if (args.size() >= 2) {
780 enabled = atoi(args[1].c_str()) != 0;
781 }
782 mProcessor->setPrintLogs(enabled);
783 return NO_ERROR;
784 } else {
785 return PERMISSION_DENIED;
786 }
787}
788
Dianne Hackborn3accca02013-09-20 09:32:11 -0700789Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700790 const vector<String16>& version_string,
791 const vector<String16>& app,
792 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600793 ENFORCE_UID(AID_SYSTEM);
794
yro74fed972017-11-27 14:42:42 -0800795 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700796 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800797 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700798
799 return Status::ok();
800}
801
dwchen730403e2018-10-29 11:41:56 -0700802Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
803 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600804 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700805
Jeff Sharkey6b649252018-04-16 09:50:22 -0600806 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700807 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700808 return Status::ok();
809}
810
811Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600812 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700813
Jeff Sharkey6b649252018-04-16 09:50:22 -0600814 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700815 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800816 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700817 return Status::ok();
818}
819
Yao Chenef99c4f2017-09-22 16:26:54 -0700820Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600821 ENFORCE_UID(AID_SYSTEM);
822
yro74fed972017-11-27 14:42:42 -0800823 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700824 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800825 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
826 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
827 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800828 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800829 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800830 } else {
831 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
832 }
Bookatz1b0b1142017-09-08 11:58:42 -0700833 return Status::ok();
834}
835
Yangster-mac932ecec2018-02-01 10:23:52 -0800836Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600837 ENFORCE_UID(AID_SYSTEM);
838
Yangster-mac932ecec2018-02-01 10:23:52 -0800839 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700840 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800841 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
842 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
843 if (alarmSet.size() > 0) {
844 VLOG("Found periodic alarm fired.");
845 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
846 } else {
847 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
848 }
849 return Status::ok();
850}
851
Yao Chenef99c4f2017-09-22 16:26:54 -0700852Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600853 ENFORCE_UID(AID_SYSTEM);
854
yro74fed972017-11-27 14:42:42 -0800855 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700856 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800857 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700858 return Status::ok();
859}
860
Yao Chenef99c4f2017-09-22 16:26:54 -0700861Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600862 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700863
864 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800865 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700866 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700867 return Status::ok();
868}
869
Yangster-mac892f3d32018-05-02 14:16:48 -0700870Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600871 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700872 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700873 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
yro947fbce2017-11-15 22:50:23 -0800874 return Status::ok();
875}
876
Yao Chenef99c4f2017-09-22 16:26:54 -0700877void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700878 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
879 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800880 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700881 statsCompanion->statsdReady();
882 } else {
yro74fed972017-11-27 14:42:42 -0800883 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700884 }
885}
886
Yao Chenef99c4f2017-09-22 16:26:54 -0700887Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600888 ENFORCE_UID(AID_SYSTEM);
889
yro74fed972017-11-27 14:42:42 -0800890 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700891 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
892 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700893 return Status::fromExceptionCode(
894 Status::EX_NULL_POINTER,
895 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700896 }
yro74fed972017-11-27 14:42:42 -0800897 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700898 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700899 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800900 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
901 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800902 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700903 return Status::ok();
904}
905
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700906void StatsService::Startup() {
907 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700908}
909
Yangster-mac97e7d202018-10-09 11:05:39 -0700910void StatsService::Terminate() {
911 ALOGI("StatsService::Terminating");
912 if (mProcessor != nullptr) {
913 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED);
914 }
915}
916
Yao Chen3ff3a492018-08-06 16:17:37 -0700917void StatsService::OnLogEvent(LogEvent* event) {
918 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -0700919 if (mShellSubscriber != nullptr) {
920 mShellSubscriber->onLogEvent(*event);
921 }
Bookatz906a35c2017-09-20 15:26:44 -0700922}
923
Jeff Sharkey6b649252018-04-16 09:50:22 -0600924Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
925 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
926
David Chenadaf8b32017-11-03 15:42:08 -0700927 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800928 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700929 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen56ae0d92018-05-11 16:00:22 -0700930 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Bookatzff71cad2018-09-20 17:17:49 -0700931 true /* erase_data */, GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -0700932 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700933}
934
Jeff Sharkey6b649252018-04-16 09:50:22 -0600935Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
936 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
937
David Chen2e8f3802017-11-22 10:56:48 -0800938 IPCThreadState* ipc = IPCThreadState::self();
939 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
940 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700941 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
942 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -0800943}
944
Jeff Sharkey6b649252018-04-16 09:50:22 -0600945Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
946 const String16& packageName) {
947 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
948
David Chenadaf8b32017-11-03 15:42:08 -0700949 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -0700950 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -0800951 return Status::ok();
952 } else {
Bookatz4f716292018-04-10 17:15:12 -0700953 ALOGE("Could not parse malformatted StatsdConfig");
954 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
955 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -0800956 }
957}
958
David Chen9fdd4032018-03-20 14:38:56 -0700959bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
960 ConfigKey configKey(uid, key);
961 StatsdConfig cfg;
962 if (config.size() > 0) { // If the config is empty, skip parsing.
963 if (!cfg.ParseFromArray(&config[0], config.size())) {
964 return false;
965 }
966 }
967 mConfigManager->UpdateConfig(configKey, cfg);
968 return true;
969}
970
Jeff Sharkey6b649252018-04-16 09:50:22 -0600971Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
972 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
973
Bookatz4f716292018-04-10 17:15:12 -0700974 IPCThreadState* ipc = IPCThreadState::self();
975 ConfigKey configKey(ipc->getCallingUid(), key);
976 mConfigManager->RemoveConfigReceiver(configKey);
977 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -0800978}
979
Jeff Sharkey6b649252018-04-16 09:50:22 -0600980Status StatsService::setDataFetchOperation(int64_t key,
981 const sp<android::IBinder>& intentSender,
982 const String16& packageName) {
983 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
984
Bookatz4f716292018-04-10 17:15:12 -0700985 IPCThreadState* ipc = IPCThreadState::self();
986 ConfigKey configKey(ipc->getCallingUid(), key);
987 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -0700988 if (StorageManager::hasConfigMetricsReport(configKey)) {
989 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
990 configKey.ToString().c_str());
991 mProcessor->noteOnDiskData(configKey);
992 }
Bookatz4f716292018-04-10 17:15:12 -0700993 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700994}
995
Jeff Sharkey6b649252018-04-16 09:50:22 -0600996Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
997 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
998
Bookatz4f716292018-04-10 17:15:12 -0700999 IPCThreadState* ipc = IPCThreadState::self();
1000 ConfigKey configKey(ipc->getCallingUid(), key);
1001 mConfigManager->RemoveConfig(configKey);
1002 SubscriberReporter::getInstance().removeConfig(configKey);
1003 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001004}
1005
Bookatzc6977972018-01-16 16:55:05 -08001006Status StatsService::setBroadcastSubscriber(int64_t configId,
1007 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001008 const sp<android::IBinder>& intentSender,
1009 const String16& packageName) {
1010 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1011
Bookatzc6977972018-01-16 16:55:05 -08001012 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001013 IPCThreadState* ipc = IPCThreadState::self();
1014 ConfigKey configKey(ipc->getCallingUid(), configId);
1015 SubscriberReporter::getInstance()
1016 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1017 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001018}
1019
1020Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001021 int64_t subscriberId,
1022 const String16& packageName) {
1023 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1024
Bookatzc6977972018-01-16 16:55:05 -08001025 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001026 IPCThreadState* ipc = IPCThreadState::self();
1027 ConfigKey configKey(ipc->getCallingUid(), configId);
1028 SubscriberReporter::getInstance()
1029 .unsetBroadcastSubscriber(configKey, subscriberId);
1030 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001031}
1032
yrobe6d7f92018-05-04 13:02:53 -07001033Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1034 // Permission check not necessary as it's meant for applications to write to
1035 // statsd.
1036 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1037 IPCThreadState::self()->getCallingUid(), label,
1038 state);
1039 return Status::ok();
1040}
1041
Howard Roa46b6582018-09-18 16:45:02 -07001042hardware::Return<void> StatsService::reportSpeakerImpedance(
1043 const SpeakerImpedance& speakerImpedance) {
1044 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speakerImpedance);
1045 mProcessor->OnLogEvent(&event);
1046
1047 return hardware::Void();
1048}
1049
1050hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
1051 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), hardwareFailed);
1052 mProcessor->OnLogEvent(&event);
1053
1054 return hardware::Void();
1055}
1056
1057hardware::Return<void> StatsService::reportPhysicalDropDetected(
1058 const PhysicalDropDetected& physicalDropDetected) {
1059 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), physicalDropDetected);
1060 mProcessor->OnLogEvent(&event);
1061
1062 return hardware::Void();
1063}
1064
1065hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
1066 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), chargeCycles);
1067 mProcessor->OnLogEvent(&event);
1068
1069 return hardware::Void();
1070}
1071
1072hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1073 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
1074 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(),
1075 batteryHealthSnapshotArgs);
1076 mProcessor->OnLogEvent(&event);
1077
1078 return hardware::Void();
1079}
1080
1081hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
1082 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), slowIo);
1083 mProcessor->OnLogEvent(&event);
1084
1085 return hardware::Void();
1086}
1087
1088hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1089 const BatteryCausedShutdown& batteryCausedShutdown) {
1090 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), batteryCausedShutdown);
1091 mProcessor->OnLogEvent(&event);
1092
1093 return hardware::Void();
1094}
1095
David Chen1d7b0cd2017-11-15 14:20:04 -08001096void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001097 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001098 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1099 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001100 ALOGW("Reset statsd upon system server restarts.");
Yangster-mac892f3d32018-05-02 14:16:48 -07001101 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
1102 mProcessor->resetConfigs();
1103 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001104 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1105 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1106 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001107 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001108}
1109
Yao Chenef99c4f2017-09-22 16:26:54 -07001110} // namespace statsd
1111} // namespace os
1112} // namespace android