blob: 4e4145439e25c0141b1738e0af60984154d58833 [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
yro74fed972017-11-27 14:42:42 -080017#define DEBUG true // 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"
Yao Chen8d9989b2017-11-18 18:54:50 -080021#include "android-base/stringprintf.h"
David Chenadaf8b32017-11-03 15:42:08 -070022#include "config/ConfigKey.h"
23#include "config/ConfigManager.h"
Yao Chen8d9989b2017-11-18 18:54:50 -080024#include "guardrail/MemoryLeakTrackUtil.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>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070030#include <binder/IPCThreadState.h>
31#include <binder/IServiceManager.h>
yro87d983c2017-11-14 21:31:43 -080032#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070033#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070034#include <private/android_filesystem_config.h>
35#include <utils/Looper.h>
Joe Onorato2cbc2cc2017-08-30 17:03:23 -070036#include <utils/String16.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070037#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070038#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070039#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070040#include <unistd.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070041
42using namespace android;
43
Bookatz906a35c2017-09-20 15:26:44 -070044namespace android {
45namespace os {
46namespace statsd {
47
David Chenadaf8b32017-11-03 15:42:08 -070048constexpr const char* kPermissionDump = "android.permission.DUMP";
yro03faf092017-12-12 00:17:50 -080049#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070050
Joe Onorato9fc9edf2017-10-15 20:08:52 -070051// ======================================================================
52/**
53 * Watches for the death of the stats companion (system process).
54 */
55class CompanionDeathRecipient : public IBinder::DeathRecipient {
56public:
57 CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor);
58 virtual void binderDied(const wp<IBinder>& who);
59
60private:
61 const sp<AnomalyMonitor> mAnomalyMonitor;
62};
63
64CompanionDeathRecipient::CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor)
65 : mAnomalyMonitor(anomalyMonitor) {
66}
67
68void CompanionDeathRecipient::binderDied(const wp<IBinder>& who) {
69 ALOGW("statscompanion service died");
70 mAnomalyMonitor->setStatsCompanionService(nullptr);
Bookatzc6977972018-01-16 16:55:05 -080071 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Joe Onorato9fc9edf2017-10-15 20:08:52 -070072}
73
74// ======================================================================
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070075StatsService::StatsService(const sp<Looper>& handlerLooper)
Bookatz1d0136d2017-12-01 11:13:32 -080076 : mAnomalyMonitor(new AnomalyMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS))
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070077{
Joe Onorato9fc9edf2017-10-15 20:08:52 -070078 mUidMap = new UidMap();
79 mConfigManager = new ConfigManager();
Yangster-mac20877162017-12-22 17:19:39 -080080 mProcessor = new StatsLogProcessor(mUidMap, mAnomalyMonitor, time(nullptr), [this](const ConfigKey& key) {
yro947fbce2017-11-15 22:50:23 -080081 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen1d7b0cd2017-11-15 14:20:04 -080082 auto receiver = mConfigManager->GetConfigReceiver(key);
83 if (sc == nullptr) {
yro74fed972017-11-27 14:42:42 -080084 VLOG("Could not find StatsCompanionService");
David Chen1d7b0cd2017-11-15 14:20:04 -080085 } else if (receiver.first.size() == 0) {
yro74fed972017-11-27 14:42:42 -080086 VLOG("Statscompanion could not find a broadcast receiver for %s",
87 key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -080088 } else {
89 sc->sendBroadcast(String16(receiver.first.c_str()),
90 String16(receiver.second.c_str()));
91 }
yro31eb67b2017-10-24 13:33:21 -070092 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -070093
94 mConfigManager->AddListener(mProcessor);
95
96 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070097}
98
Yao Chenef99c4f2017-09-22 16:26:54 -070099StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700100}
101
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700102void StatsService::init_system_properties() {
103 mEngBuild = false;
104 const prop_info* buildType = __system_property_find("ro.build.type");
105 if (buildType != NULL) {
106 __system_property_read_callback(buildType, init_build_type_callback, this);
107 }
David Chen0656b7a2017-09-13 15:53:39 -0700108}
109
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700110void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
111 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700112 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700113 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
114 }
115}
116
117/**
118 * Implement our own because the default binder implementation isn't
119 * properly handling SHELL_COMMAND_TRANSACTION.
120 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700121status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
122 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700123 status_t err;
124
125 switch (code) {
126 case SHELL_COMMAND_TRANSACTION: {
127 int in = data.readFileDescriptor();
128 int out = data.readFileDescriptor();
129 int err = data.readFileDescriptor();
130 int argc = data.readInt32();
131 Vector<String8> args;
132 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
133 args.add(String8(data.readString16()));
134 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700135 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
136 sp<IResultReceiver> resultReceiver =
137 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700138
139 FILE* fin = fdopen(in, "r");
140 FILE* fout = fdopen(out, "w");
141 FILE* ferr = fdopen(err, "w");
142
143 if (fin == NULL || fout == NULL || ferr == NULL) {
144 resultReceiver->send(NO_MEMORY);
145 } else {
146 err = command(fin, fout, ferr, args);
147 resultReceiver->send(err);
148 }
149
150 if (fin != NULL) {
151 fflush(fin);
152 fclose(fin);
153 }
154 if (fout != NULL) {
155 fflush(fout);
156 fclose(fout);
157 }
158 if (fout != NULL) {
159 fflush(ferr);
160 fclose(ferr);
161 }
162
163 return NO_ERROR;
164 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700165 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700166 }
167}
168
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700169/**
170 * Write debugging data about statsd.
171 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700172status_t StatsService::dump(int fd, const Vector<String16>& args) {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700173 FILE* out = fdopen(fd, "w");
174 if (out == NULL) {
175 return NO_MEMORY; // the fd is already open
176 }
177
Yao Chen884c8c12018-01-26 10:36:25 -0800178 bool verbose = false;
179 if (args.size() > 0 && !args[0].compare(String16("-v"))) {
180 verbose = true;
181 }
182
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700183 // TODO: Proto format for incident reports
Yao Chen884c8c12018-01-26 10:36:25 -0800184 dump_impl(out, verbose);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700185
186 fclose(out);
187 return NO_ERROR;
188}
189
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700190/**
191 * Write debugging data about statsd in text format.
192 */
Yao Chen884c8c12018-01-26 10:36:25 -0800193void StatsService::dump_impl(FILE* out, bool verbose) {
Yao Chenf5acabe2018-01-17 14:10:34 -0800194 StatsdStats::getInstance().dumpStats(out);
Yao Chen884c8c12018-01-26 10:36:25 -0800195 mProcessor->dumpStates(out, verbose);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700196}
197
198/**
199 * Implementation of the adb shell cmd stats command.
200 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700201status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700202 // TODO: Permission check
203
204 const int argCount = args.size();
205 if (argCount >= 1) {
206 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700207 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700208 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700209 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700210
David Chende701692017-10-05 13:16:02 -0700211 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800212 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700213 }
Yao Chen729093d2017-10-16 10:33:26 -0700214
215 if (!args[0].compare(String8("dump-report"))) {
216 return cmd_dump_report(out, err, args);
217 }
David Chen1481fe12017-10-16 13:16:34 -0700218
219 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
220 return cmd_print_pulled_metrics(out, args);
221 }
David Chenadaf8b32017-11-03 15:42:08 -0700222
223 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800224 return cmd_trigger_broadcast(out, args);
225 }
226
227 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800228 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700229 }
yro87d983c2017-11-14 21:31:43 -0800230
Yao Chen8d9989b2017-11-18 18:54:50 -0800231 if (!args[0].compare(String8("meminfo"))) {
232 return cmd_dump_memory_info(out);
233 }
yro947fbce2017-11-15 22:50:23 -0800234
235 if (!args[0].compare(String8("write-to-disk"))) {
236 return cmd_write_data_to_disk(out);
237 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700238 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700239
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700240 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700241 return NO_ERROR;
242}
243
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700244void StatsService::print_cmd_help(FILE* out) {
245 fprintf(out,
246 "usage: adb shell cmd stats print-stats-log [tag_required] "
247 "[timestamp_nsec_optional]\n");
248 fprintf(out, "\n");
249 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800250 fprintf(out, "usage: adb shell cmd stats meminfo\n");
251 fprintf(out, "\n");
252 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
253 fprintf(out, " # adb shell stop\n");
254 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
255 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
256 fprintf(out, " # adb shell start\n");
257 fprintf(out, "\n");
258 fprintf(out, "\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800259 fprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700260 fprintf(out, "\n");
261 fprintf(out, " Prints the UID, app name, version mapping.\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800262 fprintf(out, " PKG Optional package name to print the uids of the package\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700263 fprintf(out, "\n");
264 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800265 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700266 fprintf(out, "\n");
267 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
268 fprintf(out, "\n");
269 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800270 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
271 fprintf(out, "\n");
272 fprintf(out, " Flushes all data on memory to disk.\n");
273 fprintf(out, "\n");
274 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800275 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700276 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
277 fprintf(out, "\n");
278 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800279 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
280 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700281 fprintf(out, "\n");
282 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800283 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700284 fprintf(out, " uid is used.\n");
285 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700286 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800287 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
288 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700289 fprintf(out, "\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800290 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700291 fprintf(out, " Dump all metric data for a configuration.\n");
292 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
293 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
294 fprintf(out, " calling uid is used.\n");
295 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800296 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700297 fprintf(out, "\n");
298 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800299 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
300 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
301 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
302 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
303 fprintf(out, " calling uid is used.\n");
304 fprintf(out, " NAME The name of the configuration\n");
305 fprintf(out, "\n");
306 fprintf(out, "\n");
Yao Chenf5acabe2018-01-17 14:10:34 -0800307 fprintf(out, "usage: adb shell cmd stats print-stats\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800308 fprintf(out, " Prints some basic stats.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700309}
310
David Chen1d7b0cd2017-11-15 14:20:04 -0800311status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
312 string name;
313 bool good = false;
314 int uid;
315 const int argCount = args.size();
316 if (argCount == 2) {
317 // Automatically pick the UID
318 uid = IPCThreadState::self()->getCallingUid();
319 // TODO: What if this isn't a binder call? Should we fail?
320 name.assign(args[1].c_str(), args[1].size());
321 good = true;
322 } else if (argCount == 3) {
323 // If it's a userdebug or eng build, then the shell user can
324 // impersonate other uids.
325 if (mEngBuild) {
326 const char* s = args[1].c_str();
327 if (*s != '\0') {
328 char* end = NULL;
329 uid = strtol(s, &end, 0);
330 if (*end == '\0') {
331 name.assign(args[2].c_str(), args[2].size());
332 good = true;
333 }
334 }
335 } else {
336 fprintf(out,
337 "The metrics can only be dumped for other UIDs on eng or userdebug "
338 "builds.\n");
339 }
340 }
341 if (!good) {
342 print_cmd_help(out);
343 return UNKNOWN_ERROR;
344 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800345 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, StrToInt64(name)));
yro4d889e62017-11-17 15:44:48 -0800346 sp<IStatsCompanionService> sc = getStatsCompanionService();
347 if (sc != nullptr) {
348 sc->sendBroadcast(String16(receiver.first.c_str()), String16(receiver.second.c_str()));
yro74fed972017-11-27 14:42:42 -0800349 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
350 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800351 } else {
yro74fed972017-11-27 14:42:42 -0800352 VLOG("Could not access statsCompanion");
yro4d889e62017-11-17 15:44:48 -0800353 }
354
David Chenadaf8b32017-11-03 15:42:08 -0700355 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700356}
357
358status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
359 const int argCount = args.size();
360 if (argCount >= 2) {
361 if (args[1] == "update" || args[1] == "remove") {
362 bool good = false;
363 int uid = -1;
364 string name;
365
366 if (argCount == 3) {
367 // Automatically pick the UID
368 uid = IPCThreadState::self()->getCallingUid();
369 // TODO: What if this isn't a binder call? Should we fail?
370 name.assign(args[2].c_str(), args[2].size());
371 good = true;
372 } else if (argCount == 4) {
373 // If it's a userdebug or eng build, then the shell user can
374 // impersonate other uids.
375 if (mEngBuild) {
376 const char* s = args[2].c_str();
377 if (*s != '\0') {
378 char* end = NULL;
379 uid = strtol(s, &end, 0);
380 if (*end == '\0') {
381 name.assign(args[3].c_str(), args[3].size());
382 good = true;
383 }
384 }
385 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700386 fprintf(err,
387 "The config can only be set for other UIDs on eng or userdebug "
388 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700389 }
yroe5f82922018-01-22 18:37:27 -0800390 } else if (argCount == 2 && args[1] == "remove") {
391 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700392 }
393
394 if (!good) {
395 // If arg parsing failed, print the help text and return an error.
396 print_cmd_help(out);
397 return UNKNOWN_ERROR;
398 }
399
400 if (args[1] == "update") {
401 // Read stream into buffer.
402 string buffer;
403 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
404 fprintf(err, "Error reading stream for StatsConfig.\n");
405 return UNKNOWN_ERROR;
406 }
407
408 // Parse buffer.
409 StatsdConfig config;
410 if (!config.ParseFromString(buffer)) {
411 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
412 return UNKNOWN_ERROR;
413 }
414
415 // Add / update the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800416 mConfigManager->UpdateConfig(ConfigKey(uid, StrToInt64(name)), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700417 } else {
yro74fed972017-11-27 14:42:42 -0800418 if (argCount == 2) {
419 cmd_remove_all_configs(out);
420 } else {
421 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800422 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800423 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700424 }
425
426 return NO_ERROR;
427 }
David Chen0656b7a2017-09-13 15:53:39 -0700428 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700429 print_cmd_help(out);
430 return UNKNOWN_ERROR;
431}
432
Yao Chen729093d2017-10-16 10:33:26 -0700433status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
434 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800435 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700436 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800437 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700438 int uid;
439 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800440 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
441 proto = true;
442 argCount -= 1;
443 }
Yao Chen729093d2017-10-16 10:33:26 -0700444 if (argCount == 2) {
445 // Automatically pick the UID
446 uid = IPCThreadState::self()->getCallingUid();
447 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a3792017-10-30 22:57:06 -0700448 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700449 good = true;
450 } else if (argCount == 3) {
451 // If it's a userdebug or eng build, then the shell user can
452 // impersonate other uids.
453 if (mEngBuild) {
454 const char* s = args[1].c_str();
455 if (*s != '\0') {
456 char* end = NULL;
457 uid = strtol(s, &end, 0);
458 if (*end == '\0') {
459 name.assign(args[2].c_str(), args[2].size());
460 good = true;
461 }
462 }
463 } else {
464 fprintf(out,
465 "The metrics can only be dumped for other UIDs on eng or userdebug "
466 "builds.\n");
467 }
468 }
469 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800470 vector<uint8_t> data;
Yangster-mac94e197c2018-01-02 16:03:03 -0800471 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), &data);
Yao Chen729093d2017-10-16 10:33:26 -0700472 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800473 if (proto) {
474 for (size_t i = 0; i < data.size(); i ++) {
475 fprintf(out, "%c", data[i]);
476 }
477 } else {
478 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
479 fprintf(out, "See the StatsLogReport in logcat...\n");
480 }
Yao Chen729093d2017-10-16 10:33:26 -0700481 return android::OK;
482 } else {
483 // If arg parsing failed, print the help text and return an error.
484 print_cmd_help(out);
485 return UNKNOWN_ERROR;
486 }
487 } else {
488 fprintf(out, "Log processor does not exist...\n");
489 return UNKNOWN_ERROR;
490 }
491}
492
Yao Chenb3561512017-11-21 18:07:17 -0800493status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800494 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
495 for (const ConfigKey& key : configs) {
496 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
497 mProcessor->GetMetricsSize(key));
498 }
Yao Chenb3561512017-11-21 18:07:17 -0800499 StatsdStats& statsdStats = StatsdStats::getInstance();
Yao Chenf5acabe2018-01-17 14:10:34 -0800500 statsdStats.dumpStats(out);
David Chen1d7b0cd2017-11-15 14:20:04 -0800501 return NO_ERROR;
502}
503
Yao Chend10f7b12017-12-18 12:53:50 -0800504status_t StatsService::cmd_print_uid_map(FILE* out, const Vector<String8>& args) {
505 if (args.size() > 1) {
506 string pkg;
507 pkg.assign(args[1].c_str(), args[1].size());
508 auto uids = mUidMap->getAppUid(pkg);
509 fprintf(out, "%s -> [ ", pkg.c_str());
510 for (const auto& uid : uids) {
511 fprintf(out, "%d ", uid);
512 }
513 fprintf(out, "]\n");
514 } else {
515 mUidMap->printUidMap(out);
516 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700517 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700518}
519
yro947fbce2017-11-15 22:50:23 -0800520status_t StatsService::cmd_write_data_to_disk(FILE* out) {
521 fprintf(out, "Writing data to disk\n");
522 mProcessor->WriteDataToDisk();
523 return NO_ERROR;
524}
525
David Chen1481fe12017-10-16 13:16:34 -0700526status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
527 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700528 vector<shared_ptr<LogEvent> > stats;
529 if (mStatsPullerManager.Pull(s, &stats)) {
530 for (const auto& it : stats) {
531 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
532 }
533 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
534 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700535 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700536 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700537}
538
yro74fed972017-11-27 14:42:42 -0800539status_t StatsService::cmd_remove_all_configs(FILE* out) {
540 fprintf(out, "Removing all configs...\n");
541 VLOG("StatsService::cmd_remove_all_configs was called");
542 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800543 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800544 return NO_ERROR;
545}
546
Yao Chen8d9989b2017-11-18 18:54:50 -0800547status_t StatsService::cmd_dump_memory_info(FILE* out) {
548 std::string s = dumpMemInfo(100);
549 fprintf(out, "Memory Info\n");
550 fprintf(out, "%s", s.c_str());
551 return NO_ERROR;
552}
553
Chenjie Yue72252b2018-02-01 13:19:35 -0800554status_t StatsService::cmd_clear_puller_cache(FILE* out) {
555 mStatsPullerManager.ClearPullerCache();
556 fprintf(out, "Puller cached data removed!\n");
557 return NO_ERROR;
558}
559
Dianne Hackborn3accca02013-09-20 09:32:11 -0700560Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700561 const vector<String16>& app) {
yro74fed972017-11-27 14:42:42 -0800562 VLOG("StatsService::informAllUidData was called");
David Chende701692017-10-05 13:16:02 -0700563
564 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
565 return Status::fromExceptionCode(Status::EX_SECURITY,
566 "Only system uid can call informAllUidData");
567 }
568
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700569 mUidMap->updateMap(uid, version, app);
yro74fed972017-11-27 14:42:42 -0800570 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700571
572 return Status::ok();
573}
574
Dianne Hackborn3accca02013-09-20 09:32:11 -0700575Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
yro74fed972017-11-27 14:42:42 -0800576 VLOG("StatsService::informOnePackage was called");
David Chende701692017-10-05 13:16:02 -0700577
578 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
579 return Status::fromExceptionCode(Status::EX_SECURITY,
580 "Only system uid can call informOnePackage");
581 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700582 mUidMap->updateApp(app, uid, version);
David Chende701692017-10-05 13:16:02 -0700583 return Status::ok();
584}
585
586Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
yro74fed972017-11-27 14:42:42 -0800587 VLOG("StatsService::informOnePackageRemoved was called");
David Chende701692017-10-05 13:16:02 -0700588
589 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
590 return Status::fromExceptionCode(Status::EX_SECURITY,
591 "Only system uid can call informOnePackageRemoved");
592 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700593 mUidMap->removeApp(app, uid);
David Chende701692017-10-05 13:16:02 -0700594 return Status::ok();
595}
596
Yao Chenef99c4f2017-09-22 16:26:54 -0700597Status StatsService::informAnomalyAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800598 VLOG("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700599
600 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
601 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700602 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700603 }
604
yro74fed972017-11-27 14:42:42 -0800605 VLOG("StatsService::informAnomalyAlarmFired succeeded");
Bookatzcc5adef22017-11-21 14:36:23 -0800606 uint64_t currentTimeSec = time(nullptr);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800607 std::unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet =
Bookatzcc5adef22017-11-21 14:36:23 -0800608 mAnomalyMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
609 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, anomalySet);
Bookatz1b0b1142017-09-08 11:58:42 -0700610 return Status::ok();
611}
612
Yao Chenef99c4f2017-09-22 16:26:54 -0700613Status StatsService::informPollAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800614 VLOG("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700615
616 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
617 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700618 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700619 }
620
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700621 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700622
yro74fed972017-11-27 14:42:42 -0800623 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700624
625 return Status::ok();
626}
627
Yao Chenef99c4f2017-09-22 16:26:54 -0700628Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700629 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
630 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700631 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700632 }
633
634 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800635 VLOG("StatsService::systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700636
Bookatzb487b552017-09-18 11:26:01 -0700637 sayHiToStatsCompanion();
638
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700639 return Status::ok();
640}
641
yro947fbce2017-11-15 22:50:23 -0800642Status StatsService::writeDataToDisk() {
643 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
644 return Status::fromExceptionCode(Status::EX_SECURITY,
645 "Only system uid can call systemRunning");
646 }
647
yro74fed972017-11-27 14:42:42 -0800648 VLOG("StatsService::writeDataToDisk");
yro947fbce2017-11-15 22:50:23 -0800649
650 mProcessor->WriteDataToDisk();
651
652 return Status::ok();
653}
654
Yao Chenef99c4f2017-09-22 16:26:54 -0700655void StatsService::sayHiToStatsCompanion() {
656 // TODO: This method needs to be private. It is temporarily public and unsecured for testing
657 // purposes.
Bookatzb487b552017-09-18 11:26:01 -0700658 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
659 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800660 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700661 statsCompanion->statsdReady();
662 } else {
yro74fed972017-11-27 14:42:42 -0800663 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700664 }
665}
666
Yao Chenef99c4f2017-09-22 16:26:54 -0700667sp<IStatsCompanionService> StatsService::getStatsCompanionService() {
Bookatz906a35c2017-09-20 15:26:44 -0700668 sp<IStatsCompanionService> statsCompanion = nullptr;
669 // Get statscompanion service from service manager
670 const sp<IServiceManager> sm(defaultServiceManager());
671 if (sm != nullptr) {
672 const String16 name("statscompanion");
673 statsCompanion = interface_cast<IStatsCompanionService>(sm->checkService(name));
674 if (statsCompanion == nullptr) {
675 ALOGW("statscompanion service unavailable!");
676 return nullptr;
677 }
678 }
679 return statsCompanion;
680}
681
Yao Chenef99c4f2017-09-22 16:26:54 -0700682Status StatsService::statsCompanionReady() {
yro74fed972017-11-27 14:42:42 -0800683 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700684
685 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
686 return Status::fromExceptionCode(Status::EX_SECURITY,
687 "Only system uid can call statsCompanionReady");
688 }
689
690 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
691 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700692 return Status::fromExceptionCode(
693 Status::EX_NULL_POINTER,
694 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700695 }
yro74fed972017-11-27 14:42:42 -0800696 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700697 IInterface::asBinder(statsCompanion)->linkToDeath(new CompanionDeathRecipient(mAnomalyMonitor));
Bookatzb487b552017-09-18 11:26:01 -0700698 mAnomalyMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800699 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700700
701 return Status::ok();
702}
703
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700704void StatsService::Startup() {
705 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700706}
707
Yangster-macd40053e2018-01-09 16:29:22 -0800708void StatsService::OnLogEvent(LogEvent* event) {
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700709 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700710}
711
Yangster-mac94e197c2018-01-02 16:03:03 -0800712Status StatsService::getData(int64_t key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700713 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800714 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Yao Chen7ee94152017-11-17 09:44:40 -0800715 if (checkCallingPermission(String16(kPermissionDump))) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800716 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800717 mProcessor->onDumpReport(configKey, output);
David Chenadaf8b32017-11-03 15:42:08 -0700718 return Status::ok();
719 } else {
720 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
721 }
yro31eb67b2017-10-24 13:33:21 -0700722}
723
David Chen2e8f3802017-11-22 10:56:48 -0800724Status StatsService::getMetadata(vector<uint8_t>* output) {
725 IPCThreadState* ipc = IPCThreadState::self();
726 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
727 ipc->getCallingUid());
728 if (checkCallingPermission(String16(kPermissionDump))) {
729 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
730 return Status::ok();
731 } else {
732 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
733 }
734}
735
Yangster-mac94e197c2018-01-02 16:03:03 -0800736Status StatsService::addConfiguration(int64_t key,
David Chenadaf8b32017-11-03 15:42:08 -0700737 const vector <uint8_t>& config,
738 const String16& package, const String16& cls,
739 bool* success) {
740 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800741 if (checkCallingPermission(String16(kPermissionDump))) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800742 ConfigKey configKey(ipc->getCallingUid(), key);
David Chenadaf8b32017-11-03 15:42:08 -0700743 StatsdConfig cfg;
Yangster-macbbd056a2018-01-22 13:37:02 -0800744 if (config.empty() || !cfg.ParseFromArray(&config[0], config.size())) {
David Chen7d8aa4d2017-12-27 13:37:01 -0800745 *success = false;
746 return Status::ok();
747 }
David Chenadaf8b32017-11-03 15:42:08 -0700748 mConfigManager->UpdateConfig(configKey, cfg);
749 mConfigManager->SetConfigReceiver(configKey, string(String8(package).string()),
750 string(String8(cls).string()));
751 *success = true;
752 return Status::ok();
753 } else {
Yao Chenaa39bc72017-12-01 11:16:50 -0800754 *success = false;
David Chenadaf8b32017-11-03 15:42:08 -0700755 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700756 }
yro31eb67b2017-10-24 13:33:21 -0700757}
758
Yangster-mac94e197c2018-01-02 16:03:03 -0800759Status StatsService::removeConfiguration(int64_t key, bool* success) {
David Chenadaf8b32017-11-03 15:42:08 -0700760 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800761 if (checkCallingPermission(String16(kPermissionDump))) {
Bookatzc6977972018-01-16 16:55:05 -0800762 ConfigKey configKey(ipc->getCallingUid(), key);
763 mConfigManager->RemoveConfig(configKey);
764 SubscriberReporter::getInstance().removeConfig(configKey);
Yao Chenaa39bc72017-12-01 11:16:50 -0800765 *success = true;
David Chenadaf8b32017-11-03 15:42:08 -0700766 return Status::ok();
767 } else {
768 *success = false;
769 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700770 }
yro31eb67b2017-10-24 13:33:21 -0700771}
772
Bookatzc6977972018-01-16 16:55:05 -0800773Status StatsService::setBroadcastSubscriber(int64_t configId,
774 int64_t subscriberId,
775 const sp<android::IBinder>& intentSender,
776 bool* success) {
777 VLOG("StatsService::setBroadcastSubscriber called.");
778 IPCThreadState* ipc = IPCThreadState::self();
779 if (checkCallingPermission(String16(kPermissionDump))) {
780 ConfigKey configKey(ipc->getCallingUid(), configId);
781 SubscriberReporter::getInstance()
782 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
783 *success = true;
784 return Status::ok();
785 } else {
786 *success = false;
787 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
788 }
789}
790
791Status StatsService::unsetBroadcastSubscriber(int64_t configId,
792 int64_t subscriberId,
793 bool* success) {
794 VLOG("StatsService::unsetBroadcastSubscriber called.");
795 IPCThreadState* ipc = IPCThreadState::self();
796 if (checkCallingPermission(String16(kPermissionDump))) {
797 ConfigKey configKey(ipc->getCallingUid(), configId);
798 SubscriberReporter::getInstance()
799 .unsetBroadcastSubscriber(configKey, subscriberId);
800 *success = true;
801 return Status::ok();
802 } else {
803 *success = false;
804 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
805 }
806}
807
808
David Chen1d7b0cd2017-11-15 14:20:04 -0800809void StatsService::binderDied(const wp <IBinder>& who) {
yro31eb67b2017-10-24 13:33:21 -0700810}
811
Yao Chenef99c4f2017-09-22 16:26:54 -0700812} // namespace statsd
813} // namespace os
814} // namespace android