blob: 3107b4dd7fce3ea6a0a4175f319daf550853f477 [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);
Bookatzc71d9012018-12-19 12:28:38 -0800299 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700300 }
301}
302
303/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700304 * Implementation of the adb shell cmd stats command.
305 */
Yao Chena80e5c02018-09-04 13:55:29 -0700306status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
307 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600308 uid_t uid = IPCThreadState::self()->getCallingUid();
309 if (uid != AID_ROOT && uid != AID_SHELL) {
310 return PERMISSION_DENIED;
311 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700312
313 const int argCount = args.size();
314 if (argCount >= 1) {
315 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700316 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700317 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700318 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700319
David Chende701692017-10-05 13:16:02 -0700320 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800321 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700322 }
Yao Chen729093d2017-10-16 10:33:26 -0700323
324 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700325 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700326 }
David Chen1481fe12017-10-16 13:16:34 -0700327
328 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
329 return cmd_print_pulled_metrics(out, args);
330 }
David Chenadaf8b32017-11-03 15:42:08 -0700331
332 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800333 return cmd_trigger_broadcast(out, args);
334 }
335
336 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800337 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700338 }
yro87d983c2017-11-14 21:31:43 -0800339
Yao Chen8d9989b2017-11-18 18:54:50 -0800340 if (!args[0].compare(String8("meminfo"))) {
341 return cmd_dump_memory_info(out);
342 }
yro947fbce2017-11-15 22:50:23 -0800343
344 if (!args[0].compare(String8("write-to-disk"))) {
345 return cmd_write_data_to_disk(out);
346 }
Bookatzb223c4e2018-02-01 15:35:04 -0800347
David Chen0b5c90c2018-01-25 16:51:49 -0800348 if (!args[0].compare(String8("log-app-breadcrumb"))) {
349 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800350 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800351
352 if (!args[0].compare(String8("clear-puller-cache"))) {
353 return cmd_clear_puller_cache(out);
354 }
Yao Chen876889c2018-05-02 11:16:16 -0700355
356 if (!args[0].compare(String8("print-logs"))) {
357 return cmd_print_logs(out, args);
358 }
Yao Chena80e5c02018-09-04 13:55:29 -0700359 if (!args[0].compare(String8("data-subscribe"))) {
360 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700361 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700362 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800363 int timeoutSec = -1;
364 if (argCount >= 2) {
365 timeoutSec = atoi(args[1].c_str());
366 }
367 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700368 return NO_ERROR;
369 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700370 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700371
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700372 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700373 return NO_ERROR;
374}
375
Yao Chena80e5c02018-09-04 13:55:29 -0700376void StatsService::print_cmd_help(int out) {
377 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700378 "usage: adb shell cmd stats print-stats-log [tag_required] "
379 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700380 dprintf(out, "\n");
381 dprintf(out, "\n");
382 dprintf(out, "usage: adb shell cmd stats meminfo\n");
383 dprintf(out, "\n");
384 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
385 dprintf(out, " # adb shell stop\n");
386 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
387 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
388 dprintf(out, " # adb shell start\n");
389 dprintf(out, "\n");
390 dprintf(out, "\n");
391 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
392 dprintf(out, "\n");
393 dprintf(out, " Prints the UID, app name, version mapping.\n");
394 dprintf(out, " PKG Optional package name to print the uids of the package\n");
395 dprintf(out, "\n");
396 dprintf(out, "\n");
397 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
398 dprintf(out, "\n");
399 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
400 dprintf(out, "\n");
401 dprintf(out, "\n");
402 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
403 dprintf(out, "\n");
404 dprintf(out, " Flushes all data on memory to disk.\n");
405 dprintf(out, "\n");
406 dprintf(out, "\n");
407 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
408 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
409 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
410 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
411 dprintf(out, " uid is used.\n");
412 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
413 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
414 dprintf(out, "\n");
415 dprintf(out, "\n");
416 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
417 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
418 dprintf(out, "\n");
419 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
420 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
421 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
422 dprintf(out, "\n");
423 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
424 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
425 dprintf(out, " uid is used.\n");
426 dprintf(out, " NAME The per-uid name to use\n");
427 dprintf(out, "\n");
428 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
429 dprintf(out, "\n be removed from memory and disk!\n");
430 dprintf(out, "\n");
431 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800432 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
433 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700434 dprintf(out, " Dump all metric data for a configuration.\n");
435 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
436 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
437 dprintf(out, " calling uid is used.\n");
438 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800439 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700440 dprintf(out, " --proto Print proto binary.\n");
441 dprintf(out, "\n");
442 dprintf(out, "\n");
443 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
444 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
445 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
446 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
447 dprintf(out, " calling uid is used.\n");
448 dprintf(out, " NAME The name of the configuration\n");
449 dprintf(out, "\n");
450 dprintf(out, "\n");
451 dprintf(out, "usage: adb shell cmd stats print-stats\n");
452 dprintf(out, " Prints some basic stats.\n");
453 dprintf(out, " --proto Print proto binary instead of string format.\n");
454 dprintf(out, "\n");
455 dprintf(out, "\n");
456 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
457 dprintf(out, " Clear cached puller data.\n");
458 dprintf(out, "\n");
459 dprintf(out, "usage: adb shell cmd stats print-logs\n");
460 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700461}
462
Yao Chena80e5c02018-09-04 13:55:29 -0700463status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800464 string name;
465 bool good = false;
466 int uid;
467 const int argCount = args.size();
468 if (argCount == 2) {
469 // Automatically pick the UID
470 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800471 name.assign(args[1].c_str(), args[1].size());
472 good = true;
473 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800474 good = getUidFromArgs(args, 1, uid);
475 if (!good) {
476 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
477 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800478 }
Bookatzd2386572018-12-14 15:53:14 -0800479 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800480 }
481 if (!good) {
482 print_cmd_help(out);
483 return UNKNOWN_ERROR;
484 }
David Chend37bc232018-04-12 18:05:11 -0700485 ConfigKey key(uid, StrToInt64(name));
486 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800487 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800488 if (sc == nullptr) {
489 VLOG("Could not access statsCompanion");
490 } else if (receiver == nullptr) {
491 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
492 } else {
David Chend37bc232018-04-12 18:05:11 -0700493 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800494 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
495 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800496 }
497
David Chenadaf8b32017-11-03 15:42:08 -0700498 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700499}
500
Yao Chena80e5c02018-09-04 13:55:29 -0700501status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700502 const int argCount = args.size();
503 if (argCount >= 2) {
504 if (args[1] == "update" || args[1] == "remove") {
505 bool good = false;
506 int uid = -1;
507 string name;
508
509 if (argCount == 3) {
510 // Automatically pick the UID
511 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700512 name.assign(args[2].c_str(), args[2].size());
513 good = true;
514 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800515 good = getUidFromArgs(args, 2, uid);
516 if (!good) {
517 dprintf(err, "Invalid UID. Note that the config can only be set for "
518 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700519 }
Bookatzd2386572018-12-14 15:53:14 -0800520 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800521 } else if (argCount == 2 && args[1] == "remove") {
522 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700523 }
524
525 if (!good) {
526 // If arg parsing failed, print the help text and return an error.
527 print_cmd_help(out);
528 return UNKNOWN_ERROR;
529 }
530
531 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800532 char* endp;
533 int64_t configID = strtoll(name.c_str(), &endp, 10);
534 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700535 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800536 return UNKNOWN_ERROR;
537 }
538
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700539 // Read stream into buffer.
540 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700541 if (!android::base::ReadFdToString(in, &buffer)) {
542 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700543 return UNKNOWN_ERROR;
544 }
545
546 // Parse buffer.
547 StatsdConfig config;
548 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700549 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700550 return UNKNOWN_ERROR;
551 }
552
553 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800554 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700555 } else {
yro74fed972017-11-27 14:42:42 -0800556 if (argCount == 2) {
557 cmd_remove_all_configs(out);
558 } else {
559 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800560 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800561 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700562 }
563
564 return NO_ERROR;
565 }
David Chen0656b7a2017-09-13 15:53:39 -0700566 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700567 print_cmd_help(out);
568 return UNKNOWN_ERROR;
569}
570
Bookatzff71cad2018-09-20 17:17:49 -0700571status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700572 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800573 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700574 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800575 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700576 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800577 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700578 int uid;
579 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800580 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
581 proto = true;
582 argCount -= 1;
583 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700584 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
585 includeCurrentBucket = true;
586 argCount -= 1;
587 }
Bookatz3e906582018-12-10 17:26:58 -0800588 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
589 eraseData = false;
590 argCount -= 1;
591 }
Yao Chen729093d2017-10-16 10:33:26 -0700592 if (argCount == 2) {
593 // Automatically pick the UID
594 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700595 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700596 good = true;
597 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800598 good = getUidFromArgs(args, 1, uid);
599 if (!good) {
600 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
601 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700602 }
Bookatzd2386572018-12-14 15:53:14 -0800603 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700604 }
605 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800606 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800607 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Bookatz3e906582018-12-10 17:26:58 -0800608 includeCurrentBucket, eraseData, ADB_DUMP, &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800609 if (proto) {
610 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700611 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800612 }
613 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700614 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800615 }
Yao Chen729093d2017-10-16 10:33:26 -0700616 return android::OK;
617 } else {
618 // If arg parsing failed, print the help text and return an error.
619 print_cmd_help(out);
620 return UNKNOWN_ERROR;
621 }
622 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700623 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700624 return UNKNOWN_ERROR;
625 }
626}
627
Yao Chena80e5c02018-09-04 13:55:29 -0700628status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700629 int argCount = args.size();
630 bool proto = false;
631 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
632 proto = true;
633 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800634 }
Yao Chenb3561512017-11-21 18:07:17 -0800635 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700636 if (proto) {
637 vector<uint8_t> data;
638 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
639 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700640 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700641 }
642
643 } else {
644 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
645 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700646 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700647 mProcessor->GetMetricsSize(key));
648 }
649 statsdStats.dumpStats(out);
650 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800651 return NO_ERROR;
652}
653
Yao Chena80e5c02018-09-04 13:55:29 -0700654status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800655 if (args.size() > 1) {
656 string pkg;
657 pkg.assign(args[1].c_str(), args[1].size());
658 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700659 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800660 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700661 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800662 }
Yao Chena80e5c02018-09-04 13:55:29 -0700663 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800664 } else {
665 mUidMap->printUidMap(out);
666 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700667 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700668}
669
Yao Chena80e5c02018-09-04 13:55:29 -0700670status_t StatsService::cmd_write_data_to_disk(int out) {
671 dprintf(out, "Writing data to disk\n");
Yangster-mac892f3d32018-05-02 14:16:48 -0700672 mProcessor->WriteDataToDisk(ADB_DUMP);
yro947fbce2017-11-15 22:50:23 -0800673 return NO_ERROR;
674}
675
Yao Chena80e5c02018-09-04 13:55:29 -0700676status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800677 bool good = false;
678 int32_t uid;
679 int32_t label;
680 int32_t state;
681 const int argCount = args.size();
682 if (argCount == 3) {
683 // Automatically pick the UID
684 uid = IPCThreadState::self()->getCallingUid();
685 label = atoi(args[1].c_str());
686 state = atoi(args[2].c_str());
687 good = true;
688 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800689 good = getUidFromArgs(args, 1, uid);
690 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700691 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800692 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
693 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800694 }
Bookatzd2386572018-12-14 15:53:14 -0800695 label = atoi(args[2].c_str());
696 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800697 }
698 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700699 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800700 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800701 } else {
702 print_cmd_help(out);
703 return UNKNOWN_ERROR;
704 }
705 return NO_ERROR;
706}
707
Yao Chena80e5c02018-09-04 13:55:29 -0700708status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700709 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700710 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800711 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700712 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700713 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700714 }
Yao Chena80e5c02018-09-04 13:55:29 -0700715 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700716 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700717 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700718 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700719}
720
Yao Chena80e5c02018-09-04 13:55:29 -0700721status_t StatsService::cmd_remove_all_configs(int out) {
722 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800723 VLOG("StatsService::cmd_remove_all_configs was called");
724 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800725 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800726 return NO_ERROR;
727}
728
Yao Chena80e5c02018-09-04 13:55:29 -0700729status_t StatsService::cmd_dump_memory_info(int out) {
730 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800731 return NO_ERROR;
732}
733
Yao Chena80e5c02018-09-04 13:55:29 -0700734status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800735 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800736 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
737 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800738 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700739 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700740 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800741 return NO_ERROR;
742 } else {
743 return PERMISSION_DENIED;
744 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800745}
746
Yao Chena80e5c02018-09-04 13:55:29 -0700747status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700748 IPCThreadState* ipc = IPCThreadState::self();
749 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
750 ipc->getCallingUid());
751 if (checkCallingPermission(String16(kPermissionDump))) {
752 bool enabled = true;
753 if (args.size() >= 2) {
754 enabled = atoi(args[1].c_str()) != 0;
755 }
756 mProcessor->setPrintLogs(enabled);
757 return NO_ERROR;
758 } else {
759 return PERMISSION_DENIED;
760 }
761}
762
Bookatzd2386572018-12-14 15:53:14 -0800763bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
764 const char* s = args[uidArgIndex].c_str();
765 if (*s == '\0') {
766 return false;
767 }
768 char* endc = NULL;
769 int64_t longUid = strtol(s, &endc, 0);
770 if (*endc != '\0') {
771 return false;
772 }
773 int32_t goodUid = static_cast<int32_t>(longUid);
774 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
775 return false; // It was not of uid_t type.
776 }
777 uid = goodUid;
778
779 int32_t callingUid = IPCThreadState::self()->getCallingUid();
780 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
781 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
782 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
783}
784
Dianne Hackborn3accca02013-09-20 09:32:11 -0700785Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700786 const vector<String16>& version_string,
787 const vector<String16>& app,
788 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600789 ENFORCE_UID(AID_SYSTEM);
790
yro74fed972017-11-27 14:42:42 -0800791 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700792 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800793 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700794
795 return Status::ok();
796}
797
dwchen730403e2018-10-29 11:41:56 -0700798Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
799 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600800 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700801
Jeff Sharkey6b649252018-04-16 09:50:22 -0600802 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700803 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700804 return Status::ok();
805}
806
807Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600808 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700809
Jeff Sharkey6b649252018-04-16 09:50:22 -0600810 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700811 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800812 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700813 return Status::ok();
814}
815
Yao Chenef99c4f2017-09-22 16:26:54 -0700816Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600817 ENFORCE_UID(AID_SYSTEM);
818
yro74fed972017-11-27 14:42:42 -0800819 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700820 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800821 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
822 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
823 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800824 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800825 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800826 } else {
827 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
828 }
Bookatz1b0b1142017-09-08 11:58:42 -0700829 return Status::ok();
830}
831
Yangster-mac932ecec2018-02-01 10:23:52 -0800832Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600833 ENFORCE_UID(AID_SYSTEM);
834
Yangster-mac932ecec2018-02-01 10:23:52 -0800835 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700836 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800837 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
838 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
839 if (alarmSet.size() > 0) {
840 VLOG("Found periodic alarm fired.");
841 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
842 } else {
843 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
844 }
845 return Status::ok();
846}
847
Yao Chenef99c4f2017-09-22 16:26:54 -0700848Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600849 ENFORCE_UID(AID_SYSTEM);
850
yro74fed972017-11-27 14:42:42 -0800851 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700852 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800853 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700854 return Status::ok();
855}
856
Yao Chenef99c4f2017-09-22 16:26:54 -0700857Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600858 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700859
860 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800861 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700862 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700863 return Status::ok();
864}
865
Yangster-mac892f3d32018-05-02 14:16:48 -0700866Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600867 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700868 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700869 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
yro947fbce2017-11-15 22:50:23 -0800870 return Status::ok();
871}
872
Yao Chenef99c4f2017-09-22 16:26:54 -0700873void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700874 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
875 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800876 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700877 statsCompanion->statsdReady();
878 } else {
yro74fed972017-11-27 14:42:42 -0800879 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700880 }
881}
882
Yao Chenef99c4f2017-09-22 16:26:54 -0700883Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600884 ENFORCE_UID(AID_SYSTEM);
885
yro74fed972017-11-27 14:42:42 -0800886 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700887 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
888 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700889 return Status::fromExceptionCode(
890 Status::EX_NULL_POINTER,
891 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700892 }
yro74fed972017-11-27 14:42:42 -0800893 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700894 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700895 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800896 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
897 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800898 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700899 return Status::ok();
900}
901
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700902void StatsService::Startup() {
903 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700904}
905
Yangster-mac97e7d202018-10-09 11:05:39 -0700906void StatsService::Terminate() {
907 ALOGI("StatsService::Terminating");
908 if (mProcessor != nullptr) {
909 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED);
910 }
911}
912
Yao Chen3ff3a492018-08-06 16:17:37 -0700913void StatsService::OnLogEvent(LogEvent* event) {
914 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -0700915 if (mShellSubscriber != nullptr) {
916 mShellSubscriber->onLogEvent(*event);
917 }
Bookatz906a35c2017-09-20 15:26:44 -0700918}
919
Jeff Sharkey6b649252018-04-16 09:50:22 -0600920Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
921 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
922
David Chenadaf8b32017-11-03 15:42:08 -0700923 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800924 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700925 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen56ae0d92018-05-11 16:00:22 -0700926 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Bookatzff71cad2018-09-20 17:17:49 -0700927 true /* erase_data */, GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -0700928 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700929}
930
Jeff Sharkey6b649252018-04-16 09:50:22 -0600931Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
932 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
933
David Chen2e8f3802017-11-22 10:56:48 -0800934 IPCThreadState* ipc = IPCThreadState::self();
935 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
936 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700937 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
938 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -0800939}
940
Jeff Sharkey6b649252018-04-16 09:50:22 -0600941Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
942 const String16& packageName) {
943 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
944
David Chenadaf8b32017-11-03 15:42:08 -0700945 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -0700946 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -0800947 return Status::ok();
948 } else {
Bookatz4f716292018-04-10 17:15:12 -0700949 ALOGE("Could not parse malformatted StatsdConfig");
950 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
951 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -0800952 }
953}
954
David Chen9fdd4032018-03-20 14:38:56 -0700955bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
956 ConfigKey configKey(uid, key);
957 StatsdConfig cfg;
958 if (config.size() > 0) { // If the config is empty, skip parsing.
959 if (!cfg.ParseFromArray(&config[0], config.size())) {
960 return false;
961 }
962 }
963 mConfigManager->UpdateConfig(configKey, cfg);
964 return true;
965}
966
Jeff Sharkey6b649252018-04-16 09:50:22 -0600967Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
968 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
969
Bookatz4f716292018-04-10 17:15:12 -0700970 IPCThreadState* ipc = IPCThreadState::self();
971 ConfigKey configKey(ipc->getCallingUid(), key);
972 mConfigManager->RemoveConfigReceiver(configKey);
973 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -0800974}
975
Jeff Sharkey6b649252018-04-16 09:50:22 -0600976Status StatsService::setDataFetchOperation(int64_t key,
977 const sp<android::IBinder>& intentSender,
978 const String16& packageName) {
979 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
980
Bookatz4f716292018-04-10 17:15:12 -0700981 IPCThreadState* ipc = IPCThreadState::self();
982 ConfigKey configKey(ipc->getCallingUid(), key);
983 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -0700984 if (StorageManager::hasConfigMetricsReport(configKey)) {
985 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
986 configKey.ToString().c_str());
987 mProcessor->noteOnDiskData(configKey);
988 }
Bookatz4f716292018-04-10 17:15:12 -0700989 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700990}
991
Jeff Sharkey6b649252018-04-16 09:50:22 -0600992Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
993 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
994
Bookatz4f716292018-04-10 17:15:12 -0700995 IPCThreadState* ipc = IPCThreadState::self();
996 ConfigKey configKey(ipc->getCallingUid(), key);
997 mConfigManager->RemoveConfig(configKey);
998 SubscriberReporter::getInstance().removeConfig(configKey);
999 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001000}
1001
Bookatzc6977972018-01-16 16:55:05 -08001002Status StatsService::setBroadcastSubscriber(int64_t configId,
1003 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001004 const sp<android::IBinder>& intentSender,
1005 const String16& packageName) {
1006 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1007
Bookatzc6977972018-01-16 16:55:05 -08001008 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001009 IPCThreadState* ipc = IPCThreadState::self();
1010 ConfigKey configKey(ipc->getCallingUid(), configId);
1011 SubscriberReporter::getInstance()
1012 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1013 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001014}
1015
1016Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001017 int64_t subscriberId,
1018 const String16& packageName) {
1019 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1020
Bookatzc6977972018-01-16 16:55:05 -08001021 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001022 IPCThreadState* ipc = IPCThreadState::self();
1023 ConfigKey configKey(ipc->getCallingUid(), configId);
1024 SubscriberReporter::getInstance()
1025 .unsetBroadcastSubscriber(configKey, subscriberId);
1026 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001027}
1028
yrobe6d7f92018-05-04 13:02:53 -07001029Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1030 // Permission check not necessary as it's meant for applications to write to
1031 // statsd.
1032 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1033 IPCThreadState::self()->getCallingUid(), label,
1034 state);
1035 return Status::ok();
1036}
1037
Howard Roa46b6582018-09-18 16:45:02 -07001038hardware::Return<void> StatsService::reportSpeakerImpedance(
1039 const SpeakerImpedance& speakerImpedance) {
1040 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speakerImpedance);
1041 mProcessor->OnLogEvent(&event);
1042
1043 return hardware::Void();
1044}
1045
1046hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
1047 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), hardwareFailed);
1048 mProcessor->OnLogEvent(&event);
1049
1050 return hardware::Void();
1051}
1052
1053hardware::Return<void> StatsService::reportPhysicalDropDetected(
1054 const PhysicalDropDetected& physicalDropDetected) {
1055 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), physicalDropDetected);
1056 mProcessor->OnLogEvent(&event);
1057
1058 return hardware::Void();
1059}
1060
1061hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
1062 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), chargeCycles);
1063 mProcessor->OnLogEvent(&event);
1064
1065 return hardware::Void();
1066}
1067
1068hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1069 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
1070 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(),
1071 batteryHealthSnapshotArgs);
1072 mProcessor->OnLogEvent(&event);
1073
1074 return hardware::Void();
1075}
1076
1077hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
1078 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), slowIo);
1079 mProcessor->OnLogEvent(&event);
1080
1081 return hardware::Void();
1082}
1083
1084hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1085 const BatteryCausedShutdown& batteryCausedShutdown) {
1086 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), batteryCausedShutdown);
1087 mProcessor->OnLogEvent(&event);
1088
1089 return hardware::Void();
1090}
1091
David Chen1d7b0cd2017-11-15 14:20:04 -08001092void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001093 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001094 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1095 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001096 ALOGW("Reset statsd upon system server restarts.");
Yangster-mac892f3d32018-05-02 14:16:48 -07001097 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
1098 mProcessor->resetConfigs();
1099 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001100 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1101 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1102 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001103 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001104}
1105
Yao Chenef99c4f2017-09-22 16:26:54 -07001106} // namespace statsd
1107} // namespace os
1108} // namespace android