blob: 31994e1a92d1953409427341a1be6603a54f8e1a [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
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700178 // TODO: Proto format for incident reports
179 dump_impl(out);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700180
181 fclose(out);
182 return NO_ERROR;
183}
184
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700185/**
186 * Write debugging data about statsd in text format.
187 */
188void StatsService::dump_impl(FILE* out) {
189 mConfigManager->Dump(out);
Yao Chenf5acabe2018-01-17 14:10:34 -0800190 StatsdStats::getInstance().dumpStats(out);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700191}
192
193/**
194 * Implementation of the adb shell cmd stats command.
195 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700196status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700197 // TODO: Permission check
198
199 const int argCount = args.size();
200 if (argCount >= 1) {
201 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700202 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700203 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700204 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700205
David Chende701692017-10-05 13:16:02 -0700206 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800207 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700208 }
Yao Chen729093d2017-10-16 10:33:26 -0700209
210 if (!args[0].compare(String8("dump-report"))) {
211 return cmd_dump_report(out, err, args);
212 }
David Chen1481fe12017-10-16 13:16:34 -0700213
214 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
215 return cmd_print_pulled_metrics(out, args);
216 }
David Chenadaf8b32017-11-03 15:42:08 -0700217
218 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800219 return cmd_trigger_broadcast(out, args);
220 }
221
222 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800223 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700224 }
yro87d983c2017-11-14 21:31:43 -0800225
Yao Chen8d9989b2017-11-18 18:54:50 -0800226 if (!args[0].compare(String8("meminfo"))) {
227 return cmd_dump_memory_info(out);
228 }
yro947fbce2017-11-15 22:50:23 -0800229
230 if (!args[0].compare(String8("write-to-disk"))) {
231 return cmd_write_data_to_disk(out);
232 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700233 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700234
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700235 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700236 return NO_ERROR;
237}
238
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700239void StatsService::print_cmd_help(FILE* out) {
240 fprintf(out,
241 "usage: adb shell cmd stats print-stats-log [tag_required] "
242 "[timestamp_nsec_optional]\n");
243 fprintf(out, "\n");
244 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800245 fprintf(out, "usage: adb shell cmd stats meminfo\n");
246 fprintf(out, "\n");
247 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
248 fprintf(out, " # adb shell stop\n");
249 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
250 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
251 fprintf(out, " # adb shell start\n");
252 fprintf(out, "\n");
253 fprintf(out, "\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800254 fprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700255 fprintf(out, "\n");
256 fprintf(out, " Prints the UID, app name, version mapping.\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800257 fprintf(out, " PKG Optional package name to print the uids of the package\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700258 fprintf(out, "\n");
259 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800260 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700261 fprintf(out, "\n");
262 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
263 fprintf(out, "\n");
264 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800265 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
266 fprintf(out, "\n");
267 fprintf(out, " Flushes all data on memory to disk.\n");
268 fprintf(out, "\n");
269 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800270 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700271 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
272 fprintf(out, "\n");
273 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800274 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
275 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700276 fprintf(out, "\n");
277 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800278 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700279 fprintf(out, " uid is used.\n");
280 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a372017-10-30 22:57:06 -0700281 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800282 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
283 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a372017-10-30 22:57:06 -0700284 fprintf(out, "\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800285 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a372017-10-30 22:57:06 -0700286 fprintf(out, " Dump all metric data for a configuration.\n");
287 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
288 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
289 fprintf(out, " calling uid is used.\n");
290 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800291 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700292 fprintf(out, "\n");
293 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800294 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
295 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
296 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
297 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
298 fprintf(out, " calling uid is used.\n");
299 fprintf(out, " NAME The name of the configuration\n");
300 fprintf(out, "\n");
301 fprintf(out, "\n");
Yao Chenf5acabe2018-01-17 14:10:34 -0800302 fprintf(out, "usage: adb shell cmd stats print-stats\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800303 fprintf(out, " Prints some basic stats.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700304}
305
David Chen1d7b0cd2017-11-15 14:20:04 -0800306status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
307 string name;
308 bool good = false;
309 int uid;
310 const int argCount = args.size();
311 if (argCount == 2) {
312 // Automatically pick the UID
313 uid = IPCThreadState::self()->getCallingUid();
314 // TODO: What if this isn't a binder call? Should we fail?
315 name.assign(args[1].c_str(), args[1].size());
316 good = true;
317 } else if (argCount == 3) {
318 // If it's a userdebug or eng build, then the shell user can
319 // impersonate other uids.
320 if (mEngBuild) {
321 const char* s = args[1].c_str();
322 if (*s != '\0') {
323 char* end = NULL;
324 uid = strtol(s, &end, 0);
325 if (*end == '\0') {
326 name.assign(args[2].c_str(), args[2].size());
327 good = true;
328 }
329 }
330 } else {
331 fprintf(out,
332 "The metrics can only be dumped for other UIDs on eng or userdebug "
333 "builds.\n");
334 }
335 }
336 if (!good) {
337 print_cmd_help(out);
338 return UNKNOWN_ERROR;
339 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800340 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, StrToInt64(name)));
yro4d889e62017-11-17 15:44:48 -0800341 sp<IStatsCompanionService> sc = getStatsCompanionService();
342 if (sc != nullptr) {
343 sc->sendBroadcast(String16(receiver.first.c_str()), String16(receiver.second.c_str()));
yro74fed972017-11-27 14:42:42 -0800344 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
345 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800346 } else {
yro74fed972017-11-27 14:42:42 -0800347 VLOG("Could not access statsCompanion");
yro4d889e62017-11-17 15:44:48 -0800348 }
349
David Chenadaf8b32017-11-03 15:42:08 -0700350 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700351}
352
353status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
354 const int argCount = args.size();
355 if (argCount >= 2) {
356 if (args[1] == "update" || args[1] == "remove") {
357 bool good = false;
358 int uid = -1;
359 string name;
360
361 if (argCount == 3) {
362 // Automatically pick the UID
363 uid = IPCThreadState::self()->getCallingUid();
364 // TODO: What if this isn't a binder call? Should we fail?
365 name.assign(args[2].c_str(), args[2].size());
366 good = true;
367 } else if (argCount == 4) {
368 // If it's a userdebug or eng build, then the shell user can
369 // impersonate other uids.
370 if (mEngBuild) {
371 const char* s = args[2].c_str();
372 if (*s != '\0') {
373 char* end = NULL;
374 uid = strtol(s, &end, 0);
375 if (*end == '\0') {
376 name.assign(args[3].c_str(), args[3].size());
377 good = true;
378 }
379 }
380 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700381 fprintf(err,
382 "The config can only be set for other UIDs on eng or userdebug "
383 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700384 }
yroe5f82922018-01-22 18:37:27 -0800385 } else if (argCount == 2 && args[1] == "remove") {
386 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700387 }
388
389 if (!good) {
390 // If arg parsing failed, print the help text and return an error.
391 print_cmd_help(out);
392 return UNKNOWN_ERROR;
393 }
394
395 if (args[1] == "update") {
396 // Read stream into buffer.
397 string buffer;
398 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
399 fprintf(err, "Error reading stream for StatsConfig.\n");
400 return UNKNOWN_ERROR;
401 }
402
403 // Parse buffer.
404 StatsdConfig config;
405 if (!config.ParseFromString(buffer)) {
406 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
407 return UNKNOWN_ERROR;
408 }
409
410 // Add / update the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800411 mConfigManager->UpdateConfig(ConfigKey(uid, StrToInt64(name)), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700412 } else {
yro74fed972017-11-27 14:42:42 -0800413 if (argCount == 2) {
414 cmd_remove_all_configs(out);
415 } else {
416 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800417 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800418 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700419 }
420
421 return NO_ERROR;
422 }
David Chen0656b7a2017-09-13 15:53:39 -0700423 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700424 print_cmd_help(out);
425 return UNKNOWN_ERROR;
426}
427
Yao Chen729093d2017-10-16 10:33:26 -0700428status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
429 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800430 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700431 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800432 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700433 int uid;
434 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800435 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
436 proto = true;
437 argCount -= 1;
438 }
Yao Chen729093d2017-10-16 10:33:26 -0700439 if (argCount == 2) {
440 // Automatically pick the UID
441 uid = IPCThreadState::self()->getCallingUid();
442 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a372017-10-30 22:57:06 -0700443 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700444 good = true;
445 } else if (argCount == 3) {
446 // If it's a userdebug or eng build, then the shell user can
447 // impersonate other uids.
448 if (mEngBuild) {
449 const char* s = args[1].c_str();
450 if (*s != '\0') {
451 char* end = NULL;
452 uid = strtol(s, &end, 0);
453 if (*end == '\0') {
454 name.assign(args[2].c_str(), args[2].size());
455 good = true;
456 }
457 }
458 } else {
459 fprintf(out,
460 "The metrics can only be dumped for other UIDs on eng or userdebug "
461 "builds.\n");
462 }
463 }
464 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800465 vector<uint8_t> data;
Yangster-mac94e197c2018-01-02 16:03:03 -0800466 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), &data);
Yao Chen729093d2017-10-16 10:33:26 -0700467 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800468 if (proto) {
469 for (size_t i = 0; i < data.size(); i ++) {
470 fprintf(out, "%c", data[i]);
471 }
472 } else {
473 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
474 fprintf(out, "See the StatsLogReport in logcat...\n");
475 }
Yao Chen729093d2017-10-16 10:33:26 -0700476 return android::OK;
477 } else {
478 // If arg parsing failed, print the help text and return an error.
479 print_cmd_help(out);
480 return UNKNOWN_ERROR;
481 }
482 } else {
483 fprintf(out, "Log processor does not exist...\n");
484 return UNKNOWN_ERROR;
485 }
486}
487
Yao Chenb3561512017-11-21 18:07:17 -0800488status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800489 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
490 for (const ConfigKey& key : configs) {
491 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
492 mProcessor->GetMetricsSize(key));
493 }
Yao Chenb3561512017-11-21 18:07:17 -0800494 StatsdStats& statsdStats = StatsdStats::getInstance();
Yao Chenf5acabe2018-01-17 14:10:34 -0800495 statsdStats.dumpStats(out);
David Chen1d7b0cd2017-11-15 14:20:04 -0800496 return NO_ERROR;
497}
498
Yao Chend10f7b12017-12-18 12:53:50 -0800499status_t StatsService::cmd_print_uid_map(FILE* out, const Vector<String8>& args) {
500 if (args.size() > 1) {
501 string pkg;
502 pkg.assign(args[1].c_str(), args[1].size());
503 auto uids = mUidMap->getAppUid(pkg);
504 fprintf(out, "%s -> [ ", pkg.c_str());
505 for (const auto& uid : uids) {
506 fprintf(out, "%d ", uid);
507 }
508 fprintf(out, "]\n");
509 } else {
510 mUidMap->printUidMap(out);
511 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700512 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700513}
514
yro947fbce2017-11-15 22:50:23 -0800515status_t StatsService::cmd_write_data_to_disk(FILE* out) {
516 fprintf(out, "Writing data to disk\n");
517 mProcessor->WriteDataToDisk();
518 return NO_ERROR;
519}
520
David Chen1481fe12017-10-16 13:16:34 -0700521status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
522 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700523 vector<shared_ptr<LogEvent> > stats;
524 if (mStatsPullerManager.Pull(s, &stats)) {
525 for (const auto& it : stats) {
526 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
527 }
528 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
529 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700530 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700531 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700532}
533
yro74fed972017-11-27 14:42:42 -0800534status_t StatsService::cmd_remove_all_configs(FILE* out) {
535 fprintf(out, "Removing all configs...\n");
536 VLOG("StatsService::cmd_remove_all_configs was called");
537 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800538 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800539 return NO_ERROR;
540}
541
Yao Chen8d9989b2017-11-18 18:54:50 -0800542status_t StatsService::cmd_dump_memory_info(FILE* out) {
543 std::string s = dumpMemInfo(100);
544 fprintf(out, "Memory Info\n");
545 fprintf(out, "%s", s.c_str());
546 return NO_ERROR;
547}
548
Dianne Hackborn3accca02013-09-20 09:32:11 -0700549Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700550 const vector<String16>& app) {
yro74fed972017-11-27 14:42:42 -0800551 VLOG("StatsService::informAllUidData was called");
David Chende701692017-10-05 13:16:02 -0700552
553 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
554 return Status::fromExceptionCode(Status::EX_SECURITY,
555 "Only system uid can call informAllUidData");
556 }
557
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700558 mUidMap->updateMap(uid, version, app);
yro74fed972017-11-27 14:42:42 -0800559 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700560
561 return Status::ok();
562}
563
Dianne Hackborn3accca02013-09-20 09:32:11 -0700564Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
yro74fed972017-11-27 14:42:42 -0800565 VLOG("StatsService::informOnePackage was called");
David Chende701692017-10-05 13:16:02 -0700566
567 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
568 return Status::fromExceptionCode(Status::EX_SECURITY,
569 "Only system uid can call informOnePackage");
570 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700571 mUidMap->updateApp(app, uid, version);
David Chende701692017-10-05 13:16:02 -0700572 return Status::ok();
573}
574
575Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
yro74fed972017-11-27 14:42:42 -0800576 VLOG("StatsService::informOnePackageRemoved 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 informOnePackageRemoved");
581 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700582 mUidMap->removeApp(app, uid);
David Chende701692017-10-05 13:16:02 -0700583 return Status::ok();
584}
585
Yao Chenef99c4f2017-09-22 16:26:54 -0700586Status StatsService::informAnomalyAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800587 VLOG("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700588
589 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
590 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700591 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700592 }
593
yro74fed972017-11-27 14:42:42 -0800594 VLOG("StatsService::informAnomalyAlarmFired succeeded");
Bookatzcc5adef2017-11-21 14:36:23 -0800595 uint64_t currentTimeSec = time(nullptr);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800596 std::unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet =
Bookatzcc5adef2017-11-21 14:36:23 -0800597 mAnomalyMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
598 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, anomalySet);
Bookatz1b0b1142017-09-08 11:58:42 -0700599 return Status::ok();
600}
601
Yao Chenef99c4f2017-09-22 16:26:54 -0700602Status StatsService::informPollAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800603 VLOG("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700604
605 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
606 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700607 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700608 }
609
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700610 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700611
yro74fed972017-11-27 14:42:42 -0800612 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700613
614 return Status::ok();
615}
616
Yao Chenef99c4f2017-09-22 16:26:54 -0700617Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700618 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
619 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700620 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700621 }
622
623 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800624 VLOG("StatsService::systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700625
Bookatzb487b552017-09-18 11:26:01 -0700626 sayHiToStatsCompanion();
627
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700628 return Status::ok();
629}
630
yro947fbce2017-11-15 22:50:23 -0800631Status StatsService::writeDataToDisk() {
632 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
633 return Status::fromExceptionCode(Status::EX_SECURITY,
634 "Only system uid can call systemRunning");
635 }
636
yro74fed972017-11-27 14:42:42 -0800637 VLOG("StatsService::writeDataToDisk");
yro947fbce2017-11-15 22:50:23 -0800638
639 mProcessor->WriteDataToDisk();
640
641 return Status::ok();
642}
643
Yao Chenef99c4f2017-09-22 16:26:54 -0700644void StatsService::sayHiToStatsCompanion() {
645 // TODO: This method needs to be private. It is temporarily public and unsecured for testing
646 // purposes.
Bookatzb487b552017-09-18 11:26:01 -0700647 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
648 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800649 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700650 statsCompanion->statsdReady();
651 } else {
yro74fed972017-11-27 14:42:42 -0800652 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700653 }
654}
655
Yao Chenef99c4f2017-09-22 16:26:54 -0700656sp<IStatsCompanionService> StatsService::getStatsCompanionService() {
Bookatz906a35c2017-09-20 15:26:44 -0700657 sp<IStatsCompanionService> statsCompanion = nullptr;
658 // Get statscompanion service from service manager
659 const sp<IServiceManager> sm(defaultServiceManager());
660 if (sm != nullptr) {
661 const String16 name("statscompanion");
662 statsCompanion = interface_cast<IStatsCompanionService>(sm->checkService(name));
663 if (statsCompanion == nullptr) {
664 ALOGW("statscompanion service unavailable!");
665 return nullptr;
666 }
667 }
668 return statsCompanion;
669}
670
Yao Chenef99c4f2017-09-22 16:26:54 -0700671Status StatsService::statsCompanionReady() {
yro74fed972017-11-27 14:42:42 -0800672 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700673
674 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
675 return Status::fromExceptionCode(Status::EX_SECURITY,
676 "Only system uid can call statsCompanionReady");
677 }
678
679 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
680 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700681 return Status::fromExceptionCode(
682 Status::EX_NULL_POINTER,
683 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700684 }
yro74fed972017-11-27 14:42:42 -0800685 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700686 IInterface::asBinder(statsCompanion)->linkToDeath(new CompanionDeathRecipient(mAnomalyMonitor));
Bookatzb487b552017-09-18 11:26:01 -0700687 mAnomalyMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800688 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700689
690 return Status::ok();
691}
692
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700693void StatsService::Startup() {
694 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700695}
696
Yangster-macd40053e2018-01-09 16:29:22 -0800697void StatsService::OnLogEvent(LogEvent* event) {
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700698 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700699}
700
Yangster-mac94e197c2018-01-02 16:03:03 -0800701Status StatsService::getData(int64_t key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700702 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800703 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Yao Chen7ee94152017-11-17 09:44:40 -0800704 if (checkCallingPermission(String16(kPermissionDump))) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800705 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800706 mProcessor->onDumpReport(configKey, output);
David Chenadaf8b32017-11-03 15:42:08 -0700707 return Status::ok();
708 } else {
709 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
710 }
yro31eb67b2017-10-24 13:33:21 -0700711}
712
David Chen2e8f3802017-11-22 10:56:48 -0800713Status StatsService::getMetadata(vector<uint8_t>* output) {
714 IPCThreadState* ipc = IPCThreadState::self();
715 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
716 ipc->getCallingUid());
717 if (checkCallingPermission(String16(kPermissionDump))) {
718 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
719 return Status::ok();
720 } else {
721 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
722 }
723}
724
Yangster-mac94e197c2018-01-02 16:03:03 -0800725Status StatsService::addConfiguration(int64_t key,
David Chenadaf8b32017-11-03 15:42:08 -0700726 const vector <uint8_t>& config,
727 const String16& package, const String16& cls,
728 bool* success) {
729 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800730 if (checkCallingPermission(String16(kPermissionDump))) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800731 ConfigKey configKey(ipc->getCallingUid(), key);
David Chenadaf8b32017-11-03 15:42:08 -0700732 StatsdConfig cfg;
Yangster-macbbd056a2018-01-22 13:37:02 -0800733 if (config.empty() || !cfg.ParseFromArray(&config[0], config.size())) {
David Chen7d8aa4d2017-12-27 13:37:01 -0800734 *success = false;
735 return Status::ok();
736 }
David Chenadaf8b32017-11-03 15:42:08 -0700737 mConfigManager->UpdateConfig(configKey, cfg);
738 mConfigManager->SetConfigReceiver(configKey, string(String8(package).string()),
739 string(String8(cls).string()));
740 *success = true;
741 return Status::ok();
742 } else {
Yao Chenaa39bc72017-12-01 11:16:50 -0800743 *success = false;
David Chenadaf8b32017-11-03 15:42:08 -0700744 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700745 }
yro31eb67b2017-10-24 13:33:21 -0700746}
747
Yangster-mac94e197c2018-01-02 16:03:03 -0800748Status StatsService::removeConfiguration(int64_t key, bool* success) {
David Chenadaf8b32017-11-03 15:42:08 -0700749 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800750 if (checkCallingPermission(String16(kPermissionDump))) {
Bookatzc6977972018-01-16 16:55:05 -0800751 ConfigKey configKey(ipc->getCallingUid(), key);
752 mConfigManager->RemoveConfig(configKey);
753 SubscriberReporter::getInstance().removeConfig(configKey);
Yao Chenaa39bc72017-12-01 11:16:50 -0800754 *success = true;
David Chenadaf8b32017-11-03 15:42:08 -0700755 return Status::ok();
756 } else {
757 *success = false;
758 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700759 }
yro31eb67b2017-10-24 13:33:21 -0700760}
761
Bookatzc6977972018-01-16 16:55:05 -0800762Status StatsService::setBroadcastSubscriber(int64_t configId,
763 int64_t subscriberId,
764 const sp<android::IBinder>& intentSender,
765 bool* success) {
766 VLOG("StatsService::setBroadcastSubscriber called.");
767 IPCThreadState* ipc = IPCThreadState::self();
768 if (checkCallingPermission(String16(kPermissionDump))) {
769 ConfigKey configKey(ipc->getCallingUid(), configId);
770 SubscriberReporter::getInstance()
771 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
772 *success = true;
773 return Status::ok();
774 } else {
775 *success = false;
776 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
777 }
778}
779
780Status StatsService::unsetBroadcastSubscriber(int64_t configId,
781 int64_t subscriberId,
782 bool* success) {
783 VLOG("StatsService::unsetBroadcastSubscriber called.");
784 IPCThreadState* ipc = IPCThreadState::self();
785 if (checkCallingPermission(String16(kPermissionDump))) {
786 ConfigKey configKey(ipc->getCallingUid(), configId);
787 SubscriberReporter::getInstance()
788 .unsetBroadcastSubscriber(configKey, subscriberId);
789 *success = true;
790 return Status::ok();
791 } else {
792 *success = false;
793 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
794 }
795}
796
797
David Chen1d7b0cd2017-11-15 14:20:04 -0800798void StatsService::binderDied(const wp <IBinder>& who) {
yro31eb67b2017-10-24 13:33:21 -0700799}
800
Yao Chenef99c4f2017-09-22 16:26:54 -0700801} // namespace statsd
802} // namespace os
803} // namespace android